From 33ed71437d021060b62f1e4390cf680c6ffd570f Mon Sep 17 00:00:00 2001 From: Murtuza Chhil Date: Wed, 18 Nov 2026 06:53:28 +0530 Subject: [PATCH] feat(paymentcryptography): a deletion is scheduled, and it can be cancelled (#8799) DeleteKey removed a key at once, so there was no waiting period and nothing to cancel. It now schedules the deletion: the key is disabled and kept as DELETE_PENDING, with the moment the deletion takes effect after the DeleteKeyInDays waiting period (seven days by default), and it keeps its aliases, tags and resource policy. Floci does not sweep the period, so the key stays pending. RestoreKey cancels the deletion: the key returns to CREATE_COMPLETE without a pending timestamp and stays disabled until StartKeyUsage, as the guide's example shows. Replicas carry the pending state and its timestamp, a replica is not restored on its own, and a pending key refuses another deletion, StartKeyUsage and StopKeyUsage with ConflictException. --- .../payment-cryptography-control-plane.bats | 21 ++ .../floci/test/PaymentCryptographyTest.java | 14 ++ docs/services/index.md | 2 +- docs/services/payment-cryptography.md | 35 +++- .../PaymentCryptographyJsonHandler.java | 21 +- .../PaymentCryptographyService.java | 135 ++++++++++--- .../PaymentCryptographyIntegrationTest.java | 59 +++++- .../PaymentCryptographyServiceTest.java | 191 ++++++++++++++---- 8 files changed, 378 insertions(+), 100 deletions(-) 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 deleteKey(JsonNode request, String region) { - PaymentCryptographyKey key = service.deleteKey(requiredKey(request, region, KEY_IDENTIFIER)); + int days = request.hasNonNull("DeleteKeyInDays") + ? request.path("DeleteKeyInDays").asInt() : 7; + PaymentCryptographyKey key = service.deleteKey( + requiredKey(request, region, KEY_IDENTIFIER), days); + return Map.of("Key", keyObject(key)); + } + + /** Cancels the scheduled deletion of a key. */ + private Map restoreKey(JsonNode request, String region) { + PaymentCryptographyKey key = service.restoreKey( + requiredKey(request, region, KEY_IDENTIFIER)); return Map.of("Key", keyObject(key)); } diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java index c794a55ef4..8693a61514 100644 --- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java +++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyService.java @@ -22,7 +22,6 @@ import jakarta.inject.Inject; import java.security.KeyPair; import java.security.SecureRandom; import java.time.Clock; -import java.time.Instant; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; @@ -359,40 +358,72 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn } /** - * Removes a key and answers the key as the service does when a deletion is - * scheduled: the key's own metadata, its state {@code DELETE_PENDING} and - * the pending timestamp of that deletion. - * - *

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 store = new InMemoryStorage<>(); PaymentCryptographyService old = serviceOverLegacyStore(store); PaymentCryptographyKey key = createKey("us-east-1"); @@ -320,7 +320,9 @@ class PaymentCryptographyServiceTest { old.deleteKey(key); assertNull(store.get(key.getKeyId()).orElse(null), - "the key is gone under the name it was saved under too"); + "the key is still under the name that was replaced"); + assertEquals("DELETE_PENDING", + old.findKey("us-east-1", key.getArn()).getKeyState()); } @Test @@ -369,13 +371,14 @@ class PaymentCryptographyServiceTest { } @Test - void aDeletedKeyTakesItsAliasesWithIt() { + void aDeletedKeyKeepsItsAliasesWhileItIsPending() { PaymentCryptographyKey key = createKey("us-east-1"); service.createAlias("alias/team/card-key", key); service.deleteKey(key); - assertNull(service.findKey("us-east-1", key.getArn())); - assertNull(service.findAlias("us-east-1", "alias/team/card-key")); + assertEquals("DELETE_PENDING", service.findKey("us-east-1", key.getArn()).getKeyState()); + assertNotNull(service.findAlias("us-east-1", "alias/team/card-key"), + "the alias went with a key that is still there"); } @Test @@ -390,15 +393,135 @@ class PaymentCryptographyServiceTest { } @Test - void aDeletedKeyDoesNotComeBackWhenItIsTagged() { + void aDeletedKeyKeepsItsTagsWhileItIsPending() { + PaymentCryptographyKey key = createKey("us-east-1"); + service.tag(key, Map.of("owner", "team")); + service.deleteKey(key); + + assertEquals("team", service.listTags(key).get("owner")); + assertEquals("DELETE_PENDING", service.findKey("us-east-1", key.getArn()).getKeyState()); + } + + + @Test + void aScheduledDeletionCarriesTheMomentItTakesEffect() { + // The reference says the pending timestamp is the date and time after which the key + // is deleted, and that the waiting period is seven days unless the request names + // one. + PaymentCryptographyKey key = createKey("us-east-1"); + long before = Instant.now().getEpochSecond(); + + PaymentCryptographyKey pending = service.deleteKey(key); + + assertEquals("DELETE_PENDING", pending.getKeyState()); + assertFalse(pending.isEnabled(), "a key that is pending deletion is enabled"); + assertTrue(pending.getDeletePendingTimestamp() >= before + 7 * 86_400L + && pending.getDeletePendingTimestamp() <= Instant.now().getEpochSecond() + + 7 * 86_400L, + "the pending timestamp is not the moment the deletion takes effect"); + } + @Test + void aDeletedKeyIsRestored() { PaymentCryptographyKey key = createKey("us-east-1"); service.deleteKey(key); - AwsException gone = assertThrows(AwsException.class, - () -> service.tag(key, Map.of("owner", "team"))); - assertEquals("ResourceNotFoundException", gone.getErrorCode()); - assertNull(service.findKey("us-east-1", key.getKeyId()), - "the key is in the store again after it was deleted"); + PaymentCryptographyKey restored = service.restoreKey(key); + + assertEquals("CREATE_COMPLETE", restored.getKeyState()); + assertEquals(0, restored.getDeletePendingTimestamp(), + "a restored key is still pending deletion"); + assertEquals("CREATE_COMPLETE", service.findKey("us-east-1", key.getArn()).getKeyState()); + } + + @Test + void aRestoredKeyIsDisabledUntilItsUseIsStartedAgain() { + // The reference's own restore example answers with a key that is disabled, and says + // that two members change: the state and the pending timestamp. It is StartKeyUsage + // that enables a key again. + PaymentCryptographyKey key = createKey("us-east-1"); + service.stopKeyUsage(key); + long stoppedAt = service.findKey("us-east-1", key.getArn()).getUsageStopTimestamp(); + service.deleteKey(key); + + PaymentCryptographyKey restored = service.restoreKey(key); + + assertFalse(restored.isEnabled(), "a restored key is enabled"); + assertEquals("CREATE_COMPLETE", restored.getKeyState()); + assertEquals(stoppedAt, restored.getUsageStopTimestamp(), + "a restored key lost the moment it stopped"); + + PaymentCryptographyKey started = service.startKeyUsage(key); + assertTrue(started.isEnabled(), "a key that was started again is disabled"); + assertEquals(0, started.getUsageStopTimestamp(), + "a key in use still carries the moment it stopped"); + } + + @Test + void aKeyThatIsNotPendingDeletionIsNotRestored() { + PaymentCryptographyKey key = createKey("us-east-1"); + + AwsException conflict = assertThrows(AwsException.class, + () -> service.restoreKey(key)); + assertEquals("ConflictException", conflict.getErrorCode()); + } + + @Test + void aReplicaCarriesThePendingDeletionOfItsPrimary() { + // A replica is a copy of its primary, so a key that is pending deletion is pending + // deletion in every region it replicates into, and it says when the deletion takes + // effect there as well. + PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2")); + + PaymentCryptographyKey pending = service.deleteKey(key); + PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId()); + + assertEquals("DELETE_PENDING", replica.getKeyState()); + assertEquals(pending.getDeletePendingTimestamp(), replica.getDeletePendingTimestamp(), + "a replica that is pending deletion carries no moment the deletion takes effect"); + assertFalse(replica.isEnabled(), "a replica of a key that is pending deletion is enabled"); + } + + @Test + void aRestoredKeyIsRestoredInEveryRegionItReplicatesInto() { + PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2")); + service.deleteKey(key); + + service.restoreKey(key); + + PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId()); + assertEquals("CREATE_COMPLETE", replica.getKeyState()); + assertEquals(0, replica.getDeletePendingTimestamp(), + "a replica of a restored key is still pending deletion"); + assertFalse(replica.isEnabled(), "a replica of a restored key is enabled"); + } + + @Test + void aReplicaIsNotRestoredApartFromItsPrimary() { + // 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. + PaymentCryptographyKey key = createReplicatedKey(service, "us-east-1", List.of("us-west-2")); + service.deleteKey(key); + PaymentCryptographyKey replica = service.findKey("us-west-2", key.getKeyId()); + + AwsException refused = assertThrows(AwsException.class, + () -> service.restoreKey(replica)); + assertEquals("ValidationException", refused.getErrorCode()); + + assertEquals("DELETE_PENDING", replica.getKeyState(), + "a replica that was refused is no longer pending deletion"); + assertEquals("DELETE_PENDING", + service.findKey("us-east-1", key.getKeyId()).getKeyState()); + } + + @Test + void aKeyThatIsAlreadyPendingDeletionIsNotDeletedAgain() { + PaymentCryptographyKey key = createKey("us-east-1"); + service.deleteKey(key); + + AwsException conflict = assertThrows(AwsException.class, + () -> service.deleteKey(key)); + assertEquals("ConflictException", conflict.getErrorCode()); } /** The policy that grants different permissions to different accounts. */ @@ -475,18 +598,15 @@ class PaymentCryptographyServiceTest { } @Test - void aDeletedKeyHasNoResourcePolicy() { + void aKeyPendingDeletionKeepsItsResourcePolicy() { PaymentCryptographyKey key = createKey("us-east-1"); service.putResourcePolicy(key, PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY); service.deleteKey(key); - AwsException gone = assertThrows(AwsException.class, - () -> service.resourcePolicy(key)); - assertEquals("ResourceNotFoundException", gone.getErrorCode()); - - AwsException deleted = assertThrows(AwsException.class, - () -> service.putResourcePolicy(key, PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY)); - assertEquals("ResourceNotFoundException", deleted.getErrorCode()); + // The key is still there while its deletion is pending, so the policy it carries is + // still there too. + assertEquals(PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY, + service.resourcePolicy(key).policy()); } @Test @@ -510,17 +630,19 @@ class PaymentCryptographyServiceTest { } @Test - void aDeletedKeyIsNotStartedOrStopped() { + void aKeyPendingDeletionIsNotStartedOrStopped() { PaymentCryptographyKey key = createKey("us-east-1"); service.deleteKey(key); + // The deletion is under way, so the use of the key is not the caller's to change: + // the reference does not publish the answer, so the service refuses the request. AwsException start = assertThrows(AwsException.class, () -> service.startKeyUsage(key)); - assertEquals("ResourceNotFoundException", start.getErrorCode()); + assertEquals("ConflictException", start.getErrorCode()); AwsException stop = assertThrows(AwsException.class, () -> service.stopKeyUsage(key)); - assertEquals("ResourceNotFoundException", stop.getErrorCode()); + assertEquals("ConflictException", stop.getErrorCode()); } @Test @@ -681,10 +803,11 @@ class PaymentCryptographyServiceTest { @Test void theKeysAreListedByTheirState() { createKey("us-east-1"); - createKey("us-east-1"); + PaymentCryptographyKey deleted = createKey("us-east-1"); + service.deleteKey(deleted); - assertEquals(2, service.listKeys("us-east-1", "CREATE_COMPLETE").size()); - assertEquals(0, service.listKeys("us-east-1", "DELETE_PENDING").size()); + assertEquals(1, service.listKeys("us-east-1", "CREATE_COMPLETE").size()); + assertEquals(1, service.listKeys("us-east-1", "DELETE_PENDING").size()); assertEquals(0, service.listKeys("us-east-1", "CREATE_IN_PROGRESS").size()); } @@ -1395,24 +1518,6 @@ class PaymentCryptographyServiceTest { 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