feat(paymentcryptography): the multi-region keys (#8541)

* feat(paymentcryptography): the multi-region keys
* fix(paymentcryptography): the multi-region replication refuses what it cannot carry out
* test(compatibility-tests): the multi-region tests leave the account as they found it
* fix(paymentcryptography): the default replication regions are the ones of the region
* test(compatibility-tests): the multi-region tests keep their settings to their own region
* docs(paymentcryptography): what the multi-region replication does
* fix(paymentcryptography): the rules the multi-region replication follows
* chore(paymentcryptography): the shape check settles the type of a list of names
* style(paymentcryptography): the accessor the edit left on one line
* docs(paymentcryptography): the page says what the replication does
* fix(paymentcryptography): the replica answers as the reference answers
* fix(paymentcryptography): a key is replicated within the partition it is in
* style(paymentcryptography): the rules the replication shares are written once
* fix(paymentcryptography): the partition of a region is the one its ARN carries
* style(paymentcryptography): the tests of the service share the key they make
* style(compatibility-tests): the compatibility tests share the key they make
This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-16 12:47:19 -04:00
1 parent c12db764e6
commit 057684feac
10 files changed
+1905 -166

No files matched your search

@@ -0,0 +1,171 @@
#!/usr/bin/env bats
# Payment Cryptography multi-region key replication tests
#
# A key that is replicated is one key with one identifier in several regions: the key is
# created in the region of the request and is the Primary Region key there, and every
# other region holds a Replica Region key with the same identifier and its own ARN. The
# tests drive the operations with the AWS CLI, which is such a client.
#
# The default replication regions are the ones of the region they are read in, so the
# test that changes them does it in a region of its own. The other tests of the suite
# create their keys in the region the command line names, and a key that is replicated
# has to be exportable, so the settings of one region must not reach the keys of another.
setup() {
load 'test_helper/common-setup'
KEY_ARN=""
SETTINGS_REGION="us-west-2"
# The default regions of the region the tests change are read before any test runs, so
# the teardown can put them back as they were.
DEFAULT_REGIONS=$(aws_cmd_in "$SETTINGS_REGION" payment-cryptography \
get-default-key-replication-regions --query 'EnabledReplicationRegions' \
--output text 2>/dev/null || true)
}
teardown() {
if [ -n "$KEY_ARN" ]; then
aws_cmd payment-cryptography delete-key --key-identifier "$KEY_ARN" \
--delete-key-in-days 7 >/dev/null 2>&1 || true
fi
# The default regions of the region the tests changed are put back as they were: the
# ones the tests turned on are turned off, and the ones that were on are turned on
# again, so a run against an account that already had one does not take it away.
local now
now=$(aws_cmd_in "$SETTINGS_REGION" payment-cryptography \
get-default-key-replication-regions --query 'EnabledReplicationRegions' \
--output text 2>/dev/null || true)
for region in $now; do
aws_cmd_in "$SETTINGS_REGION" payment-cryptography disable-default-key-replication-regions \
--replication-regions "$region" >/dev/null 2>&1 || true
done
if [ -n "$DEFAULT_REGIONS" ] && [ "$DEFAULT_REGIONS" != "None" ]; then
for region in $DEFAULT_REGIONS; do
aws_cmd_in "$SETTINGS_REGION" payment-cryptography enable-default-key-replication-regions \
--replication-regions "$region" >/dev/null 2>&1 || true
done
fi
}
# The command in a region of its own, for the operations whose settings are the ones of
# that region.
aws_cmd_in() {
local region="$1"
shift
aws --endpoint-url "$FLOCI_ENDPOINT" --region "$region" --output json "$@" 2>&1
}
# The attributes of the key the tests create.
KEY_ATTRIBUTES='KeyAlgorithm=AES_256,KeyClass=SYMMETRIC_KEY,KeyUsage=TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY,KeyModesOfUse={Encrypt=true,Decrypt=true}'
# The key that leaves the service, replicated to the regions named.
create_replicated_key() {
aws_cmd payment-cryptography create-key \
--key-attributes "$KEY_ATTRIBUTES" \
--exportable \
--replication-regions "$1" \
--query 'Key.KeyArn' --output text
}
@test "Payment Cryptography multi-region: the default replication regions are read and set" {
# The default regions of the region were read in the setup, so the teardown can put
# them back as they were.
run aws_cmd_in "$SETTINGS_REGION" payment-cryptography get-default-key-replication-regions
assert_success
[ -n "$(json_get "$output" '.EnabledReplicationRegions')" ]
run aws_cmd_in "$SETTINGS_REGION" payment-cryptography enable-default-key-replication-regions \
--replication-regions us-east-2
assert_success
[[ "$(json_get "$output" '.EnabledReplicationRegions')" == *"us-east-2"* ]]
run aws_cmd_in "$SETTINGS_REGION" payment-cryptography get-default-key-replication-regions
assert_success
[[ "$(json_get "$output" '.EnabledReplicationRegions')" == *"us-east-2"* ]]
run aws_cmd_in "$SETTINGS_REGION" payment-cryptography disable-default-key-replication-regions \
--replication-regions us-east-2
assert_success
[[ "$(json_get "$output" '.EnabledReplicationRegions')" != *"us-east-2"* ]]
}
@test "Payment Cryptography multi-region: the default replication regions are the ones of the region" {
# The settings are the ones of the region they are read in, so the region the command
# line names keeps the settings it had.
run aws_cmd_in "$SETTINGS_REGION" payment-cryptography enable-default-key-replication-regions \
--replication-regions us-east-2
assert_success
run aws_cmd payment-cryptography get-default-key-replication-regions
assert_success
[[ "$(json_get "$output" '.EnabledReplicationRegions')" != *"us-east-2"* ]]
}
@test "Payment Cryptography multi-region: a key is replicated to the regions it names" {
KEY_ARN=$(create_replicated_key us-west-2)
[ -n "$KEY_ARN" ]
run aws_cmd payment-cryptography get-key --key-identifier "$KEY_ARN"
assert_success
[ "$(json_get "$output" '.Key.MultiRegionKeyType')" = "PRIMARY" ]
[ "$(json_get "$output" '.Key.PrimaryRegion')" = "us-east-1" ]
# The status of a replica that is there is that it is in sync.
[ "$(json_get "$output" '.Key.ReplicationStatus."us-west-2".Status')" = "SYNCHRONIZED" ]
}
@test "Payment Cryptography multi-region: the regions of a key can be changed" {
KEY_ARN=$(create_replicated_key us-west-2)
[ -n "$KEY_ARN" ]
run aws_cmd payment-cryptography add-key-replication-regions \
--key-identifier "$KEY_ARN" \
--replication-regions us-west-1
assert_success
[[ "$(json_get "$output" '.Key.ReplicationStatus')" == *"us-west-1"* ]]
run aws_cmd payment-cryptography remove-key-replication-regions \
--key-identifier "$KEY_ARN" \
--replication-regions us-west-2
assert_success
[[ "$(json_get "$output" '.Key.ReplicationStatus')" != *"us-west-2"* ]]
}
@test "Payment Cryptography multi-region: a key that is replicated has to be exportable" {
# The model asks for the flag, and the CLI writes a false one as the negated flag.
run aws_cmd payment-cryptography create-key \
--key-attributes "$KEY_ATTRIBUTES" \
--no-exportable \
--replication-regions us-west-2
assert_failure
[[ "$output" == *"exportable"* ]]
}
@test "Payment Cryptography multi-region: a name that is not a region is refused" {
# A Region a request names has to be a name of a Region this service serves, and a name
# that is not one of those is refused.
run aws_cmd_in "$SETTINGS_REGION" payment-cryptography enable-default-key-replication-regions \
--replication-regions moon-west-1
assert_failure
[[ "$output" == *"moon-west-1"* ]]
}
@test "Payment Cryptography multi-region: a region of another partition is refused" {
# A key is replicated within the partition it is in, as the reference says, so a
# region of another partition is refused.
run aws_cmd payment-cryptography create-key \
--key-attributes "$KEY_ATTRIBUTES" \
--exportable \
--replication-regions cn-north-1
assert_failure
[[ "$output" == *"cn-north-1"* ]]
}
@test "Payment Cryptography multi-region: the region of the request is not a region to replicate to" {
# The key is in the region of the request already, so naming that region is a request
# that cannot be carried out.
run aws_cmd payment-cryptography create-key \
--key-attributes "$KEY_ATTRIBUTES" \
--exportable \
--replication-regions us-east-1
assert_failure
[[ "$output" == *"us-east-1"* ]]
}
@@ -1,5 +1,6 @@
package com.floci.test;
import org.assertj.core.api.ThrowableAssert.ThrowingCallable;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
@@ -11,10 +12,14 @@ import org.junit.jupiter.api.Test;
import software.amazon.awssdk.awscore.exception.AwsServiceException;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.paymentcryptography.PaymentCryptographyClient;
import software.amazon.awssdk.services.paymentcryptography.model.AddKeyReplicationRegionsResponse;
import software.amazon.awssdk.services.paymentcryptography.model.Alias;
import software.amazon.awssdk.services.paymentcryptography.model.As2805KeyVariant;
import software.amazon.awssdk.services.paymentcryptography.model.CreateKeyRequest;
import software.amazon.awssdk.services.paymentcryptography.model.DeriveKeyUsage;
import software.amazon.awssdk.services.paymentcryptography.model.EnableDefaultKeyReplicationRegionsResponse;
import software.amazon.awssdk.services.paymentcryptography.model.ExportKeyResponse;
import software.amazon.awssdk.services.paymentcryptography.model.GetDefaultKeyReplicationRegionsResponse;
import software.amazon.awssdk.services.paymentcryptography.model.GetParametersForExportResponse;
import software.amazon.awssdk.services.paymentcryptography.model.GetParametersForImportResponse;
import software.amazon.awssdk.services.paymentcryptography.model.GetPublicKeyCertificateResponse;
@@ -25,9 +30,12 @@ import software.amazon.awssdk.services.paymentcryptography.model.KeyAttributes;
import software.amazon.awssdk.services.paymentcryptography.model.KeyCheckValueAlgorithm;
import software.amazon.awssdk.services.paymentcryptography.model.KeyClass;
import software.amazon.awssdk.services.paymentcryptography.model.KeyMaterialType;
import software.amazon.awssdk.services.paymentcryptography.model.KeyReplicationState;
import software.amazon.awssdk.services.paymentcryptography.model.KeyState;
import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage;
import software.amazon.awssdk.services.paymentcryptography.model.ListKeysResponse;
import software.amazon.awssdk.services.paymentcryptography.model.MultiRegionKeyType;
import software.amazon.awssdk.services.paymentcryptography.model.RemoveKeyReplicationRegionsResponse;
import software.amazon.awssdk.services.paymentcryptography.model.Tag;
import software.amazon.awssdk.services.paymentcryptography.model.Tr34KeyBlockFormat;
import software.amazon.awssdk.services.paymentcryptography.model.WrappedKeyMaterialFormat;
@@ -45,6 +53,7 @@ import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
@@ -133,6 +142,152 @@ class PaymentCryptographyTest {
return key;
}
@Test
void aKeyIsReplicatedToTheRegionsTheAccountReplicatesToByDefault() {
// The account's own default regions are read before the test changes them, so the
// cleanup can put them back.
List<String> before = client.getDefaultKeyReplicationRegions(r -> { })
.enabledReplicationRegions();
EnableDefaultKeyReplicationRegionsResponse enabled = client.enableDefaultKeyReplicationRegions(r -> r
.replicationRegions("us-west-2"));
try {
assertThat(enabled.enabledReplicationRegions()).contains("us-west-2");
GetDefaultKeyReplicationRegionsResponse defaults = client.getDefaultKeyReplicationRegions(r -> { });
assertThat(defaults.enabledReplicationRegions()).contains("us-west-2");
// A key created while the default is on takes it.
Key key = createAesKey();
assertThat(key.multiRegionKeyType()).isEqualTo(MultiRegionKeyType.PRIMARY);
assertThat(key.primaryRegion()).isEqualTo("us-east-1");
assertThat(key.usingDefaultReplicationRegions()).isTrue();
// The status of a replica that is there is that it is in sync.
assertThat(key.replicationStatus()).containsKey("us-west-2");
assertThat(key.replicationStatus().get("us-west-2").status())
.isEqualTo(KeyReplicationState.SYNCHRONIZED);
} finally {
client.disableDefaultKeyReplicationRegions(r -> r.replicationRegions("us-west-2"));
for (String region : before) {
client.enableDefaultKeyReplicationRegions(r -> r.replicationRegions(region));
}
}
}
@Test
void theReplicationRegionsOfAKeyCanBeChanged() {
Key key = createReplicatedKey("us-west-2");
assertThat(key.multiRegionKeyType()).isEqualTo(MultiRegionKeyType.PRIMARY);
assertThat(key.replicationStatus()).containsKey("us-west-2");
AddKeyReplicationRegionsResponse added = client.addKeyReplicationRegions(r -> r
.keyIdentifier(key.keyArn())
.replicationRegions("us-west-1"));
assertThat(added.key().replicationStatus()).containsKeys("us-west-2", "us-west-1");
RemoveKeyReplicationRegionsResponse removed = client.removeKeyReplicationRegions(r -> r
.keyIdentifier(key.keyArn())
.replicationRegions("us-west-2"));
assertThat(removed.key().replicationStatus()).containsKey("us-west-1");
assertThat(removed.key().replicationStatus()).doesNotContainKey("us-west-2");
}
@Test
void aRegionTheKeyAlreadyReplicatesIntoIsRefused() {
// Adding a region the key already replicates into changes nothing, and a request
// that cannot be carried out is refused rather than answered with what it already was.
Key key = createReplicatedKey("us-west-2");
assertRefusedWithValidationException(() -> client.addKeyReplicationRegions(r -> r
.keyIdentifier(key.keyArn())
.replicationRegions("us-west-2")), "already replicates into");
}
@Test
void aRegionTheKeyDoesNotReplicateIntoIsRefused() {
// There is nothing to take away from a region the key does not replicate into.
Key key = createReplicatedKey("us-west-2");
assertRefusedWithValidationException(() -> client.removeKeyReplicationRegions(r -> r
.keyIdentifier(key.keyArn())
.replicationRegions("us-west-1")), "does not replicate into");
}
@Test
void takingTheLastReplicaAwayEndsTheReplication() {
// Taking the replica regions away is how the replication is turned off for a key, so
// a key that replicates nowhere is not a multi-region key and says so by carrying no
// type at all.
Key key = createReplicatedKey("us-west-2");
assertThat(key.multiRegionKeyType()).isEqualTo(MultiRegionKeyType.PRIMARY);
RemoveKeyReplicationRegionsResponse removed = client.removeKeyReplicationRegions(r -> r
.keyIdentifier(key.keyArn())
.replicationRegions("us-west-2"));
assertThat(removed.key().multiRegionKeyType()).isNull();
assertThat(removed.key().primaryRegion()).isNull();
assertThat(removed.key().replicationStatus()).isEmpty();
}
@Test
void aKeyThatIsReplicatedHasToBeExportable() {
assertRefusedWithValidationException(
() -> client.createKey(replicatedKeyRequest(false, "us-west-2")),
"exportable");
}
@Test
void aNameThatIsNotARegionIsRefused() {
// A Region a request names has to be a name of a Region this service serves, and a
// name that is not one of those is refused.
assertRefusedWithValidationException(() -> client.enableDefaultKeyReplicationRegions(r -> r
.replicationRegions("moon-west-1")), "moon-west-1");
}
@Test
void aRegionOfAnotherPartitionIsRefused() {
// A key is replicated within the partition it is in, as the reference says, so a
// region of another partition is refused.
assertRefusedWithValidationException(
() -> client.createKey(replicatedKeyRequest(true, "cn-north-1")),
"cn-north-1");
}
@Test
void aDefaultRegionOfAnotherPartitionIsRefused() {
// The default regions are the regions a new key is replicated to, so they are
// within the partition of the region they are the defaults of.
assertRefusedWithValidationException(() -> client.enableDefaultKeyReplicationRegions(r -> r
.replicationRegions("us-gov-west-1")), "us-gov-west-1");
}
@Test
void theRegionOfTheRequestIsNotARegionToReplicateTo() {
// The key is in the region of the request already, so naming that region is a request
// that cannot be carried out.
assertRefusedWithValidationException(
() -> client.createKey(replicatedKeyRequest(true, "us-east-1")),
"us-east-1");
}
@Test
void aKeyWhoseRegionsAreChangedHasAConfigurationOfItsOwn() {
// A key that took the account's default regions says so, and a key whose regions are
// changed afterwards has a configuration of its own, so it says the other thing.
Key key = createReplicatedKey("us-west-2");
assertThat(key.usingDefaultReplicationRegions()).isFalse();
AddKeyReplicationRegionsResponse added = client.addKeyReplicationRegions(r -> r
.keyIdentifier(key.keyArn())
.replicationRegions("us-west-1"));
assertThat(added.key().usingDefaultReplicationRegions()).isFalse();
}
/**
* The public half of a certificate, held by the service as a key.
*
@@ -172,6 +327,85 @@ class PaymentCryptographyTest {
return key;
}
/**
* The request that creates a key of the data the cipher protects, replicated to the
* regions named.
*
* @param exportable whether the key may leave the service
* @param regions the regions the key is replicated to
*/
private static Consumer<CreateKeyRequest.Builder> replicatedKeyRequest(boolean exportable,
String... regions) {
return r -> r
.keyAttributes(a -> a
.keyAlgorithm(KeyAlgorithm.AES_256)
.keyClass(KeyClass.SYMMETRIC_KEY)
.keyUsage(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY)
.keyModesOfUse(m -> m.encrypt(true).decrypt(true)))
.exportable(exportable)
.replicationRegions(regions);
}
/**
* A key of the data the cipher protects, replicated to the regions named.
*
* @param regions the regions the key is replicated to
*/
private static Key createReplicatedKey(String... regions) {
Key key = client.createKey(replicatedKeyRequest(true, regions)).key();
keyArns.add(key.keyArn());
return key;
}
/**
* The error a request the service refuses carries.
*
* @param call the request the service refuses
* @param message the words the refusal carries
*/
private static void assertRefusedWithValidationException(ThrowingCallable call, String message) {
assertThatThrownBy(call)
.isInstanceOf(AwsServiceException.class)
.satisfies(thrown -> assertThat(((AwsServiceException) thrown).awsErrorDetails()
.errorCode()).isEqualTo("ValidationException"))
.hasMessageContaining(message);
}
/**
* The export of a key under an AS2805 cryptogram.
*
* @param key the key that leaves
* @param encryptionKey the key the cryptogram is wrapped under
* @return the export
*/
private static ExportKeyResponse exportAs2805(Key key, Key encryptionKey) {
return client.exportKey(r -> r
.exportKeyIdentifier(key.keyArn())
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
.wrappingKeyIdentifier(encryptionKey.keyArn()))));
}
/**
* The import of a cryptogram that carries a key.
*
* @param encryptionKey the key the cryptogram is wrapped under
* @param cryptogram the cryptogram that carries the key
* @param exportable whether the key that comes in may leave the service
* @return the import
*/
private static ImportKeyResponse importAs2805(Key encryptionKey, String cryptogram,
boolean exportable) {
return client.importKey(r -> r
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
.wrappingKeyIdentifier(encryptionKey.keyArn())
.wrappedKeyCryptogram(cryptogram)
.keyAlgorithm(KeyAlgorithm.TDES_3_KEY)
.keyModesOfUse(modes -> modes.encrypt(true).decrypt(true))
.exportable(exportable))));
}
/** The key identifier of an ARN: the part after the last slash. */
private static String keyIdOf(String arn) {
return arn.substring(arn.lastIndexOf('/') + 1);
@@ -271,29 +505,42 @@ class PaymentCryptographyTest {
.isEqualTo(KeyUsage.TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY);
}
@Test
void anImportedKeyIsReplicatedToTheRegionsTheRequestNames() {
// The model gives an import the same replication regions a creation does, so a key
// that comes in can be replicated as soon as it lands.
Key wrapping = createWrappingKey();
Key key = createAesKey();
ExportKeyResponse exported = client.exportKey(r -> r
.exportKeyIdentifier(key.keyArn())
.keyMaterial(m -> m.tr31KeyBlock(b -> b.wrappingKeyIdentifier(wrapping.keyArn()))));
ImportKeyResponse imported = client.importKey(r -> r
.replicationRegions("us-west-2")
.keyMaterial(m -> m.tr31KeyBlock(b -> b
.wrappingKeyIdentifier(wrapping.keyArn())
.wrappedKeyBlock(exported.wrappedKey().keyMaterial()))));
assertThat(imported.key().multiRegionKeyType()).isEqualTo(MultiRegionKeyType.PRIMARY);
assertThat(imported.key().primaryRegion()).isEqualTo("us-east-1");
// The imported key is cleaned up with the others, so it does not stay behind.
keyArns.add(imported.key().keyArn());
}
@Test
void aKeyLeavesTheServiceAndComesBackThroughAnAs2805Cryptogram() {
Key encryptionKey = createKeyEncryptionKey();
Key key = createKey(KeyAlgorithm.TDES_3_KEY, KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY);
ExportKeyResponse exported = client.exportKey(r -> r
.exportKeyIdentifier(key.keyArn())
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
.wrappingKeyIdentifier(encryptionKey.keyArn()))));
ExportKeyResponse exported = exportAs2805(key, encryptionKey);
assertThat(exported.wrappedKey().wrappedKeyMaterialFormat())
.isEqualTo(WrappedKeyMaterialFormat.KEY_CRYPTOGRAM);
assertThat(exported.wrappedKey().keyMaterial()).isNotBlank();
ImportKeyResponse imported = client.importKey(r -> r
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
.wrappingKeyIdentifier(encryptionKey.keyArn())
.wrappedKeyCryptogram(exported.wrappedKey().keyMaterial())
.keyAlgorithm(KeyAlgorithm.TDES_3_KEY)
.keyModesOfUse(modes -> modes.encrypt(true).decrypt(true))
.exportable(true))));
ImportKeyResponse imported = importAs2805(encryptionKey, exported.wrappedKey().keyMaterial(),
true);
assertThat(imported.key().keyArn()).isNotBlank();
assertThat(imported.key().keyAttributes().keyUsage())
@@ -312,20 +559,10 @@ class PaymentCryptographyTest {
Key encryptionKey = createKeyEncryptionKey();
Key key = createKey(KeyAlgorithm.TDES_3_KEY, KeyUsage.TR31_P0_PIN_ENCRYPTION_KEY);
ExportKeyResponse exported = client.exportKey(r -> r
.exportKeyIdentifier(key.keyArn())
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
.wrappingKeyIdentifier(encryptionKey.keyArn()))));
ExportKeyResponse exported = exportAs2805(key, encryptionKey);
ImportKeyResponse imported = client.importKey(r -> r
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
.as2805KeyVariant(As2805KeyVariant.PIN_ENCRYPTION_KEY_VARIANT_28)
.wrappingKeyIdentifier(encryptionKey.keyArn())
.wrappedKeyCryptogram(exported.wrappedKey().keyMaterial())
.keyAlgorithm(KeyAlgorithm.TDES_3_KEY)
.keyModesOfUse(modes -> modes.encrypt(true).decrypt(true))
.exportable(false))));
ImportKeyResponse imported = importAs2805(encryptionKey, exported.wrappedKey().keyMaterial(),
false);
assertThat(imported.key().exportable()).isFalse();
// The key came into the service, so the cleanup has to take it away again.
@@ -374,14 +611,12 @@ class PaymentCryptographyTest {
Key encryptionKey = createKeyEncryptionKey();
Key key = createTdesKey();
assertThatThrownBy(() -> client.exportKey(r -> r
assertRefusedWithValidationException(() -> client.exportKey(r -> r
.exportKeyIdentifier(key.keyArn())
.keyMaterial(m -> m.as2805KeyCryptogram(b -> b
.as2805KeyVariant(As2805KeyVariant.TERMINAL_MAJOR_KEY_VARIANT_00)
.wrappingKeyIdentifier(encryptionKey.keyArn())))))
.isInstanceOf(AwsServiceException.class)
.satisfies(thrown -> assertThat(((AwsServiceException) thrown).awsErrorDetails()
.errorCode()).isEqualTo("ValidationException"));
.wrappingKeyIdentifier(encryptionKey.keyArn())))),
"AS2805 variant");
}
@Test
@@ -757,12 +992,10 @@ class PaymentCryptographyTest {
// The block is signed with the key the export parameters issue, and the block's
// signature is an RSA one, so a signing key that is not an RSA_2048 one cannot
// sign it.
assertThatThrownBy(() -> client.getParametersForExport(r -> r
assertRefusedWithValidationException(() -> client.getParametersForExport(r -> r
.keyMaterialType(KeyMaterialType.TR34_KEY_BLOCK)
.signingKeyAlgorithm(KeyAlgorithm.ECC_NIST_P256)))
.isInstanceOf(AwsServiceException.class)
.satisfies(thrown -> assertThat(((AwsServiceException) thrown).awsErrorDetails()
.errorCode()).isEqualTo("ValidationException"));
.signingKeyAlgorithm(KeyAlgorithm.ECC_NIST_P256)),
"RSA_2048");
}
@Test
+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 | 17 |
| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 22 |
| [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 |
+58 -14
View File
@@ -22,6 +22,11 @@
| `GetPublicKeyCertificate` | The certificate of an asymmetric key |
| `GetParametersForImport` | The token and the wrapping key certificate an import quotes back |
| `GetParametersForExport` | The token and the signing key certificate an export quotes back |
| `AddKeyReplicationRegions` | Add Regions to the key's replication |
| `RemoveKeyReplicationRegions` | Remove Regions from the key's replication |
| `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 |
| `TagResource` | Add tags to a key |
| `UntagResource` | Remove tags from a key |
| `ListTagsForResource` | List the tags of a key |
@@ -35,20 +40,23 @@
algorithm: the leftmost three bytes of the CMAC of sixteen zero bytes under an AES
key, and the ANSI X9.24 one for a Triple DES key. The material is held by the key
while the emulator runs and is not written to the store.
- **Regional:** keys, aliases and tags all live in the region they were made in. The
- **Regional:** keys and aliases live in the region they were made in. The
service is regional, and so is this.
- **Alias names are unique in a region, not in an account:** the same name may name a
key in two regions, and the two are two aliases. A name that is already taken in
the key's own region is a `ConflictException`.
- **Tags are the region's:** they are not part of the replication process, so a key in
another region carries its own tag set, and tagging one leaves the others alone.
- **Tags follow the key they are on.** A key's tags live with it, and a replica is a
copy of its primary's material and metadata, so a replica carries the primary's tags
and a change to them is replicated. The alias names are the region's own: an alias
names a key in its own region, and a replica is named by an alias of that region.
- **Deletion:** `DeleteKey` removes the key and the aliases that name it, and answers
with the key, its state `DELETE_PENDING` and the moment its deletion takes effect.
A key that is gone does not come back: a tagging request for it is refused. The
service deletes a key the moment it is asked to, so the waiting period of
`DeleteKeyInDays` is checked against the range the model states and is not waited for.
- **Creating a key:** `CreateKey` takes `Exportable`, `Enabled` and `Tags`, and a key
created disabled or with tags comes back that way. The `KeyUsage` and the
- **Creating a key:** `CreateKey` takes `Exportable`, `Enabled`, `Tags`,
`DeriveKeyUsage` and `ReplicationRegions`, and a key created disabled or with tags
comes back that way. The `KeyUsage` and the
`KeyModesOfUse` of the key are required, as the reference requires them. The answer
carries every mode of use the reference gives a key, the ones the key was not made
with as false, so a caller reading them finds a boolean for each of them. The check
@@ -60,12 +68,12 @@
refused, and the permission check reads the same member the request does.
- **Listing by state:** `ListKeys` takes a `KeyState` and answers with the keys in
that state alone, and with every key when it names none. Each key in the list is the
summary the model names: its identifier, its state, its attributes, its check value
and its two flags.
- **The members a request may name that the service does not read:** `CreateKey` and
`ImportKey` take `ReplicationRegions`, and `ImportKey` takes `RequesterComment`, and the
service reads none of them. No replica is made and no approval is recorded, because the
replication and the multi-party approval are not emulated.
summary the model names: its identifier, its state, its attributes, its check value,
its two flags and, for a key that is replicated, the kind of key it is and the region
it is the primary of.
- **The members a request may name that the service does not read:** `ImportKey` takes
`RequesterComment`, and the service reads none of it. No approval is recorded, because
the multi-party approval is not emulated.
- **An alias may name no key:** `UpdateAlias` names the key of an alias, and an update
that names none removes the key the alias names and leaves the alias. `CreateAlias`
refuses an alias without a key, as the reference does, though its model requires
@@ -181,9 +189,45 @@
- **The data plane is a service of its own:** the operations that use a key are on
[the data plane's page](payment-cryptography-data.md), which is reached at its own
routes.
- **Not yet emulated:** the multi-region replication operations, the resource policy
operations, the key usage operations, the key restore operation, the multi-party
approval operations and the certificate signing request.
- **Multi-Region key replication:** a key may be replicated to other Regions, so the same
key material is usable in several of them. The key is created in the Region of the
request and is the *Primary Region key* there; every other Region holds a *Replica
Region key* with the same key identifier and its own ARN. A key that is replicated has
to be exportable, a replica cannot be replicated further, and a replica is read-only:
every change is made on the primary. `AddKeyReplicationRegions` and
`RemoveKeyReplicationRegions` change the Regions of a key, and the default Regions of
the account are set with `EnableDefaultKeyReplicationRegions` and
`DisableDefaultKeyReplicationRegions` and read with
`GetDefaultKeyReplicationRegions`. A key created while the account has default Regions
takes them unless it names its own, and says which it did. A key whose Regions are
changed afterwards has a configuration of its own, and says so. Taking the replica
Regions away is how the replication is turned off for a key, so a key that replicates
nowhere is not a multi-region key and carries no type at all. A Region a request names
has to be a name of a Region this service serves, and it has to be a Region of the
partition the key is in, as the reference says: a key is replicated within its own
partition and account. The Region of the primary is not one to replicate to, to add or
to take away, so a request that cannot be carried out is refused rather than answered as
if it had named no Region at all. A refused request leaves no key behind.
- **The default Regions are the ones of the Region they are read in:** each Region has its
own default Regions, so a key created in a Region takes the default Regions of that
Region and not the ones of another. A key's own replication takes precedence over the
default Regions of its Region.
- **A replica is a complete copy of the key:** it carries the primary's material, so the
key leaves the service from the Region of a replica as well as from the primary's, and
it carries the primary's tags, so a change to them reaches it. The alias names are the
Region's own, and an alias that names a replica goes with it when the replica does.
A replica answers with the kind of the key and the Region of its primary, and the
replication status and the defaults flag are the primary's alone, as the reference's
own answer shows.
- **Not checked:** the permission to create a key in the Region a key is replicated to.
The permission is checked in the Region of the request, which is the Region the
replication is asked in.
- **The replication is in sync at once:** the service does not model the progress of a
replication, so the status of a replica that is there is `SYNCHRONIZED` right away,
where the reference answers `IN_PROGRESS` until the replication has finished.
- **Not yet emulated:** the resource policy operations, the key usage operations, the key
restore operation, the multi-party approval operations and the certificate signing
request.
## Configuration
@@ -62,6 +62,11 @@ public class PaymentCryptographyJsonHandler {
case "GetPublicKeyCertificate" -> () -> getPublicKeyCertificate(request, region);
case "GetParametersForImport" -> () -> getParametersForImport(request, region);
case "GetParametersForExport" -> () -> getParametersForExport(request, region);
case "AddKeyReplicationRegions" -> () -> addKeyReplicationRegions(request, region);
case "RemoveKeyReplicationRegions" -> () -> removeKeyReplicationRegions(request, region);
case "GetDefaultKeyReplicationRegions" -> () -> getDefaultKeyReplicationRegions(request, region);
case "EnableDefaultKeyReplicationRegions" -> () -> enableDefaultKeyReplicationRegions(request, region);
case "DisableDefaultKeyReplicationRegions" -> () -> disableDefaultKeyReplicationRegions(request, region);
case "TagResource" -> () -> tagResource(request, region);
case "UntagResource" -> () -> untagResource(request, region);
case "ListTagsForResource" -> () -> listTagsForResource(request, region);
@@ -117,7 +122,8 @@ public class PaymentCryptographyJsonHandler {
declared.put("DeriveKeyUsage", request.path("DeriveKeyUsage").asText());
}
PaymentCryptographyKey key = service.createKey(region, declared, modesOfUse(attributes),
request.path("Exportable").asBoolean(false), enabled, tagsOf(request));
request.path("Exportable").asBoolean(false), enabled, tagsOf(request),
stringsOf(request, "ReplicationRegions"));
return Map.of("Key", keyObject(key));
}
@@ -360,6 +366,10 @@ public class PaymentCryptographyJsonHandler {
out.put("KeyCheckValue", key.getKeyCheckValue());
out.put("Enabled", key.isEnabled());
out.put("Exportable", key.isExportable());
if (key.getMultiRegionKeyType() != null) {
out.put("MultiRegionKeyType", key.getMultiRegionKeyType());
out.put("PrimaryRegion", key.getPrimaryRegion());
}
return out;
}
@@ -385,6 +395,23 @@ public class PaymentCryptographyJsonHandler {
if (key.getDeleteTimestamp() > 0) {
out.put("DeleteTimestamp", key.getDeleteTimestamp());
}
if (key.getMultiRegionKeyType() != null) {
out.put("MultiRegionKeyType", key.getMultiRegionKeyType());
out.put("PrimaryRegion", key.getPrimaryRegion());
if ("PRIMARY".equals(key.getMultiRegionKeyType())) {
// The replication status and the defaults flag belong to the primary: a
// replica answers with the kind of the key and its primary Region alone,
// as the reference's own answer shows.
Map<String, Object> status = new LinkedHashMap<>();
for (String target : key.getReplicationRegions()) {
// The model's replication states are IN_PROGRESS, DELETE_IN_PROGRESS, FAILED
// and SYNCHRONIZED. A replica that is there is a key that is in sync.
status.put(target, Map.of("Status", "SYNCHRONIZED"));
}
out.put("ReplicationStatus", status);
out.put("UsingDefaultReplicationRegions", key.isUsingDefaultReplicationRegions());
}
}
return out;
}
@@ -463,7 +490,8 @@ public class PaymentCryptographyJsonHandler {
"imports");
PaymentCryptographyKey key = service.importKey(region, form, members(material.path(form)),
request.path("KeyCheckValueAlgorithm").asText(),
request.path("Enabled").asBoolean(true), tagsOf(request));
request.path("Enabled").asBoolean(true), tagsOf(request),
stringsOf(request, "ReplicationRegions"));
return Map.of("Key", keyObject(key));
}
@@ -546,4 +574,67 @@ public class PaymentCryptographyJsonHandler {
}
return node.asText();
}
/**
* The key with the regions the request names added to its replication.
*/
private Map<String, Object> addKeyReplicationRegions(JsonNode request, String region) {
PaymentCryptographyKey key = service.addKeyReplicationRegions(region,
request.path("KeyIdentifier").asText(), stringsOf(request, "ReplicationRegions"));
return Map.of("Key", keyObject(key));
}
/**
* The key with the regions the request names taken away from its replication.
*/
private Map<String, Object> removeKeyReplicationRegions(JsonNode request, String region) {
PaymentCryptographyKey key = service.removeKeyReplicationRegions(region,
request.path("KeyIdentifier").asText(), stringsOf(request, "ReplicationRegions"));
return Map.of("Key", keyObject(key));
}
/**
* The regions the account replicates a new key to by default.
*
* <p>The settings are the ones of the Region the request is in, so each Region has its
* own.
*/
private Map<String, Object> getDefaultKeyReplicationRegions(JsonNode request, String region) {
return Map.of("EnabledReplicationRegions", service.defaultReplicationRegions(region));
}
/** Turns the default replication of the account on for the regions the request names. */
private Map<String, Object> enableDefaultKeyReplicationRegions(JsonNode request, String region) {
return Map.of("EnabledReplicationRegions",
service.enableDefaultReplicationRegions(region,
stringsOf(request, "ReplicationRegions")));
}
/** Turns the default replication of the account off for the regions the request names. */
private Map<String, Object> disableDefaultKeyReplicationRegions(JsonNode request, String region) {
return Map.of("EnabledReplicationRegions",
service.disableDefaultReplicationRegions(region,
stringsOf(request, "ReplicationRegions")));
}
/**
* The strings of a request, such as the replication regions.
*
* <p>The shape check settles that the member is a list of names, so a request that names a
* region that is not one is refused before this reads it.
*
* @param request the request the member is in
* @param member the member to read
*/
private static List<String> stringsOf(JsonNode request, String member) {
JsonNode declared = request.get(member);
if (declared == null || declared.isNull()) {
return new ArrayList<>();
}
List<String> values = new ArrayList<>();
for (JsonNode value : declared) {
values.add(value.asText());
}
return values;
}
}
@@ -24,6 +24,7 @@ import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
@@ -73,11 +74,20 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
/** The origin of a key whose material came in from outside the service. */
private static final String ORIGIN_EXTERNAL = "EXTERNAL";
/**
* The storage key the account's default replication regions are kept under.
*
* <p>The store is account-aware, so what is under this key belongs to the account that
* put it there and to no other.
*/
private static final String DEFAULT_REGIONS_KEY = "default-replication-regions";
private final StorageBackend<String, PaymentCryptographyKey> keyStore;
private final StorageBackend<String, PaymentCryptographyAlias> aliasStore;
/** The key exchange: the forms a key may leave in, and the certificates that carry them. */
private final PaymentCryptographyKeyExchange exchange;
private final StorageBackend<String, List<String>> settingsStore;
private final RegionResolver regionResolver;
private final SecureRandom secureRandom;
private final PaymentCryptographyRequestContext requestContext;
@@ -90,6 +100,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
new TypeReference<>() {}),
storageFactory.create(STORAGE_KEY, "payment-cryptography-aliases.json",
new TypeReference<>() {}),
storageFactory.create(STORAGE_KEY, "payment-cryptography-settings.json",
new TypeReference<Map<String, List<String>>>() {}),
regionResolver,
new SecureRandom(),
requestContext,
@@ -101,7 +113,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
RegionResolver regionResolver,
PaymentCryptographyRequestContext requestContext) {
this(keyStore, aliasStore, regionResolver, new SecureRandom(), requestContext);
this(keyStore, aliasStore, new InMemoryStorage<>(), regionResolver, new SecureRandom(),
requestContext, new CertificateGenerator(), Clock.systemUTC());
}
/**
@@ -113,8 +126,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
RegionResolver regionResolver) {
this(keyStore, aliasStore, regionResolver, new SecureRandom(),
new PaymentCryptographyRequestContext());
this(keyStore, aliasStore, new InMemoryStorage<>(), regionResolver, new SecureRandom(),
new PaymentCryptographyRequestContext(), new CertificateGenerator(), Clock.systemUTC());
}
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
@@ -122,8 +135,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
RegionResolver regionResolver,
SecureRandom secureRandom,
PaymentCryptographyRequestContext requestContext) {
this(keyStore, aliasStore, regionResolver, secureRandom, requestContext,
new CertificateGenerator(), Clock.systemUTC());
this(keyStore, aliasStore, new InMemoryStorage<>(), regionResolver, secureRandom,
requestContext, new CertificateGenerator(), Clock.systemUTC());
}
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
@@ -133,8 +146,21 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
PaymentCryptographyRequestContext requestContext,
CertificateGenerator certificates,
Clock clock) {
this(keyStore, aliasStore, new InMemoryStorage<>(), regionResolver, secureRandom,
requestContext, certificates, clock);
}
PaymentCryptographyService(StorageBackend<String, PaymentCryptographyKey> keyStore,
StorageBackend<String, PaymentCryptographyAlias> aliasStore,
StorageBackend<String, List<String>> settingsStore,
RegionResolver regionResolver,
SecureRandom secureRandom,
PaymentCryptographyRequestContext requestContext,
CertificateGenerator certificates,
Clock clock) {
this.keyStore = keyStore;
this.aliasStore = aliasStore;
this.settingsStore = settingsStore;
this.regionResolver = regionResolver;
this.exchange = new PaymentCryptographyKeyExchange(this, certificates, clock);
this.secureRandom = secureRandom;
@@ -343,20 +369,25 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
* is being tagged cannot be written back after it was deleted.
*/
public synchronized PaymentCryptographyKey deleteKey(PaymentCryptographyKey key) {
// A replica is read-only: only the primary may be deleted.
requireNotReplica(key, "only the primary may be deleted");
long now = Instant.now().getEpochSecond();
key.setKeyState("DELETE_PENDING");
key.setEnabled(false);
key.setDeletePendingTimestamp(now);
// The replicas of a key go when the key goes. A replica left behind would be a
// record of a key that is gone, and it could not be deleted on its own.
for (String target : key.getReplicationRegions()) {
keyStore.delete(storageKey(target, key.getKeyId()));
}
keyStore.delete(storageKey(key.getRegion(), key.getKeyId()));
// A key saved before the region became part of its name is under that name too,
// and it goes with the key: a record left behind would be a key that was deleted
// and still there.
keyStore.delete(key.getKeyId());
for (PaymentCryptographyAlias alias : aliasStore.scan(a -> true)) {
if (key.getKeyId().equals(alias.getKeyId())) {
aliasStore.delete(aliasKey(alias.getAliasName(), alias.getRegion()));
}
}
// The aliases that name the key go with it, in every region: a replica shares the
// identifier of its primary, so these are the aliases of the replicas too.
deleteAliasesOf(null, key.getKeyId());
return key;
}
@@ -478,13 +509,16 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
/**
* Adds tags to a key.
*
* <p>The tags are the region's: they are not part of the replication
* process, so a key in another region carries its own tag set.
* <p>A replica is a copy of the primary's metadata, so it carries the primary's tags,
* and a change made on the primary reaches the replicas. A replica is read-only, so the
* change is made on the primary.
*/
public synchronized void tag(PaymentCryptographyKey key, Map<String, String> tags) {
PaymentCryptographyKey current = liveKey(key);
requireNotReplica(current, "a replica is read-only");
current.getTags().putAll(tags);
storeKey(current);
refreshReplicas(current, current.getReplicationRegions());
}
/**
@@ -521,13 +555,64 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
}
}
/** Removes tags from a key, in this region only. */
/**
* Removes tags from a key.
*
* <p>A replica is read-only, so the change is made on the primary and reaches the
* replicas.
*/
public synchronized void untag(PaymentCryptographyKey key, List<String> tagKeys) {
PaymentCryptographyKey current = liveKey(key);
requireNotReplica(current, "a replica is read-only");
for (String tagKey : tagKeys) {
current.getTags().remove(tagKey);
}
storeKey(current);
refreshReplicas(current, current.getReplicationRegions());
}
/**
* The replicas of a primary brought up to date with it.
*
* <p>A replica is a copy of the primary's material and metadata, and a change to the
* primary's metadata is replicated to the replicas, as the reference says. The copy is
* in one place, so every change to a primary reaches its replicas the same way.
*
* @param primary the key the change was made on
* @param regions the regions the replicas are in
*/
private void refreshReplicas(PaymentCryptographyKey primary, Collection<String> regions) {
for (String target : regions) {
PaymentCryptographyKey replica = findKeyRecord(keyStore, target, primary.getKeyId());
if (replica == null) {
continue;
}
replica.setTags(new LinkedHashMap<>(primary.getTags()));
replica.setKeyState(primary.getKeyState());
replica.setEnabled(primary.isEnabled());
replica.setUsingDefaultReplicationRegions(primary.isUsingDefaultReplicationRegions());
replica.setPrimaryRegion(primary.getPrimaryRegion());
replica.setReplicationRegions(new ArrayList<>(primary.getReplicationRegions()));
keyStore.put(storageKey(target, replica.getKeyId()), replica);
}
}
/**
* The refusal of a request that names a replica.
*
* <p>A replica is read-only: only the primary may be deleted, replicated further or
* changed, so a change made on the replica itself is refused. The check is in one place,
* so every operation that names a replica refuses it in the same words.
*
* @param key the key the request names
* @param what what the request wanted to do with the key, for the message
*/
private static void requireNotReplica(PaymentCryptographyKey key, String what) {
if ("REPLICA".equals(key.getMultiRegionKeyType())) {
throw new AwsException("ValidationException",
"the key " + key.getArn() + " is a replica of a key in "
+ key.getPrimaryRegion() + ", and " + what, 400);
}
}
/**
@@ -552,8 +637,6 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
maxResults, nextToken, DEFAULT_PAGE_SIZE, MAX_RESULTS, PAGINATION_ERROR);
}
// ---- the replication ------------------------------------------------------
// ---- the key exchange ----------------------------------------------------
/**
@@ -619,6 +702,18 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
public PaymentCryptographyKey importKey(String region, String form, Map<String, Object> material,
String checkValueAlgorithm, boolean enabled,
Map<String, String> tags) {
return importKey(region, form, material, checkValueAlgorithm, enabled, tags, List.of());
}
/**
* Imports a key and replicates it to the regions the request names.
*
* <p>The model gives an import the same replication regions a creation does, so a key
* that comes in can be replicated as soon as it lands.
*/
public PaymentCryptographyKey importKey(String region, String form, Map<String, Object> material,
String checkValueAlgorithm, boolean enabled,
Map<String, String> tags, List<String> replicationRegions) {
PaymentCryptographyKeyExchange.Imported imported = exchange.importKey(region, form, material);
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", imported.algorithm());
@@ -634,11 +729,16 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
+ imported.algorithm() + " key has, which is " + own, 400);
}
}
return makeKey(region, attributes, imported.modes(), imported.exportable(), enabled, tags,
Replication replication = replicationOf(region, replicationRegions);
// The key is checked before it is made, so a refused request leaves no key behind.
requireExportable(imported.exportable(), replication.targets());
PaymentCryptographyKey key = makeKey(region, attributes, imported.modes(),
imported.exportable(), enabled, tags,
imported.material() == null ? null
: PaymentCryptographyCrypto.toHex(imported.material()),
imported.publicKeyBase64(), imported.privateKeyBase64(), imported.certificatePem(),
ORIGIN_EXTERNAL);
return replicate(key, replication);
}
/**
@@ -1084,6 +1184,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
@Override
public void clear() {
keyStore.clear();
settingsStore.clear();
aliasStore.clear();
}
@@ -1108,4 +1209,408 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
boolean reuse) {
return exchange.parametersForExport(materialType, algorithm, reuse);
}
// ---- the replication ------------------------------------------------------
/**
* The regions the account replicates a new key to when the request names none.
*
* <p>They are kept in the account-aware store, so they belong to the account that set
* them and to no other account. Each Region has its own settings, so a Region whose
* keys are replicated is not the same as another Region whose keys are not.
*
* @param region the Region the settings are read in
*/
public List<String> defaultReplicationRegions(String region) {
List<String> regions = settingsStore.get(defaultRegionsKey(region)).orElseGet(ArrayList::new);
return new ArrayList<>(regions);
}
/**
* The name the default regions of a Region are kept under.
*
* @param region the Region the settings are of
*/
private static String defaultRegionsKey(String region) {
return DEFAULT_REGIONS_KEY + ":" + region;
}
/**
* Turns the default replication of the account on for the regions the request names.
*
* <p>The regions the account already had are left on, so the operation adds rather than
* replaces. The settings are the ones of the Region the request is in, so each Region
* has its own.
*
* @param region the Region the request is in
* @param regions the regions the request names
*/
public synchronized List<String> enableDefaultReplicationRegions(String region,
List<String> regions) {
requireReplicationRegions(region, regions);
// The region of the request is where the keys made there are primary, so it is not
// a region they are replicated to.
requireOtherRegion(region, regions, "enable");
List<String> current = defaultReplicationRegions(region);
for (String target : regions) {
if (!current.contains(target)) {
current.add(target);
}
}
settingsStore.put(defaultRegionsKey(region), current);
return defaultReplicationRegions(region);
}
/**
* Turns the default replication of the account off for the regions the request names.
*
* <p>Only the regions the request names are turned off, so the others stay on. The
* settings are the ones of the Region the request is in, so each Region has its own.
*
* @param region the Region the request is in
* @param regions the regions the request names
*/
public synchronized List<String> disableDefaultReplicationRegions(String region,
List<String> regions) {
requireKnownRegions(regions);
List<String> current = defaultReplicationRegions(region);
current.removeAll(regions);
settingsStore.put(defaultRegionsKey(region), current);
return defaultReplicationRegions(region);
}
/**
* The regions the service serves, or the refusal of the ones it does not.
*
* <p>The check is in one place, so every operation that names a region refuses the same
* regions in the same words.
*
* @param regions the regions the request names
*/
private static void requireKnownRegions(List<String> regions) {
for (String region : regions) {
if (!RegionResolver.isKnownRegion(region)) {
throw new AwsException("ValidationException",
"the region " + region + " is not a region this service serves", 400);
}
}
}
/**
* The regions a key may be replicated to, or the refusal of the ones it may not.
*
* <p>A key is replicated within the partition it is in and the account it belongs to, as
* the reference says, so a region of another partition is refused. The account is the
* one the request is made in, so a request cannot name a region of another account.
* The partition of a region is the one its ARN is minted with, so a region the catalog
* cannot place is in the partition of the deployment and not in the commercial one.
* The check is in one place, so every operation that names a replication region
* refuses the same regions in the same words.
*
* @param region the region the request is in
* @param regions the regions the request names
*/
private void requireReplicationRegions(String region, List<String> regions) {
requireKnownRegions(regions);
for (String target : regions) {
if (!regionResolver.partitionForRegion(region)
.equals(regionResolver.partitionForRegion(target))) {
throw new AwsException("ValidationException",
"the region " + target + " is in another partition than the region "
+ region + ", and a key is replicated within its own partition", 400);
}
}
}
/**
* The refusal of a request that names the region of the request as a region to replicate to.
*
* <p>A key is in the region of the request already, so that region is not a region the key
* is replicated to. The check is in one place, so every operation that names a region
* refuses it in the same words.
*
* @param region the region the request is in
* @param regions the regions the request names
* @param what the operation, for the message
*/
private static void requireOtherRegion(String region, List<String> regions, String what) {
if (regions.contains(region)) {
throw new AwsException("ValidationException",
"the region " + region + " is the region of the request, and it is not a region to "
+ what, 400);
}
}
/**
* The key with the regions the request names added to its replication.
*
* <p>Only the primary of a multi-region key may be replicated further, and a key that is
* replicated has to be exportable.
*/
public synchronized PaymentCryptographyKey addKeyReplicationRegions(String region, String keyIdentifier,
List<String> regions) {
PaymentCryptographyKey key = primaryOf(region, keyIdentifier);
// The key has to be in an active state to be replicated, as the reference says.
PaymentCryptographyKeyRules.requireEnabled(key);
if (!key.isExportable()) {
throw new AwsException("ValidationException",
"a key that is replicated has to be exportable, and " + key.getArn() + " is not", 400);
}
requireReplicationRegions(region, regions);
// The key is in its own region already, so naming that region again is a request
// that cannot be carried out.
requireOtherRegion(region, regions, "add");
Set<String> added = new LinkedHashSet<>(key.getReplicationRegions());
for (String target : regions) {
if (added.contains(target)) {
// The key already replicates there, so adding it again is a request that
// cannot be carried out rather than one that changes nothing.
throw new AwsException("ValidationException",
"the key " + key.getArn() + " already replicates into " + target, 400);
}
added.add(target);
}
if (added.isEmpty()) {
// Nothing is left to replicate to, so the key would be a multi-region key with no
// replica, which is not a thing: a request that names no region is refused.
throw new AwsException("ValidationException",
"the request names no region to add to the replication of " + key.getArn(), 400);
}
// A key with a replica is a primary, and says which region it is the primary of.
key.setMultiRegionKeyType("PRIMARY");
key.setPrimaryRegion(key.getPrimaryRegion() == null ? region : key.getPrimaryRegion());
key.setReplicationRegions(new ArrayList<>(added));
// The key has a configuration of its own now, so it no longer takes the account's
// default regions.
key.setUsingDefaultReplicationRegions(false);
storeKey(key);
// A region the key did not replicate into gets a replica of the key, and a replica
// that is already there keeps its own region and its own ARN and takes the primary's
// metadata, so it does not report regions the primary has left behind.
for (String target : added) {
if (findKeyRecord(keyStore, target, key.getKeyId()) == null) {
keyStore.put(storageKey(target, key.getKeyId()), replicaOf(key, target));
}
}
refreshReplicas(key, added);
return key;
}
/**
* The key with the regions the request names taken away from its replication.
*
* <p>The key goes out of the region it was replicated to, and the record of it there is
* gone.
*/
public synchronized PaymentCryptographyKey removeKeyReplicationRegions(String region,
String keyIdentifier,
List<String> regions) {
PaymentCryptographyKey key = primaryOf(region, keyIdentifier);
// The region the primary is in is not a replica, and taking it away would
// delete the key without going through the deletion operation.
requireOtherRegion(region, regions, "remove");
Set<String> left = new LinkedHashSet<>(key.getReplicationRegions());
for (String target : regions) {
if (!left.contains(target)) {
// The key does not replicate there, so there is nothing to take away.
throw new AwsException("ValidationException",
"the key " + key.getArn() + " does not replicate into " + target, 400);
}
}
left.removeAll(regions);
key.setReplicationRegions(new ArrayList<>(left));
if (left.isEmpty()) {
// A key that replicates nowhere is not part of a replication relationship, and
// says so by carrying no type at all. Taking the last replica away is how the
// replication is turned off for a key, so the key is a plain one afterwards.
key.setMultiRegionKeyType(null);
key.setPrimaryRegion(null);
key.setUsingDefaultReplicationRegions(false);
}
storeKey(key);
for (String target : regions) {
keyStore.delete(storageKey(target, key.getKeyId()));
// The aliases that named the replica in that region go with it: an alias that
// names a key that is not there cannot be resolved, and its name would be taken
// by a key that is not the one it named.
deleteAliasesOf(target, key.getKeyId());
}
// The replicas that are left carry the regions the primary has now, so none of them
// reports a region the primary has left behind. They carry the primary's tags too: a
// replica is a copy of the primary's material and metadata.
refreshReplicas(key, left);
return key;
}
/**
* The aliases that name a key, gone with the key.
*
* <p>An alias that names a key that is not there cannot be resolved, so it goes when the
* key does, as it does when the key itself is deleted. A replica shares the identifier
* of its primary, so the aliases that name the replica are the ones that name the key.
*
* @param region the region the aliases are in, or null for the aliases of every region
* @param keyId the key the aliases name
*/
private void deleteAliasesOf(String region, String keyId) {
for (PaymentCryptographyAlias alias : aliasStore.scan(a -> true)) {
if (region != null && !region.equals(alias.getRegion())) {
continue;
}
if (keyId.equals(alias.getKeyId())) {
aliasStore.delete(aliasKey(alias.getAliasName(), alias.getRegion()));
}
}
}
/**
* The primary of a key, which is the only one that may be replicated further.
*
* <p>A replica is read-only: it cannot be deleted on its own and it cannot be replicated
* further, so the operations that change the replication of a key start at its primary.
*/
private PaymentCryptographyKey primaryOf(String region, String keyIdentifier) {
PaymentCryptographyKey key = findKey(region, keyIdentifier);
if (key == null) {
throw new AwsException("ResourceNotFoundException", "Key not found: " + keyIdentifier, 400);
}
requireNotReplica(key, "only the primary may be replicated");
return key;
}
/**
* The record of a key in another region: the same key, with the ARN of that region.
*
* <p>The alias names are the region's own, but the tags are the primary's: a replica is
* a copy of the primary's material and metadata.
*/
private PaymentCryptographyKey replicaOf(PaymentCryptographyKey primary, String region) {
PaymentCryptographyKey replica = new PaymentCryptographyKey();
replica.setKeyId(primary.getKeyId());
replica.setArn(regionResolver.buildArn(SERVICE, region, "key/" + primary.getKeyId()));
replica.setRegion(region);
replica.setKeyAlgorithm(primary.getKeyAlgorithm());
replica.setKeyClass(primary.getKeyClass());
replica.setKeyUsage(primary.getKeyUsage());
replica.setKeyModesOfUse(new LinkedHashMap<>(primary.getKeyModesOfUse()));
replica.setKeyOrigin(primary.getKeyOrigin());
replica.setKeyCheckValue(primary.getKeyCheckValue());
replica.setKeyCheckValueAlgorithm(primary.getKeyCheckValueAlgorithm());
replica.setKeyState(primary.getKeyState());
replica.setExportable(primary.isExportable());
replica.setEnabled(primary.isEnabled());
replica.setKeyMaterialHex(primary.getKeyMaterialHex());
// The halves of an asymmetric key travel with it, or the replica is a record of a
// key that has none.
replica.setKeyPublicKeyBase64(primary.getKeyPublicKeyBase64());
replica.setKeyPrivateKeyBase64(primary.getKeyPrivateKeyBase64());
replica.setKeyCertificatePem(primary.getKeyCertificatePem());
replica.setDeriveKeyUsage(primary.getDeriveKeyUsage());
// A replica is a copy of the primary's material and metadata, so it carries the
// primary's tags too.
replica.setTags(new LinkedHashMap<>(primary.getTags()));
replica.setCreateTimestamp(primary.getCreateTimestamp());
replica.setUsageStartTimestamp(primary.getUsageStartTimestamp());
replica.setPrimaryRegion(primary.getPrimaryRegion());
replica.setReplicationRegions(new ArrayList<>(primary.getReplicationRegions()));
replica.setMultiRegionKeyType("REPLICA");
replica.setUsingDefaultReplicationRegions(primary.isUsingDefaultReplicationRegions());
return replica;
}
/**
* Creates a key, in the region of the request and in the regions it is replicated to.
*
* <p>A key that is replicated is one key with one identifier in several regions, and each
* region has its own ARN of it. The regions the request names are the ones the key is
* replicated to; when it names none, the account's default regions are the ones, and the
* key says that it took them.
*/
public PaymentCryptographyKey createKey(String region, Map<String, Object> attributes,
Map<String, Boolean> modesOfUse, boolean exportable,
boolean enabled, Map<String, String> tags,
List<String> replicationRegions) {
Replication replication = replicationOf(region, replicationRegions);
// The key is checked before it is made, so a refused request leaves no key behind.
requireExportable(exportable, replication.targets());
PaymentCryptographyKey primary = makeKey(region, attributes, modesOfUse, exportable,
enabled, tags, null);
return replicate(primary, replication);
}
/**
* The regions a key is replicated to, and whether they are the account's defaults.
*
* <p>The regions the request names are the ones the key is replicated to; when it names
* none, the account's default regions are the ones. The region's own is never one of
* them, since the key is in that region already.
*
* @param region the region the request is in
* @param replicationRegions the regions the request names, or none for the account's
*/
private Replication replicationOf(String region, List<String> replicationRegions) {
Set<String> targets = new LinkedHashSet<>();
boolean named = replicationRegions != null && !replicationRegions.isEmpty();
if (named) {
// A key is in the region of the request already, so naming that region is a
// request that cannot be carried out.
requireOtherRegion(region, replicationRegions, "replicate to");
targets.addAll(replicationRegions);
} else {
targets.addAll(defaultReplicationRegions(region));
// The region of the request is never a replica of the key made there.
targets.remove(region);
}
requireReplicationRegions(region, new ArrayList<>(targets));
return new Replication(targets, !named);
}
/**
* A key that is replicated has to be exportable, since a replica is a copy of its
* material.
*
* @param exportable whether the key may leave the service
* @param targets the regions the key would be replicated to
*/
private static void requireExportable(boolean exportable, Set<String> targets) {
if (!targets.isEmpty() && !exportable) {
throw new AwsException("ValidationException",
"a key that is replicated has to be exportable, and this one is not", 400);
}
}
/**
* The regions a key is replicated to, and whether they are the account's defaults.
*
* @param targets the regions the key is replicated to
* @param usingDefaults whether those regions are the account's default ones
*/
private record Replication(Set<String> targets, boolean usingDefaults) { }
/**
* Replicates a key to the regions the request names.
*
* <p>A key that is replicated is one key with one identifier in several regions, and each
* region has its own ARN of it. The regions the request names are the ones the key is
* replicated to; when it names none, the account's default regions are the ones, and the
* key says that it took them.
*
* @param primary the key that was made
* @param replication the regions it is replicated to
* @return the key, which is the primary of a multi-region key when it was replicated
*/
private PaymentCryptographyKey replicate(PaymentCryptographyKey primary, Replication replication) {
if (replication.targets().isEmpty()) {
return primary;
}
primary.setPrimaryRegion(primary.getRegion());
primary.setMultiRegionKeyType("PRIMARY");
primary.setReplicationRegions(new ArrayList<>(replication.targets()));
primary.setUsingDefaultReplicationRegions(replication.usingDefaults());
storeKey(primary);
for (String target : replication.targets()) {
keyStore.put(storageKey(target, primary.getKeyId()), replicaOf(primary, target));
}
return primary;
}
}
@@ -4,7 +4,9 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.quarkus.runtime.annotations.RegisterForReflection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
@@ -68,12 +70,13 @@ public class PaymentCryptographyKey {
private long deleteTimestamp;
private Map<String, String> tags = new HashMap<>();
/** The region of the primary of a multi-region key, and its own region otherwise. */
private String primaryRegion;
/** The regions a multi-region key is in, besides the primary's. */
private List<String> replicationRegions = new ArrayList<>();
/** Whether this record is the primary of a multi-region key or a replica of one. */
private String multiRegionKeyType;
/** Whether the key took the account's default replication regions. */
private boolean usingDefaultReplicationRegions;
public String getKeyId() { return keyId; }
public void setKeyId(String keyId) { this.keyId = keyId; }
@@ -164,6 +167,20 @@ public class PaymentCryptographyKey {
public long getDeleteTimestamp() { return deleteTimestamp; }
public void setDeleteTimestamp(long deleteTimestamp) { this.deleteTimestamp = deleteTimestamp; }
public String getPrimaryRegion() { return primaryRegion; }
public void setPrimaryRegion(String primaryRegion) { this.primaryRegion = primaryRegion; }
public List<String> getReplicationRegions() { return replicationRegions; }
public void setReplicationRegions(List<String> replicationRegions) { this.replicationRegions = replicationRegions; }
public String getMultiRegionKeyType() { return multiRegionKeyType; }
public void setMultiRegionKeyType(String multiRegionKeyType) { this.multiRegionKeyType = multiRegionKeyType; }
public boolean isUsingDefaultReplicationRegions() { return usingDefaultReplicationRegions; }
public void setUsingDefaultReplicationRegions(boolean usingDefaultReplicationRegions) {
this.usingDefaultReplicationRegions = usingDefaultReplicationRegions;
}
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
}
@@ -65,6 +65,12 @@ class PaymentCryptographyIntegrationTest {
"KeyModesOfUse":{"Encrypt":true,"Decrypt":true}},
"Exportable":true}""";
private static final String CREATE_WRAPPING_KEY = """
{"KeyAttributes":{"KeyAlgorithm":"AES_256","KeyClass":"SYMMETRIC_KEY",
"KeyUsage":"TR31_K1_KEY_BLOCK_PROTECTION_KEY",
"KeyModesOfUse":{"Wrap":true,"Unwrap":true}},
"Exportable":true}""";
private static final String CREATE_KEY_PAIR = """
{"KeyAttributes":{"KeyAlgorithm":"RSA_2048","KeyClass":"ASYMMETRIC_KEY_PAIR",
"KeyUsage":"TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE",
@@ -184,17 +190,10 @@ class PaymentCryptographyIntegrationTest {
@Test
void anImportedKeyCarriesTheEnabledFlagAndTheTags() {
// The import names the key's state and its tags, and the key comes back that way.
String wrapping = call("CreateKey", """
{"KeyAttributes":{"KeyAlgorithm":"AES_256","KeyClass":"SYMMETRIC_KEY",
"KeyUsage":"TR31_K1_KEY_BLOCK_PROTECTION_KEY",
"KeyModesOfUse":{"Wrap":true,"Unwrap":true}},
"Exportable":true}
""")
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = call("CreateKey", CREATE_KEY)
String wrapping = call("CreateKey", CREATE_WRAPPING_KEY)
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
String block = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn
+ "\",\"KeyMaterial\":{\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\""
+ wrapping + "\"}}}")
@@ -218,9 +217,7 @@ class PaymentCryptographyIntegrationTest {
@Test
void aRequestNamingTwoFormsIsRefused() {
// The union holds one form per request, and naming two is not naming one.
String arn = call("CreateKey", CREATE_KEY)
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ "\"Tr31KeyBlock\":{\"WrappingKeyIdentifier\":\"" + arn + "\"},"
@@ -234,9 +231,7 @@ class PaymentCryptographyIntegrationTest {
void theTr34FormIsServed() {
// The TR-34 form is one the service makes now, so a request that names one is
// refused for what it is missing and not for naming an unserved form.
String arn = call("CreateKey", CREATE_KEY)
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ "\"Tr34KeyBlock\":{\"WrappingKeyCertificate\":\"x\","
@@ -250,9 +245,7 @@ class PaymentCryptographyIntegrationTest {
void theAs2805FormIsServed() {
// The AS2805 form is one the service makes now, so a request that names one is
// refused for what it is missing and not for naming an unserved form.
String arn = call("CreateKey", CREATE_KEY)
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ "\"As2805KeyCryptogram\":{\"As2805KeyVariant\":"
@@ -267,9 +260,7 @@ class PaymentCryptographyIntegrationTest {
void aRequestNamingNoFormIsRefused() {
// Every form the model names is one the service makes now, so a request that
// names none of them names no form at all.
String arn = call("CreateKey", CREATE_KEY)
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{}}")
.then().statusCode(400)
@@ -284,9 +275,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void theModelCheckRefusesAnExportWithoutAWrappingKeyCertificate() {
String arn = call("CreateKey", CREATE_KEY)
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ "\"KeyCryptogram\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + "\"}}}");
@@ -385,6 +374,19 @@ class PaymentCryptographyIntegrationTest {
assertTheModelRefused(answer, "KeyDerivationHashAlgorithm");
}
/**
* The body of a request that creates a key replicated to the regions the member names.
*
* @param regions the member that names the regions, as the request spells it
*/
private static String createReplicatedKeyBody(String regions) {
return """
{"KeyAttributes":{"KeyAlgorithm":"AES_256","KeyClass":"SYMMETRIC_KEY",
"KeyUsage":"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
"KeyModesOfUse":{"Encrypt":true,"Decrypt":true}},
"Exportable":true,"ReplicationRegions":%s}""".formatted(regions);
}
/** The ARN of a key the request may name. */
private static String keyArn() {
return call("CreateKey", CREATE_KEY).then().statusCode(200)
@@ -404,9 +406,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void theModelCheckRefusesATr34ExportWithoutItsWrappingKeyCertificate() {
String arn = call("CreateKey", CREATE_KEY)
.then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
Response answer = call("ExportKey", "{\"ExportKeyIdentifier\":\"" + arn + "\",\"KeyMaterial\":{"
+ "\"Tr34KeyBlock\":{\"CertificateAuthorityPublicKeyIdentifier\":\"" + arn + "\","
@@ -496,8 +496,7 @@ class PaymentCryptographyIntegrationTest {
@Test
void theKeysOfARegionAreListed() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ListKeys", "{}")
.then().statusCode(200)
@@ -509,8 +508,7 @@ class PaymentCryptographyIntegrationTest {
void aListedKeyIsItsSummary() {
// A list carries the key's summary and not the whole key: the identifier, the state,
// the attributes, the check value and the two flags.
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ListKeys", "{}")
.then().statusCode(200)
@@ -527,13 +525,82 @@ class PaymentCryptographyIntegrationTest {
// key, which the list does not carry.
.body("Keys.find { it.KeyArn == '" + arn + "' }.CreateTimestamp", nullValue())
.body("Keys.find { it.KeyArn == '" + arn + "' }.KeyOrigin", nullValue())
.body("Keys.find { it.KeyArn == '" + arn + "' }.UsageStartTimestamp", nullValue());
.body("Keys.find { it.KeyArn == '" + arn + "' }.UsageStartTimestamp", nullValue())
// A key that replicates nowhere is not a multi-region key, so the summary
// says nothing about where it stands.
.body("Keys.find { it.KeyArn == '" + arn + "' }.MultiRegionKeyType", nullValue());
}
@Test
void aReplicaAnswersWithTheKindOfTheKeyAndItsPrimaryRegion() {
// The replication status and the defaults flag are the primary's alone, as the
// reference's own answer shows.
String arn = call("CreateKey", createReplicatedKeyBody("[\"us-west-2\"]"))
.then().statusCode(200)
.extract().path("Key.KeyArn");
call("GetKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
.then().statusCode(200)
.body("Key.MultiRegionKeyType", equalTo("PRIMARY"))
.body("Key.PrimaryRegion", equalTo("us-east-1"))
.body("Key.ReplicationStatus.'us-west-2'.Status", equalTo("SYNCHRONIZED"))
.body("Key.UsingDefaultReplicationRegions", equalTo(false));
String replicaArn = arn.replace(":us-east-1:", ":us-west-2:");
callIn("us-west-2", "GetKey", "{\"KeyIdentifier\":\"" + replicaArn + "\"}")
.then().statusCode(200)
.body("Key.MultiRegionKeyType", equalTo("REPLICA"))
.body("Key.PrimaryRegion", equalTo("us-east-1"))
.body("Key.ReplicationStatus", nullValue())
.body("Key.UsingDefaultReplicationRegions", nullValue());
}
@Test
void aReplicationRegionThatIsNotANameIsRefused() {
// The replication regions are names, so a request that names something else is
// refused rather than answered as if it had named no region at all. The shape check
// settles that the member is a list of names, so the refusal is the model's own.
String arn = keyArn();
call("CreateKey", createReplicatedKeyBody("[123]"))
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("ReplicationRegions"));
call("AddKeyReplicationRegions",
"{\"KeyIdentifier\":\"" + arn + "\",\"ReplicationRegions\":[null]}")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("ReplicationRegions"));
}
@Test
void aReplicationRegionThatIsNotAListIsRefused() {
call("CreateKey", createReplicatedKeyBody("\"us-west-2\""))
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("ReplicationRegions"));
}
@Test
void aReplicationRegionOfAnotherPartitionIsRefused() {
// A key is replicated within the partition it is in, as the reference says, so a
// Region of another partition is refused.
call("CreateKey", createReplicatedKeyBody("[\"cn-north-1\"]"))
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("cn-north-1"));
call("EnableDefaultKeyReplicationRegions", """
{"ReplicationRegions":["us-gov-west-1"]}""")
.then().statusCode(400)
.body("__type", equalTo("ValidationException"))
.body("message", containsString("us-gov-west-1"));
}
@Test
void anAliasIsCreatedAndListed() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("CreateAlias", "{\"AliasName\":\"alias/team/card-key\",\"KeyArn\":\"" + arn + "\"}")
.then().statusCode(200)
@@ -551,8 +618,7 @@ class PaymentCryptographyIntegrationTest {
@Test
void anAliasNameIsUniqueInARegion() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("CreateAlias", "{\"AliasName\":\"alias/team/duplicate\",\"KeyArn\":\"" + arn + "\"}")
.then().statusCode(200);
@@ -563,8 +629,7 @@ class PaymentCryptographyIntegrationTest {
@Test
void aKeyIsTaggedAndUntagged() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("TagResource", "{\"ResourceArn\":\"" + arn + "\","
+ "\"Tags\":[{\"Key\":\"Origin\",\"Value\":\"PRIMARY\"}]}")
@@ -594,8 +659,7 @@ class PaymentCryptographyIntegrationTest {
@Test
void aKeyIsDeleted() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
.then().statusCode(200);
@@ -682,8 +746,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void aDeletedKeyIsAnsweredWithTheKey() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
.then().statusCode(200)
@@ -700,8 +763,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void aWaitingPeriodOutsideTheServiceRangeIsRefused() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\",\"DeleteKeyInDays\":1}")
.then().statusCode(400)
@@ -716,8 +778,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void theKeysAreListedByTheirState() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ListKeys", "{\"KeyState\":\"CREATE_COMPLETE\"}")
.then().statusCode(200)
@@ -736,8 +797,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void anAliasIsDetachedFromItsKeyByAnUpdateNamingNoKey() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("CreateAlias", "{\"AliasName\":\"alias/team/detached\",\"KeyArn\":\"" + arn + "\"}")
.then().statusCode(200);
@@ -761,8 +821,7 @@ class PaymentCryptographyIntegrationTest {
.body("Key.Enabled", equalTo(false))
.body("Key.Exportable", equalTo(false));
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("ListTagsForResource", "{\"ResourceArn\":\"" + arn + "\"}")
.then().statusCode(200)
@@ -771,10 +830,8 @@ class PaymentCryptographyIntegrationTest {
@Test
void aTaggingRequestNamesItsKeyInResourceArnOnly() {
String named = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String other = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String named = keyArn();
String other = keyArn();
// The request names one key and another besides it. The change follows the member
// the operation names its key in, which is the member the permission check reads.
@@ -796,8 +853,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void aKeyIsNamedByItsArnOrByAnAliasAndNotByABareId() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
String id = arn.substring(arn.lastIndexOf('/') + 1);
call("CreateAlias", "{\"AliasName\":\"alias/team/named\",\"KeyArn\":\"" + arn + "\"}")
.then().statusCode(200);
@@ -825,8 +881,7 @@ class PaymentCryptographyIntegrationTest {
.body("message", containsString("You can't create an alias without a key."));
// The name was not taken by the refused request.
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
call("CreateAlias", "{\"AliasName\":\"alias/team/reserved\",\"KeyArn\":\"" + arn + "\"}")
.then().statusCode(200)
.body("Alias.AliasName", equalTo("alias/team/reserved"))
@@ -876,8 +931,7 @@ class PaymentCryptographyIntegrationTest {
*/
@Test
void aTaggingRequestNamingItsKeyByAnIdOrAnAliasIsRefused() {
String arn = call("CreateKey", CREATE_KEY).then().statusCode(200)
.extract().path("Key.KeyArn");
String arn = keyArn();
String id = arn.substring(arn.lastIndexOf('/') + 1);
call("CreateAlias", "{\"AliasName\":\"alias/team/tagged\",\"KeyArn\":\"" + arn + "\"}")
.then().statusCode(200);
@@ -24,6 +24,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -417,6 +418,24 @@ class PaymentCryptographyKeyExchangeTest {
assertNotNull(Certificates.parseCertificate(certificate));
}
@Test
void aReplicatedKeyPairKeepsItsHalves() {
// A replica is the same key in another region, so it has to hold the halves the
// primary holds. A replica without them is a record of a key that has none.
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "RSA_2048");
attributes.put("KeyClass", "ASYMMETRIC_KEY_PAIR");
attributes.put("KeyUsage", "TR31_S0_ASYMMETRIC_KEY_FOR_DIGITAL_SIGNATURE");
PaymentCryptographyKey pair = service.createKey("us-east-1", attributes,
Map.of("Sign", Boolean.TRUE), true, true, Map.of(), List.of("us-west-2"));
PaymentCryptographyKey replica = service.findKey("us-west-2", pair.getKeyId());
assertNotNull(replica, "the key was not replicated");
assertEquals(pair.getKeyPublicKeyBase64(), replica.getKeyPublicKeyBase64());
assertEquals(pair.getKeyPrivateKeyBase64(), replica.getKeyPrivateKeyBase64());
}
@Test
void aFormTheServiceDoesNotKnowIsRefused() {
PaymentCryptographyKey key = createKey("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
@@ -30,11 +30,14 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class PaymentCryptographyServiceTest {
private PaymentCryptographyService service;
/** The store the keys live in, for the tests that write a record themselves. */
private InMemoryStorage<String, PaymentCryptographyKey> store;
@BeforeEach
void setUp() {
store = new InMemoryStorage<>();
service = new PaymentCryptographyService(
new InMemoryStorage<>(),
store,
new InMemoryStorage<>(),
new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
@@ -43,22 +46,12 @@ class PaymentCryptographyServiceTest {
/** A key of the given algorithm and class, for the tests that need one. */
private PaymentCryptographyKey createKey(String region, String algorithm, String keyClass,
String usage, Map<String, Boolean> modes) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", algorithm);
attributes.put("KeyClass", keyClass);
attributes.put("KeyUsage", usage);
return service.createKey(region, attributes, modes, true, true, Map.of());
return service.createKey(region, attributes(algorithm, keyClass, usage), modes, true, true,
Map.of());
}
private PaymentCryptographyKey createKey(String region) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_256");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<String, Boolean> modes = new LinkedHashMap<>();
modes.put("Encrypt", Boolean.TRUE);
modes.put("Decrypt", Boolean.TRUE);
return service.createKey(region, attributes, modes, true, true, Map.of());
return service.createKey(region, dataKeyAttributes(), dataKeyModes(), true, true, Map.of());
}
/**
@@ -68,14 +61,11 @@ class PaymentCryptographyServiceTest {
* key: the usages keep the two apart.
*/
private PaymentCryptographyKey createWrappingKey(String region) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_256");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_K1_KEY_BLOCK_PROTECTION_KEY");
Map<String, Boolean> modes = new LinkedHashMap<>();
modes.put("Wrap", Boolean.TRUE);
modes.put("Unwrap", Boolean.TRUE);
return service.createKey(region, attributes, modes, true, true, Map.of());
return service.createKey(region,
attributes("AES_256", "TR31_K1_KEY_BLOCK_PROTECTION_KEY"), modes, true, true, Map.of());
}
@Test
@@ -285,9 +275,7 @@ class PaymentCryptographyServiceTest {
// A store written before the region became part of the name holds its keys under
// their identifier alone, so an alias written then keeps working.
InMemoryStorage<String, PaymentCryptographyKey> store = new InMemoryStorage<>();
PaymentCryptographyService old = new PaymentCryptographyService(store,
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
PaymentCryptographyService old = serviceOverLegacyStore(store);
PaymentCryptographyKey key = createKey("us-east-1");
// The key under the name it was saved under before the region was part of it.
store.put(key.getKeyId(), key);
@@ -301,9 +289,7 @@ class PaymentCryptographyServiceTest {
@Test
void aDeletedKeyIsGoneUnderTheNameItWasSavedUnder() {
InMemoryStorage<String, PaymentCryptographyKey> store = new InMemoryStorage<>();
PaymentCryptographyService old = new PaymentCryptographyService(store,
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
PaymentCryptographyService old = serviceOverLegacyStore(store);
PaymentCryptographyKey key = createKey("us-east-1");
store.put(key.getKeyId(), key);
@@ -370,10 +356,7 @@ class PaymentCryptographyServiceTest {
@Test
void aKeyMayBeCreatedDisabledAndWithTags() {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_256");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<String, Object> attributes = dataKeyAttributes();
PaymentCryptographyKey key = service.createKey("us-east-1", attributes, Map.of(), false,
false, Map.of("owner", "team"));
@@ -737,10 +720,7 @@ class PaymentCryptographyServiceTest {
@Test
void aKeyThatIsNotExportableDoesNotLeaveTheService() {
PaymentCryptographyKey protection = createKey("us-east-1");
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", "AES_256");
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyUsage", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
Map<String, Object> attributes = dataKeyAttributes();
PaymentCryptographyKey key = service.createKey("us-east-1", attributes, Map.of(), false, true, Map.of());
AwsException refused = assertThrows(AwsException.class,
@@ -762,6 +742,549 @@ class PaymentCryptographyServiceTest {
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aKeyIsCreatedInEveryRegionItIsReplicatedTo() {
PaymentCryptographyKey primary = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
assertEquals("us-east-1", primary.getPrimaryRegion());
assertEquals("PRIMARY", primary.getMultiRegionKeyType());
assertEquals(List.of("us-west-2"), primary.getReplicationRegions());
PaymentCryptographyKey replica = service.findKey("us-west-2", primary.getKeyId());
assertNotNull(replica, "the key is not in the region it is replicated to");
assertEquals(primary.getKeyId(), replica.getKeyId());
assertEquals("REPLICA", replica.getMultiRegionKeyType());
assertEquals("us-east-1", replica.getPrimaryRegion());
assertTrue(replica.getArn().contains(":us-west-2:"), replica.getArn());
assertEquals(primary.getKeyMaterialHex(), replica.getKeyMaterialHex());
}
@Test
void aKeyThatIsReplicatedHasToBeExportable() {
Map<String, Object> attributes = dataKeyAttributes();
AwsException refused = assertThrows(AwsException.class, () -> service.createKey("us-east-1",
attributes, Map.of(), false, true, Map.of(), List.of("us-west-2")));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aNameThatIsNotARegionIsRefused() {
// A Region a request names has to be a name of a Region this service serves, and a
// name that is not one of those is refused.
AwsException refused = assertThrows(AwsException.class,
() -> createReplicatedKey(service, "us-east-1", List.of("moon-west-1")));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aRegionOfAnotherPartitionIsRefused() {
// A key is replicated within the partition it is in, as the reference says, so a
// Region of another partition is refused.
AwsException refused = assertThrows(AwsException.class,
() -> createReplicatedKey(service, "us-east-1", List.of("cn-north-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("cn-north-1"), refused.getMessage());
assertNoKeyWasMade();
}
@Test
void aDefaultRegionOfAnotherPartitionIsRefused() {
// The default Regions are the Regions a new key is replicated to, so they are
// within the partition of the Region they are the defaults of.
AwsException refused = assertThrows(AwsException.class,
() -> service.enableDefaultReplicationRegions("us-east-1",
List.of("us-gov-west-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("us-gov-west-1"), refused.getMessage());
assertEquals(List.of(), service.defaultReplicationRegions("us-east-1"));
}
@Test
void aRegionOfAnotherPartitionIsRefusedWhenTheRegionsOfAKeyAreChanged() {
// The same rule holds when the Regions of a key are changed.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
AwsException refused = assertThrows(AwsException.class,
() -> service.addKeyReplicationRegions("us-east-1", key.getKeyId(),
List.of("cn-north-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertEquals(List.of("us-west-2"),
service.findKey("us-east-1", key.getKeyId()).getReplicationRegions(),
"the refused Region is in the replication of the key");
}
@Test
void aKeyIsReplicatedWithinItsOwnPartition() {
// The rule is the partition and not a list of Regions, so a key of one partition is
// replicated to another Region of that partition.
PaymentCryptographyKey primary = createReplicatedKey(service, "cn-north-1",
List.of("cn-northwest-1"));
assertEquals("PRIMARY", primary.getMultiRegionKeyType());
assertEquals("cn-north-1", primary.getPrimaryRegion());
PaymentCryptographyKey replica = service.findKey("cn-northwest-1", primary.getKeyId());
assertNotNull(replica, "the key is not in the region it is replicated to");
assertEquals("REPLICA", replica.getMultiRegionKeyType());
assertEquals(primary.getKeyMaterialHex(), replica.getKeyMaterialHex());
}
@Test
void aKeyIsReplicatedWithinThePartitionOfItsDeployment() {
// The partition of a Region the catalog cannot place is the partition of the
// deployment, which is the one the ARN of the key is minted in, so a key of a
// deployment in another partition is replicated to a Region of that partition.
PaymentCryptographyService china = new PaymentCryptographyService(
new InMemoryStorage<>(), new InMemoryStorage<>(),
new RegionResolver("cn-north-1", "000000000000"),
new PaymentCryptographyRequestContext());
PaymentCryptographyKey primary = createReplicatedKey(china, "local-1", List.of("cn-north-1"));
assertEquals("PRIMARY", primary.getMultiRegionKeyType());
assertTrue(primary.getArn().startsWith("arn:aws-cn:"), primary.getArn());
PaymentCryptographyKey replica = china.findKey("cn-north-1", primary.getKeyId());
assertNotNull(replica, "the key is not in the region it is replicated to");
assertTrue(replica.getArn().startsWith("arn:aws-cn:"), replica.getArn());
}
@Test
void theRegionOfTheRequestIsNotARegionToReplicateTo() {
// The key is in the region of the request already, so naming that region is a request
// that cannot be carried out.
AwsException refused = assertThrows(AwsException.class,
() -> createReplicatedKey(service, "us-east-1", List.of("us-east-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("us-east-1"), refused.getMessage());
assertNoKeyWasMade();
}
@Test
void theRegionOfTheRequestIsNotADefaultReplicationRegion() {
// The default regions of a region are the regions the keys made there are replicated
// to, and the region itself is where they are primary.
AwsException refused = assertThrows(AwsException.class,
() -> service.enableDefaultReplicationRegions("us-east-1", List.of("us-east-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertEquals(List.of(), service.defaultReplicationRegions("us-east-1"));
}
@Test
void aKeyWhoseRegionsAreChangedHasAConfigurationOfItsOwn() {
// A key that took the account's default regions says so, and a key whose regions are
// changed afterwards has a configuration of its own, so it says the other thing.
service.enableDefaultReplicationRegions("us-east-1", List.of("us-west-2"));
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of());
assertTrue(key.isUsingDefaultReplicationRegions());
PaymentCryptographyKey added = service.addKeyReplicationRegions("us-east-1", key.getKeyId(),
List.of("us-west-1"));
assertFalse(added.isUsingDefaultReplicationRegions());
assertEquals(List.of("us-west-2", "us-west-1"), added.getReplicationRegions());
// The replica carries the primary's answer, so it does not say the key takes the
// account's defaults either.
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
assertFalse(replica.isUsingDefaultReplicationRegions());
}
@Test
void theAccountHasDefaultReplicationRegions() {
assertEquals(List.of(), service.defaultReplicationRegions("us-east-1"));
assertEquals(List.of("us-west-2"),
service.enableDefaultReplicationRegions("us-east-1", List.of("us-west-2")));
assertEquals(List.of("us-west-2"), service.defaultReplicationRegions("us-east-1"));
// A key that is created with the default on is in the default region as well.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of());
assertEquals(List.of("us-west-2"), key.getReplicationRegions());
assertTrue(key.isUsingDefaultReplicationRegions());
assertNotNull(service.findKey("us-west-2", key.getKeyId()));
// Turning it off leaves the other regions alone.
assertEquals(List.of("us-west-2", "us-east-2"),
service.enableDefaultReplicationRegions("us-east-1", List.of("us-east-2")));
assertEquals(List.of("us-west-2"),
service.disableDefaultReplicationRegions("us-east-1", List.of("us-east-2")));
assertEquals(List.of(),
service.disableDefaultReplicationRegions("us-east-1", List.of("us-west-2")));
}
@Test
void eachRegionHasItsOwnDefaultReplicationRegions() {
// The settings are the ones of the Region they are read in, so a Region whose keys
// are replicated is not the same as another Region whose keys are not.
service.enableDefaultReplicationRegions("us-east-1", List.of("us-west-2"));
assertEquals(List.of("us-west-2"), service.defaultReplicationRegions("us-east-1"));
assertEquals(List.of(), service.defaultReplicationRegions("us-west-2"));
// A key created in the other Region takes the settings of that Region, which are
// none, so it is not replicated.
PaymentCryptographyKey key = createReplicatedKey(service, "us-west-2", List.of());
assertTrue(key.getReplicationRegions().isEmpty());
assertNull(key.getMultiRegionKeyType());
}
@Test
void theReplicationRegionsOfAKeyCanBeChanged() {
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
PaymentCryptographyKey added = service.addKeyReplicationRegions("us-east-1", key.getKeyId(),
List.of("us-west-1"));
assertEquals(List.of("us-west-2", "us-west-1"), added.getReplicationRegions());
assertNotNull(service.findKey("us-west-1", key.getKeyId()));
PaymentCryptographyKey removed = service.removeKeyReplicationRegions("us-east-1", key.getKeyId(),
List.of("us-west-2"));
assertEquals(List.of("us-west-1"), removed.getReplicationRegions());
assertNull(service.findKey("us-west-2", key.getKeyId()), "the key is in the region it left");
}
@Test
void takingTheLastReplicaAwayEndsTheReplication() {
// Taking the replica regions away is how the replication is turned off for a key, so
// a key that replicates nowhere is not a multi-region key and says so by carrying no
// type at all.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
assertEquals("PRIMARY", key.getMultiRegionKeyType());
PaymentCryptographyKey plain = service.removeKeyReplicationRegions("us-east-1",
key.getKeyId(), List.of("us-west-2"));
assertTrue(plain.getReplicationRegions().isEmpty(), "the key replicates nowhere");
assertNull(plain.getMultiRegionKeyType(), "the key is still a primary");
assertNull(plain.getPrimaryRegion(), "the key still names a primary region");
assertNull(service.findKey("us-west-2", key.getKeyId()), "the key is in the region it left");
}
@Test
void aReplicaIsReadOnly() {
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
AwsException refused = assertThrows(AwsException.class, () -> service.deleteKey(replica));
assertEquals("ValidationException", refused.getErrorCode());
AwsException notPrimary = assertThrows(AwsException.class,
() -> service.addKeyReplicationRegions("us-west-2", key.getKeyId(), List.of("us-west-1")));
assertEquals("ValidationException", notPrimary.getErrorCode());
}
@Test
void aRegionTheKeyAlreadyReplicatesIntoIsRefused() {
// Adding a region the key already replicates into changes nothing, and a request
// that cannot be carried out is refused rather than answered with what it already was.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
AwsException refused = assertThrows(AwsException.class,
() -> service.addKeyReplicationRegions("us-east-1", key.getKeyId(),
List.of("us-west-2")));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("already replicates into"), refused.getMessage());
}
@Test
void aRegionTheKeyDoesNotReplicateIntoIsRefused() {
// There is nothing to take away from a region the key does not replicate into.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
AwsException refused = assertThrows(AwsException.class,
() -> service.removeKeyReplicationRegions("us-east-1", key.getKeyId(),
List.of("us-west-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertTrue(refused.getMessage().contains("does not replicate into"), refused.getMessage());
}
@Test
void theTagsOfAReplicaAreThePrimaries() {
// A replica is a copy of the primary's material and metadata, so it carries the
// primary's tags, and a change to them is replicated.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
service.tag(key, Map.of("owner", "team"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
assertEquals("team", replica.getTags().get("owner"));
assertEquals("team", service.findKey("us-east-1", key.getKeyId()).getTags().get("owner"));
}
@Test
void aReplicaIsReadOnlyForItsOwnMetadata() {
// The tags of a replica are the primary's, so a change to them is made on the primary.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
AwsException refused = assertThrows(AwsException.class,
() -> service.tag(replica, Map.of("owner", "team")));
assertEquals("ValidationException", refused.getErrorCode());
}
@Test
void aRefusedReplicationLeavesNoKeyBehind() {
// The key is refused before it is made, so a request that cannot be carried out
// leaves nothing in the region it was made in.
AwsException refused = assertThrows(AwsException.class,
() -> createReplicatedKey(service, "us-east-1", List.of("moon-west-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertNoKeyWasMade();
}
@Test
void aRefusedImportLeavesNoKeyBehind() {
PaymentCryptographyKey protection = createKey("us-east-1", "AES_256", "SYMMETRIC_KEY",
"TR31_K1_KEY_BLOCK_PROTECTION_KEY",
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE));
PaymentCryptographyKey key = createKey("us-east-1", "AES_256", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE));
String block = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
AwsException refused = assertThrows(AwsException.class,
() -> service.importKey("us-east-1", "Tr31KeyBlock", Map.of(
"WrappingKeyIdentifier", protection.getKeyId(),
"WrappedKeyBlock", block), "", true, Map.of(), List.of("moon-west-1")));
assertEquals("ValidationException", refused.getErrorCode());
assertEquals(2, service.listKeys("us-east-1", null, 10, null).items().size(),
"the refused import left a key in the store");
}
@Test
void aKeyThatIsNotExportableIsNotReplicated() {
// A replica is a copy of the key's material, so a key that may not leave is not
// replicated, and the refusal leaves no key behind.
Map<String, Object> attributes = dataKeyAttributes();
AwsException refused = assertThrows(AwsException.class,
() -> service.createKey("us-east-1", attributes, Map.of(), false, true, Map.of(),
List.of("us-west-2")));
assertEquals("ValidationException", refused.getErrorCode());
assertNoKeyWasMade();
}
@Test
void aKeyThatIsNotExportableIsNotReplicatedToTheDefaultsEither() {
// The defaults are the regions the key takes when the request names none, so a key
// that may not leave is refused there as well.
service.enableDefaultReplicationRegions("us-east-1", List.of("us-west-2"));
Map<String, Object> attributes = dataKeyAttributes();
AwsException refused = assertThrows(AwsException.class,
() -> service.createKey("us-east-1", attributes, Map.of(), false, true, Map.of(),
List.of()));
assertEquals("ValidationException", refused.getErrorCode());
assertNoKeyWasMade();
}
@Test
void aRegionTheKeyIsAlreadyInIsNotAReplicationTarget() {
// The key is in its own region already, so naming that region again is a request
// that cannot be carried out, and the key does not become a multi-region key.
PaymentCryptographyKey key = createKey("us-east-1");
AwsException refused = assertThrows(AwsException.class,
() -> service.addKeyReplicationRegions("us-east-1", key.getKeyId(),
List.of("us-east-1")));
assertEquals("ValidationException", refused.getErrorCode());
PaymentCryptographyKey current = service.findKey("us-east-1", key.getKeyId());
assertNull(current.getMultiRegionKeyType(), "the key is a multi-region key with no replica");
assertTrue(current.getReplicationRegions().isEmpty());
}
@Test
void aRequestThatNamesNoRegionToAddIsRefused() {
PaymentCryptographyKey key = createKey("us-east-1");
AwsException refused = assertThrows(AwsException.class,
() -> service.addKeyReplicationRegions("us-east-1", key.getKeyId(), List.of()));
assertEquals("ValidationException", refused.getErrorCode());
assertNull(service.findKey("us-east-1", key.getKeyId()).getMultiRegionKeyType());
}
@Test
void theRegionsOfAReplicaFollowThePrimary() {
// A replica reports the regions the primary is in, so it does not report a region
// the primary has left behind.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
service.addKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-1"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
assertEquals(List.of("us-west-2", "us-west-1"), replica.getReplicationRegions());
service.removeKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-2"));
PaymentCryptographyKey left = service.findKey("us-west-1", key.getKeyId());
assertEquals(List.of("us-west-1"), left.getReplicationRegions());
}
@Test
void aReplicaThatIsLeftBehindReportsTheRegionsThePrimaryHasNow() {
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
service.removeKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-2"));
assertNull(service.findKey("us-west-2", key.getKeyId()), "the replica is still there");
PaymentCryptographyKey primary = service.findKey("us-east-1", key.getKeyId());
assertNull(primary.getMultiRegionKeyType(), "the key is still a multi-region key");
assertTrue(primary.getReplicationRegions().isEmpty());
}
@Test
void theAliasesOfARemovedReplicaGoWithIt() {
// An alias that names a key that is not there cannot be resolved, so it goes when
// the replica does.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
service.createAlias("alias/team/card-key", replica);
assertNotNull(service.findAlias("us-west-2", "alias/team/card-key"));
service.removeKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-2"));
assertNull(service.findAlias("us-west-2", "alias/team/card-key"),
"the alias of the removed replica is still there");
assertEquals(0, service.listAliases("us-west-2", null).size());
}
@Test
void theAliasesOfAReplicaGoWithThePrimary() {
// A replica shares the identifier of its primary, so the aliases that name the
// replica are the aliases of the key, and they go when the key goes.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
service.createAlias("alias/team/card-key", replica);
PaymentCryptographyKey primary = service.findKey("us-east-1", key.getKeyId());
service.createAlias("alias/team/primary-key", primary);
service.deleteKey(primary);
assertNull(service.findAlias("us-west-2", "alias/team/card-key"),
"the alias of the replica is still there");
assertNull(service.findAlias("us-east-1", "alias/team/primary-key"),
"the alias of the primary is still there");
}
@Test
void aReplicaCarriesTheMetadataOfItsPrimary() {
// A replica is a copy of the primary's material and metadata, so every change made
// on the primary reaches it: its tags, its state, whether it is enabled, and the
// regions it replicates to.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
service.tag(key, Map.of("owner", "team"));
service.addKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-1"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
PaymentCryptographyKey primary = service.findKey("us-east-1", key.getKeyId());
assertEquals(primary.getTags(), replica.getTags());
assertEquals(primary.getKeyState(), replica.getKeyState());
assertEquals(primary.isEnabled(), replica.isEnabled());
assertEquals(primary.getPrimaryRegion(), replica.getPrimaryRegion());
assertEquals(primary.getReplicationRegions(), replica.getReplicationRegions());
assertEquals(primary.isUsingDefaultReplicationRegions(),
replica.isUsingDefaultReplicationRegions());
}
@Test
void replicatingAKeySavedUnderTheOldNameKeepsOneRecordOfIt() {
// A store written before the region became part of the name holds its keys under
// their identifier alone, so replicating one moves it to the name the store holds it
// under now, and the list does not answer with the key twice.
InMemoryStorage<String, PaymentCryptographyKey> store = new InMemoryStorage<>();
PaymentCryptographyService old = serviceOverLegacyStore(store);
PaymentCryptographyKey key = createKey("us-east-1");
// The key under the name it was saved under before the region was part of it.
store.put(key.getKeyId(), key);
old.addKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-2"));
assertEquals(1, old.listKeys("us-east-1", null, 10, null).items().size(),
"the key is in the list twice");
assertNull(store.get(key.getKeyId()).orElse(null),
"the key is still under the name it was saved under");
}
@Test
void aReplicaIsUsableOnItsOwn() {
// A replica is a complete copy of the key, so the key leaves the service from the
// region the replica is in as well as from the primary's.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
PaymentCryptographyKey protection = createWrappingKey("us-west-2");
Map<String, Object> answer = exportTr31Answer("us-west-2", key.getKeyId(),
protection.getKeyId());
Map<?, ?> wrapped = (Map<?, ?>) answer.get("WrappedKey");
String export = (String) wrapped.get("KeyMaterial");
assertTrue(export.length() > 32, "the block is only its header");
assertEquals(key.getKeyCheckValue(), wrapped.get("KeyCheckValue"));
PaymentCryptographyKey imported = importTr31("us-west-2", protection.getKeyId(), export);
assertEquals(key.getKeyMaterialHex(), imported.getKeyMaterialHex());
}
@Test
void aReplicaThatIsAlreadyThereTakesThePrimariesTags() {
// A replica is a copy of the primary's material and metadata, so a replica that is
// already there takes the primary's tags when the replication changes.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
PaymentCryptographyKey primary = service.findKey("us-east-1", key.getKeyId());
primary.getTags().put("owner", "team");
store.put("us-east-1\u0000" + key.getKeyId(), primary);
// A replica whose tags are not the primary's, as a record written before the tags
// were replicated may hold.
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
replica.setTags(new LinkedHashMap<>(Map.of("owner", "other")));
store.put("us-west-2\u0000" + key.getKeyId(), replica);
service.addKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-1"));
PaymentCryptographyKey after = service.findKey("us-west-2", key.getKeyId());
assertEquals("team", after.getTags().get("owner"), "the replica kept the tags it had");
}
@Test
void aReplicaThatIsLeftBehindTakesThePrimariesTags() {
// The same holds for the replicas that survive a removal of a region.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
service.addKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-1"));
PaymentCryptographyKey primary = service.findKey("us-east-1", key.getKeyId());
primary.getTags().put("owner", "team");
store.put("us-east-1\u0000" + key.getKeyId(), primary);
PaymentCryptographyKey replica = service.findKey("us-west-1", key.getKeyId());
replica.setTags(new LinkedHashMap<>(Map.of("owner", "other")));
store.put("us-west-1\u0000" + key.getKeyId(), replica);
service.removeKeyReplicationRegions("us-east-1", key.getKeyId(), List.of("us-west-2"));
PaymentCryptographyKey after = service.findKey("us-west-1", key.getKeyId());
assertEquals("team", after.getTags().get("owner"), "the replica kept the tags it had");
}
/**
* A key of the data the cipher protects, replicated to the regions named.
*
* @param service the service the key is made in
* @param region the region the key is made in
* @param regions the regions the key is replicated to
*/
private static PaymentCryptographyKey createReplicatedKey(PaymentCryptographyService service, String region,
List<String> regions) {
return service.createKey(region, dataKeyAttributes(), dataKeyModes(), true, true, Map.of(), regions);
}
/**
* The TR-31 key block a key leaves the service in.
*/
@@ -787,12 +1310,94 @@ class PaymentCryptographyServiceTest {
"WrappedKeyBlock", block), "", true, Map.of());
}
@Test
void anImportedKeyIsReplicatedToTheRegionsTheRequestNames() {
// The model gives an import the same replication regions a creation does, so a key
// that comes in can be replicated as soon as it lands.
PaymentCryptographyKey protection = createKey("us-east-1", "AES_256", "SYMMETRIC_KEY",
"TR31_K1_KEY_BLOCK_PROTECTION_KEY",
Map.of("Wrap", Boolean.TRUE, "Unwrap", Boolean.TRUE));
PaymentCryptographyKey key = createKey("us-east-1", "AES_256", "SYMMETRIC_KEY",
"TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY",
Map.of("Encrypt", Boolean.TRUE, "Decrypt", Boolean.TRUE));
String block = exportTr31("us-east-1", key.getKeyId(), protection.getKeyId());
PaymentCryptographyKey imported = service.importKey("us-east-1", "Tr31KeyBlock", Map.of(
"WrappingKeyIdentifier", protection.getKeyId(),
"WrappedKeyBlock", block), "", true, Map.of(), List.of("us-west-2"));
assertEquals("PRIMARY", imported.getMultiRegionKeyType());
assertEquals("us-east-1", imported.getPrimaryRegion());
assertEquals(List.of("us-west-2"), imported.getReplicationRegions());
PaymentCryptographyKey replica = service.findKey("us-west-2", imported.getKeyId());
assertNotNull(replica, "the key was not replicated");
assertEquals("REPLICA", replica.getMultiRegionKeyType());
assertEquals(imported.getKeyMaterialHex(), replica.getKeyMaterialHex());
}
@Test
void theTagsOfAReplicaFollowThePrimary() {
// A replica is a copy of its primary's material and metadata, so a change to the
// primary's tags reaches it.
PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
service.tag(key, Map.of("owner", "team"));
PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId());
assertEquals("team", replica.getTags().get("owner"));
service.untag(key, List.of("owner"));
PaymentCryptographyKey after = service.findKey("us-west-2", key.getKeyId());
assertNull(after.getTags().get("owner"), "the tag was not taken away");
}
/** 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);
}
/** The attributes of a key with that algorithm, class and usage. */
private static Map<String, Object> attributes(String algorithm, String keyClass, String usage) {
Map<String, Object> attributes = new LinkedHashMap<>();
attributes.put("KeyAlgorithm", algorithm);
attributes.put("KeyClass", "SYMMETRIC_KEY");
attributes.put("KeyClass", keyClass);
attributes.put("KeyUsage", usage);
return attributes;
}
/** The attributes of an AES-256 data encryption key. */
private static Map<String, Object> dataKeyAttributes() {
return attributes("AES_256", "TR31_D0_SYMMETRIC_DATA_ENCRYPTION_KEY");
}
/** The modes of use of a data encryption key. */
private static Map<String, Boolean> dataKeyModes() {
Map<String, Boolean> modes = new LinkedHashMap<>();
modes.put("Encrypt", Boolean.TRUE);
modes.put("Decrypt", Boolean.TRUE);
return modes;
}
/**
* The service over a store that holds its keys under their identifier alone.
*
* <p>A store written before the region became part of the name holds its keys under
* their identifier alone, and the tests that need such a store make one.
*
* @param store the store the service keeps its keys in
*/
private static PaymentCryptographyService serviceOverLegacyStore(
InMemoryStorage<String, PaymentCryptographyKey> store) {
return new PaymentCryptographyService(store,
new InMemoryStorage<>(), new RegionResolver("us-east-1", "000000000000"),
new PaymentCryptographyRequestContext());
}
/** That a refused request left no key behind. */
private void assertNoKeyWasMade() {
assertEquals(0, service.listKeys("us-east-1", null, 10, null).items().size(),
"the refused request left a key in the store");
}
}