diff --git a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats index 1a7512512e..1426e1a112 100644 --- a/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats +++ b/compatibility-tests/sdk-test-awscli/test/payment-cryptography-control-plane.bats @@ -118,6 +118,7 @@ create_key() { assert_failure [[ "$output" == *"ValidationException"* ]] } + @test "Payment Cryptography control plane: a key is stopped and started again" { KEY_ARN=$(create_key AES_256) [ -n "$KEY_ARN" ] @@ -133,6 +134,26 @@ create_key() { [ -n "$(json_get "$output" '.Key.UsageStartTimestamp')" ] } +@test "Payment Cryptography control plane: a deleted key is restored" { + KEY_ARN=$(create_key AES_256) + [ -n "$KEY_ARN" ] + + run aws_cmd payment-cryptography delete-key --key-identifier "$KEY_ARN" + assert_success + [ "$(json_get "$output" '.Key.KeyState')" = "DELETE_PENDING" ] + + run aws_cmd payment-cryptography get-key --key-identifier "$KEY_ARN" + assert_success + [ "$(json_get "$output" '.Key.KeyState')" = "DELETE_PENDING" ] + + run aws_cmd payment-cryptography restore-key --key-identifier "$KEY_ARN" + assert_success + [ "$(json_get "$output" '.Key.KeyState')" = "CREATE_COMPLETE" ] + # The reference's own restore example answers with a key that is disabled: it is + # start-key-usage that enables a key again. + [ "$(json_get "$output" '.Key.Enabled')" = "false" ] +} + @test "Payment Cryptography control plane: a key pair is created with the usage its derived keys have" { # The usage a derived key is for is named when the key pair is made, as the export # guide's key agreement flow does. diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java index 355e9dcee2..99ab1f7e7a 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/PaymentCryptographyTest.java @@ -785,6 +785,20 @@ class PaymentCryptographyTest { assertThat(deleted.enabled()).isFalse(); } + @Test + void aDeletedKeyIsRestored() { + Key created = createAesKey(); + client.deleteKey(k -> k.keyIdentifier(created.keyArn())); + + Key restored = client.restoreKey(k -> k.keyIdentifier(created.keyArn())).key(); + + assertThat(restored.keyState()).isEqualTo(KeyState.CREATE_COMPLETE); + // The reference's own restore example answers with a key that is disabled: it is + // StartKeyUsage that enables a key again. + assertThat(restored.enabled()).isFalse(); + assertThat(restored.deletePendingTimestamp()).isNull(); + } + /** A listing names the state of the keys it wants, and the service answers with those keys alone. */ @Test void theKeysAreListedByTheirState() { diff --git a/docs/services/index.md b/docs/services/index.md index 338bf3f02c..db3a3e1280 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -34,7 +34,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [CloudHSM v2](cloudhsmv2.md) | `POST /` + `X-Amz-Target: BaldrApiService.*` | JSON 1.1 | 18 | | [Kinesis](kinesis.md) | `POST /` + `X-Amz-Target: Kinesis_20131202.*` | JSON 1.1 | 32 | | [Managed Service for Apache Flink](kinesisanalytics.md) | `POST /` + `X-Amz-Target: KinesisAnalytics_20180523.*` | JSON 1.1 | 15 | -| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 27 | +| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 28 | | [Payment Cryptography data plane](payment-cryptography-data.md) | `POST /keys/{KeyIdentifier}/encrypt` and the rest | REST JSON | 12 | | [Secrets Manager](secrets-manager.md) | `POST /` + `X-Amz-Target: secretsmanager.*` | JSON 1.1 | 23 | | [Step Functions](step-functions.md) | `POST /` + `X-Amz-Target: AmazonStatesService.*` | JSON 1.1 | 32 | diff --git a/docs/services/payment-cryptography.md b/docs/services/payment-cryptography.md index f0d2d44127..29eccbfb87 100644 --- a/docs/services/payment-cryptography.md +++ b/docs/services/payment-cryptography.md @@ -11,7 +11,8 @@ | `CreateKey` | Create a key with fresh material | | `GetKey` | Get a key's attributes, state and check value | | `ListKeys` | List the keys of a region | -| `DeleteKey` | Delete a key | +| `DeleteKey` | Schedule a key for deletion | +| `RestoreKey` | Cancel a scheduled key deletion | | `StartKeyUsage` | Start the use of a key | | `StopKeyUsage` | Stop the use of a key | | `CreateAlias` | Point an alias name at a key | @@ -54,11 +55,21 @@ 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. +- **Deletion and restore:** `DeleteKey` disables the key and answers with the key, its + state `DELETE_PENDING` and the moment its deletion takes effect. The key is kept, so it + stays readable and keeps its aliases and tags until the waiting period ends. + `DeleteKeyInDays` is checked against the range the model states. `RestoreKey` cancels a + scheduled deletion and returns the key to `CREATE_COMPLETE` with no pending deletion + timestamp; a key that is not pending deletion is refused with `ConflictException`. The + reference's own example of the restore says that two members change, the state and the + pending timestamp, so the restored key stays disabled and keeps the moments of its use: + it is `StartKeyUsage` that enables a key again. The waiting period is not swept by a + timer: the emulator keeps the key pending rather than deleting it on a clock. A key that + is already pending deletion is refused with `ConflictException`, because the deletion is + already under way, and the replicas of the key carry its pending state and the moment the + deletion takes effect, as they carry the rest of its metadata. A replica is read-only, so + the deletion is cancelled on the primary: a request that names a replica is refused with + `ValidationException`. - **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 @@ -245,7 +256,8 @@ on, so a policy that names another key is refused. The reference attaches a policy to the primary key alone, so a replica takes none and a request that names one is refused. The access the policy grants is not enforced: the service's operations are not among the ones - IAM checks. + IAM checks. A key that is pending deletion keeps its policy, because the key is still + there. - **Key usage:** `StopKeyUsage` disables the key and records when it stopped, and `StartKeyUsage` enables it again and records when it started. The moment recorded is the moment the key changed state, so a request that names a key that is already in the state @@ -253,9 +265,12 @@ readable and its material stays where it is, so it can be started again. A replica is read-only, so the change is made on the primary, and a request that names a replica is refused. The change reaches the replicas: a stop on the primary stops the use of the - replicas too, as the reference says. -- **Not yet emulated:** the key restore operation, the multi-party approval operations - and the certificate signing request. + replicas too, as the reference says. A key that is pending deletion is not the caller's + to start or stop: the reference does not publish the answer for that case, so the + request is refused with `ConflictException`, which is the code the service uses for a + request that conflicts with the state of a key. +- **Not yet emulated:** the multi-party approval operations and the certificate signing + request. ## Configuration diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java index dab93c161d..8b9ea19560 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java @@ -65,6 +65,7 @@ public class PaymentCryptographyJsonHandler { case "GetKey" -> () -> getKey(request, region); case "ListKeys" -> () -> listKeys(request, region); case "DeleteKey" -> () -> deleteKey(request, region); + case "RestoreKey" -> () -> restoreKey(request, region); case "StartKeyUsage" -> () -> startKeyUsage(request, region); case "StopKeyUsage" -> () -> stopKeyUsage(request, region); case "CreateAlias" -> () -> createAlias(request, region); @@ -181,14 +182,24 @@ public class PaymentCryptographyJsonHandler { } /** - * Deletes a key and answers with the key, as the reference does. + * Schedules a key for deletion and answers with the key, as the reference does. * - *
The waiting period the reference offers is read, and the key is - * deleted at once all the same: the service deletes a key the moment it - * is asked to. + *
The waiting period is the one the request names, or the reference's default of
+ * seven days. The model settles the range, so a period outside it is refused before
+ * the key is touched.
*/
private Map The service deletes a key the moment it is asked to, so the waiting
- * period the service offers is not one: the key is gone when the answer
- * goes out. The answer carries only the pending timestamp of that
- * deletion; the delete timestamp stays unset, because the key is already
- * gone when the answer goes out.
- *
- * The lock is the same one the tagging operations take, so a key that
- * is being tagged cannot be written back after it was deleted.
+ * Schedules a key for deletion after the reference's default waiting period, seven days.
*/
public synchronized PaymentCryptographyKey deleteKey(PaymentCryptographyKey key) {
+ return deleteKey(key, 7);
+ }
+
+ /**
+ * Schedules a key for deletion and answers with the key as it now stands.
+ *
+ * The key is disabled and stays in the store, in the state {@code DELETE_PENDING},
+ * until the waiting period ends. The key is therefore still readable and still named by
+ * its aliases, and {@link #restoreKey(PaymentCryptographyKey)} can cancel the deletion.
+ * The waiting period is a promise to the caller, not a sweep this service runs: a key
+ * stays pending rather than disappearing on a timer the emulator does not have.
+ *
+ * The pending timestamp is the moment the deletion takes effect, and the deletion
+ * timestamp is unset while the key has not been deleted.
+ *
+ * A key that is already pending deletion is refused with {@code ConflictException},
+ * as the reference refuses it: the deletion is already under way.
+ */
+ public synchronized PaymentCryptographyKey deleteKey(PaymentCryptographyKey key, int days) {
+ PaymentCryptographyKey current = liveKey(key);
// A replica is read-only: only the primary may be deleted.
- requireNotReplica(key, "only the primary may be deleted");
+ requireNotReplica(current, "only the primary may be deleted");
+ requireNotPendingDeletion(current, "it cannot be deleted again");
long now = clock.instant().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());
- // 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;
+ current.setKeyState("DELETE_PENDING");
+ current.setEnabled(false);
+ current.setDeletePendingTimestamp(now + days * 86_400L);
+ current.setDeleteTimestamp(0);
+ storeKey(current);
+ // The replicas of a key carry the state of their primary, so a key that is pending
+ // deletion is pending deletion in every region it replicates into.
+ refreshReplicas(current, current.getReplicationRegions());
+ return current;
+ }
+
+ /**
+ * Cancels the scheduled deletion of a key and answers with the key as it now stands.
+ *
+ * Only a key in the state {@code DELETE_PENDING} can be restored; one that is not
+ * pending deletion is refused with {@code ConflictException}, as the reference refuses
+ * it.
+ *
+ * The reference's own example of the restore says that two members change: the state
+ * goes back to {@code CREATE_COMPLETE} and the pending timestamp is removed. The key
+ * stays disabled, because the deletion disabled it and it is {@code StartKeyUsage} that
+ * enables a key again, and the moments of its use are the ones it had.
+ *
+ * A replica is read-only, so the deletion is cancelled on the primary: a replica
+ * that was restored on its own would be usable while the key it is a copy of is still
+ * pending deletion.
+ */
+ public synchronized PaymentCryptographyKey restoreKey(PaymentCryptographyKey key) {
+ PaymentCryptographyKey current = liveKey(key);
+ requireNotReplica(current, "only the primary may be restored");
+ requirePendingDeletion(current, "it cannot be restored");
+ current.setKeyState("CREATE_COMPLETE");
+ current.setDeletePendingTimestamp(0);
+ current.setDeleteTimestamp(0);
+ storeKey(current);
+ // The replicas of a key carry the state of their primary, so a key that is restored
+ // is restored in every region it replicates into.
+ refreshReplicas(current, current.getReplicationRegions());
+ return current;
}
// ---- key usage -----------------------------------------------------------
@@ -411,6 +442,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
public synchronized PaymentCryptographyKey startKeyUsage(PaymentCryptographyKey key) {
PaymentCryptographyKey current = liveKey(key);
requireNotReplica(current, "a replica is read-only");
+ requireNotPendingDeletion(current, "its use cannot be started");
if (!current.isEnabled()) {
current.setEnabled(true);
current.setUsageStartTimestamp(clock.instant().getEpochSecond());
@@ -437,6 +469,7 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
public synchronized PaymentCryptographyKey stopKeyUsage(PaymentCryptographyKey key) {
PaymentCryptographyKey current = liveKey(key);
requireNotReplica(current, "a replica is read-only");
+ requireNotPendingDeletion(current, "its use cannot be stopped");
if (current.isEnabled()) {
current.setEnabled(false);
current.setUsageStopTimestamp(clock.instant().getEpochSecond());
@@ -649,6 +682,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
replica.setEnabled(primary.isEnabled());
replica.setUsageStartTimestamp(primary.getUsageStartTimestamp());
replica.setUsageStopTimestamp(primary.getUsageStopTimestamp());
+ replica.setDeletePendingTimestamp(primary.getDeletePendingTimestamp());
+ replica.setDeleteTimestamp(primary.getDeleteTimestamp());
replica.setUsingDefaultReplicationRegions(primary.isUsingDefaultReplicationRegions());
replica.setPrimaryRegion(primary.getPrimaryRegion());
replica.setReplicationRegions(new ArrayList<>(primary.getReplicationRegions()));
@@ -674,6 +709,42 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
}
}
+ /**
+ * The refusal of a request that names a key whose deletion is under way.
+ *
+ * A key that is pending deletion is disabled and on its way out, so the use of it is
+ * not the caller's to change: the deletion is cancelled with
+ * {@link #restoreKey(PaymentCryptographyKey)} instead. The reference does not publish
+ * the answer for this case, so the service refuses the request with
+ * {@code ConflictException}, which is the code it uses for a request that conflicts with
+ * the state of a key.
+ *
+ * @param key the key the request names
+ * @param what what the request wanted to do with the key, for the message
+ */
+ private static void requireNotPendingDeletion(PaymentCryptographyKey key, String what) {
+ if ("DELETE_PENDING".equals(key.getKeyState())) {
+ throw new AwsException("ConflictException",
+ "the key " + key.getArn() + " is pending deletion, and " + what, 400);
+ }
+ }
+
+ /**
+ * The refusal of a request that names a key whose deletion is not under way.
+ *
+ * A scheduled deletion is cancelled while it is under way, so a key that is not
+ * pending deletion has nothing to cancel.
+ *
+ * @param key the key the request names
+ * @param what what the request wanted to do with the key, for the message
+ */
+ private static void requirePendingDeletion(PaymentCryptographyKey key, String what) {
+ if (!"DELETE_PENDING".equals(key.getKeyState())) {
+ throw new AwsException("ConflictException",
+ "the key " + key.getArn() + " is not pending deletion, and " + what, 400);
+ }
+ }
+
/**
* The tags of a key.
*
@@ -1671,6 +1742,8 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
replica.setCreateTimestamp(primary.getCreateTimestamp());
replica.setUsageStartTimestamp(primary.getUsageStartTimestamp());
replica.setUsageStopTimestamp(primary.getUsageStopTimestamp());
+ replica.setDeletePendingTimestamp(primary.getDeletePendingTimestamp());
+ replica.setDeleteTimestamp(primary.getDeleteTimestamp());
replica.setPrimaryRegion(primary.getPrimaryRegion());
replica.setReplicationRegions(new ArrayList<>(primary.getReplicationRegions()));
replica.setMultiRegionKeyType("REPLICA");
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
index 7853a12c5f..d50da6e7e6 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyIntegrationTest.java
@@ -31,6 +31,7 @@ import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.matchesPattern;
+import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@@ -974,15 +975,37 @@ class PaymentCryptographyIntegrationTest {
}
@Test
- void aKeyIsDeleted() {
+ void aKeyIsDeletedAndStaysReadableWhileItIsPending() {
String arn = keyArn();
call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
.then().statusCode(200);
call("GetKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
+ .then().statusCode(200)
+ .body("Key.KeyState", equalTo("DELETE_PENDING"));
+ }
+
+ @Test
+ void aDeletedKeyIsRestored() {
+ String arn = keyArn();
+ call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
+ .then().statusCode(200);
+
+ call("RestoreKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
+ .then().statusCode(200)
+ .body("Key.KeyState", equalTo("CREATE_COMPLETE"))
+ .body("Key.Enabled", equalTo(false))
+ .body("Key.DeletePendingTimestamp", nullValue());
+ }
+
+ @Test
+ void aKeyThatIsNotPendingDeletionIsNotRestored() {
+ String arn = keyArn();
+
+ call("RestoreKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
.then().statusCode(400)
- .body("__type", containsString("ResourceNotFoundException"));
+ .body("__type", containsString("ConflictException"));
}
@Test
@@ -998,11 +1021,11 @@ class PaymentCryptographyIntegrationTest {
// as the unknown operation it is. The body it carries does not change that: a body
// that breaks the model's rules is not the answer to an operation that is not
// served at all.
- call("RestoreKey", "{}")
+ call("GetCertificateSigningRequest", "{}")
.then().statusCode(400)
.body("__type", containsString("UnknownOperationException"));
- call("RestoreKey", "{\"KeyIdentifier\":\"arn:aws:payment-cryptography:us-east-1:"
- + "000000000000:key/abcdefghijklmnop\"}")
+ call("GetCertificateSigningRequest", "{\"KeyIdentifier\":\"arn:aws:payment-cryptography:"
+ + "us-east-1:000000000000:key/abcdefghijklmnop\"}")
.then().statusCode(400)
.body("__type", containsString("UnknownOperationException"));
}
@@ -1081,10 +1104,14 @@ class PaymentCryptographyIntegrationTest {
void aWaitingPeriodOutsideTheServiceRangeIsRefused() {
String arn = keyArn();
- call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\",\"DeleteKeyInDays\":1}")
+ call("DeleteKey", """
+ {"KeyIdentifier":"%s","DeleteKeyInDays":1}
+ """.formatted(arn))
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
- call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\",\"DeleteKeyInDays\":7}")
+ call("DeleteKey", """
+ {"KeyIdentifier":"%s","DeleteKeyInDays":7}
+ """.formatted(arn))
.then().statusCode(200);
}
@@ -1095,8 +1122,9 @@ class PaymentCryptographyIntegrationTest {
@Test
void theKeysAreListedByTheirState() {
String arn = keyArn();
- cleanup.register(() -> call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
- .then().statusCode(200));
+ // The key this test deletes is not cleaned up again: a deletion of a key that is
+ // already pending deletion is refused, and the key stays pending until the waiting
+ // period ends.
String secondArn = keyArn();
cleanup.register(() -> call("DeleteKey", "{\"KeyIdentifier\":\"" + secondArn + "\"}")
.then().statusCode(200));
@@ -1119,7 +1147,18 @@ class PaymentCryptographyIntegrationTest {
assertThat(listedArns, hasItems(arn, secondArn));
call("ListKeys", "{\"KeyState\":\"DELETE_PENDING\"}")
.then().statusCode(200)
- .body("Keys", hasSize(0));
+ .body("Keys.KeyArn", not(hasItem(equalTo(arn))));
+
+ call("DeleteKey", "{\"KeyIdentifier\":\"" + arn + "\"}")
+ .then().statusCode(200);
+
+ call("ListKeys", "{\"KeyState\":\"CREATE_COMPLETE\"}")
+ .then().statusCode(200)
+ .body("Keys.KeyArn", not(hasItem(equalTo(arn))));
+ call("ListKeys", "{\"KeyState\":\"DELETE_PENDING\"}")
+ .then().statusCode(200)
+ .body("Keys.KeyArn", hasItem(equalTo(arn)));
+
call("ListKeys", "{\"KeyState\":\"NO_SUCH_STATE\"}")
.then().statusCode(400)
.body("__type", containsString("ValidationException"));
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
index aa4c8f8ba4..61c01e9e84 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
@@ -311,7 +311,7 @@ class PaymentCryptographyServiceTest {
}
@Test
- void aDeletedKeyIsGoneUnderTheNameItWasSavedUnder() {
+ void aDeletedKeyIsFoundUnderTheNameItIsSavedUnderNow() {
InMemoryStorage