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

@@ -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");
}
}