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 d316adf6d1..c4a6fc1471 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 @@ -71,6 +71,54 @@ create_key() { [ "$(json_get "$output" '.Tags | length')" = "0" ] } +@test "Payment Cryptography control plane: a resource policy is put, read and deleted" { + KEY_ARN=$(create_key AES_256) + [ -n "$KEY_ARN" ] + + # The cross-account grant the reference's own page shows. + local policy='{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111122223333:role/ExampleRole"},"Action":["payment-cryptography:GenerateCardValidationData","payment-cryptography:VerifyCardValidationData"],"Resource":"*"}]}' + + run aws_cmd payment-cryptography put-resource-policy \ + --resource-arn "$KEY_ARN" \ + --policy "$policy" + assert_success + [ "$(json_get "$output" '.Policy')" = "$policy" ] + + run aws_cmd payment-cryptography get-resource-policy --resource-arn "$KEY_ARN" + assert_success + [ "$(json_get "$output" '.Policy')" = "$policy" ] + + run aws_cmd payment-cryptography delete-resource-policy --resource-arn "$KEY_ARN" + assert_success + + run aws_cmd payment-cryptography get-resource-policy --resource-arn "$KEY_ARN" + assert_failure +} + +@test "Payment Cryptography control plane: a policy that grants public access is refused" { + KEY_ARN=$(create_key AES_256) + [ -n "$KEY_ARN" ] + + run aws_cmd payment-cryptography put-resource-policy \ + --resource-arn "$KEY_ARN" \ + --policy '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":["payment-cryptography:EncryptData"],"Resource":"*"}]}' + assert_failure + [[ "$output" == *"PublicPolicyException"* ]] +} + +@test "Payment Cryptography control plane: a policy that names another key is refused" { + # The reference says the resource of a policy must be every resource or the ARN of the + # key the policy is on. + KEY_ARN=$(create_key AES_256) + [ -n "$KEY_ARN" ] + + run aws_cmd payment-cryptography put-resource-policy \ + --resource-arn "$KEY_ARN" \ + --policy '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::111122223333:role/ExampleRole"},"Action":["payment-cryptography:GenerateCardValidationData"],"Resource":"arn:aws:payment-cryptography:us-east-1:000000000000:key/1234abcd1234abcd"}]}' + assert_failure + [[ "$output" == *"ValidationException"* ]] +} + @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 d239485d28..b5edde40c3 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 @@ -35,7 +35,9 @@ import software.amazon.awssdk.services.paymentcryptography.model.KeyState; import software.amazon.awssdk.services.paymentcryptography.model.KeyUsage; import software.amazon.awssdk.services.paymentcryptography.model.ListKeysResponse; import software.amazon.awssdk.services.paymentcryptography.model.MultiRegionKeyType; +import software.amazon.awssdk.services.paymentcryptography.model.PublicPolicyException; import software.amazon.awssdk.services.paymentcryptography.model.RemoveKeyReplicationRegionsResponse; +import software.amazon.awssdk.services.paymentcryptography.model.ResourceNotFoundException; import software.amazon.awssdk.services.paymentcryptography.model.Tag; import software.amazon.awssdk.services.paymentcryptography.model.Tr34KeyBlockFormat; import software.amazon.awssdk.services.paymentcryptography.model.WrappedKeyMaterialFormat; @@ -724,6 +726,36 @@ class PaymentCryptographyTest { assertThat(tags).containsEntry("owner", "compat"); } + @Test + void aResourcePolicyIsPutReadAndDeleted() { + Key key = createAesKey(); + String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"}," + + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"]," + + "\"Resource\":\"*\"}]}"; + + assertThat(client.putResourcePolicy(r -> r + .resourceArn(key.keyArn()) + .policy(policy)).policy()).isEqualTo(policy); + assertThat(client.getResourcePolicy(r -> r.resourceArn(key.keyArn())).policy()) + .isEqualTo(policy); + + client.deleteResourcePolicy(r -> r.resourceArn(key.keyArn())); + + assertThatThrownBy(() -> client.getResourcePolicy(r -> r.resourceArn(key.keyArn()))) + .isInstanceOf(ResourceNotFoundException.class); + } + + @Test + void aPublicResourcePolicyIsRefused() { + Key key = createAesKey(); + + assertThatThrownBy(() -> client.putResourcePolicy(r -> r + .resourceArn(key.keyArn()) + .policy("{\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\"}]}"))) + .isInstanceOf(PublicPolicyException.class); + } + /** * A delete answers with the key it deleted, its state DELETE_PENDING and the * moment it is deleted, so a caller reads the key and not an empty answer. diff --git a/docs/services/index.md b/docs/services/index.md index f93e09cba7..00da650bdf 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 | 22 | +| [Payment Cryptography](payment-cryptography.md) | `POST /` + `X-Amz-Target: PaymentCryptographyControlPlane.*` | JSON 1.0 | 25 | | [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 a33349a59a..56e2addb2e 100644 --- a/docs/services/payment-cryptography.md +++ b/docs/services/payment-cryptography.md @@ -30,6 +30,9 @@ | `TagResource` | Add tags to a key | | `UntagResource` | Remove tags from a key | | `ListTagsForResource` | List the tags of a key | +| `PutResourcePolicy` | Attach or replace the resource-based policy of a key | +| `GetResourcePolicy` | Get the resource-based policy of a key | +| `DeleteResourcePolicy` | Remove the resource-based policy of a key | ## Emulation Behavior @@ -225,9 +228,24 @@ - **The replication is in sync at once:** the service does not model the progress of a replication, so the status of a replica that is there is `SYNCHRONIZED` right away, where the reference answers `IN_PROGRESS` until the replication has finished. -- **Not yet emulated:** the resource policy operations, the key usage operations, the key - restore operation, the multi-party approval operations and the certificate signing - request. +- **Resource policies:** `PutResourcePolicy` attaches or replaces the policy stored on the + key, `GetResourcePolicy` returns it and `DeleteResourcePolicy` removes it. A key without + a policy is answered with `ResourceNotFoundException` by both reads. The policy is a JSON + document, and one that does not parse, or that carries anything after the document, is + refused with `ValidationException`. A grant names an effect, a principal, an action and + a resource, and a policy that carries no statement, or a statement that names none of + them, is refused with `ValidationException`. An `Allow` statement that reaches every + principal and carries no condition is refused with `PublicPolicyException`, as the + reference refuses one: a principal that is everyone, and a grant that excludes a + principal and so reaches everyone else, both reach everyone. A statement that carries a + condition is taken to be narrowed by it, so a condition that narrows nothing is not read. + The resource a policy names must be every resource or the ARN of the key the policy is + 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. +- **Not yet emulated:** the key usage operations, the key restore operation, the + multi-party approval operations and the certificate signing request. ## Configuration diff --git a/src/main/java/io/floci/aws/services/iam/PolicyDocument.java b/src/main/java/io/floci/aws/services/iam/PolicyDocument.java new file mode 100644 index 0000000000..a8efa6057c --- /dev/null +++ b/src/main/java/io/floci/aws/services/iam/PolicyDocument.java @@ -0,0 +1,108 @@ +package io.floci.aws.services.iam; + +import com.fasterxml.jackson.databind.JsonNode; + +import java.util.ArrayList; +import java.util.List; + +/** + * How a resource policy document reads: the statements it carries, and the principals + * those statements reach. + * + *
S3's block public access, Secrets Manager's block public policy and Payment
+ * Cryptography's public policy refusal all read a policy this way, and each of them had a
+ * copy of it. The copies disagreed: one of them did not see a wildcard principal written
+ * as a list, and one of them saw a wildcard in a shape the others did not. The rule is
+ * here now, and the three read it.
+ */
+public final class PolicyDocument {
+
+ /** The wildcard that names every principal. */
+ private static final String WILDCARD = "*";
+
+ private PolicyDocument() {
+ }
+
+ /**
+ * The statements of a policy, whether it carries one alone or a list of them.
+ *
+ * @param policy the policy document
+ * @return the statements, empty when the document carries none
+ */
+ public static List A principal names everyone when it is the wildcard itself, when it is a list that
+ * holds the wildcard, or when it is a map whose values hold it: {@code "*"},
+ * {@code {"AWS": "*"}}, {@code {"AWS": ["*"]}} and {@code ["*"]} all name everyone.
+ *
+ * @param principal the principal of a statement
+ * @return whether the principal names everyone
+ */
+ public static boolean namesEveryone(JsonNode principal) {
+ if (principal == null || principal.isMissingNode() || principal.isNull()) {
+ return false;
+ }
+ if (principal.isTextual()) {
+ return WILDCARD.equals(principal.asText());
+ }
+ if (principal.isArray()) {
+ return holdsEveryone(principal);
+ }
+ if (principal.isObject()) {
+ for (JsonNode value : principal) {
+ if (holdsEveryone(value)) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Whether a statement grants to everyone.
+ *
+ * A grant that names everyone as its principal reaches everyone, and a grant that
+ * names the principals it excludes reaches everyone else. A grant that excludes
+ * everyone reaches nobody.
+ *
+ * @param statement the statement of a policy
+ * @return whether the statement reaches everyone
+ */
+ public static boolean grantsToEveryone(JsonNode statement) {
+ if (statement.hasNonNull("Principal")) {
+ return namesEveryone(statement.path("Principal"));
+ }
+ return statement.hasNonNull("NotPrincipal") && !namesEveryone(statement.path("NotPrincipal"));
+ }
+
+ /** Whether a value holds the wildcard, whether it is the value itself or a list of them. */
+ private static boolean holdsEveryone(JsonNode node) {
+ if (node == null || node.isNull()) {
+ return false;
+ }
+ if (node.isTextual()) {
+ return WILDCARD.equals(node.asText());
+ }
+ if (node.isArray()) {
+ for (JsonNode item : node) {
+ if (WILDCARD.equals(item.asText())) {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+}
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 c382d43a87..080876158e 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyJsonHandler.java
@@ -1,9 +1,13 @@
package io.floci.aws.services.paymentcryptography;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.Pagination;
+import io.floci.aws.services.iam.PolicyDocument;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyAlias;
import io.floci.aws.services.paymentcryptography.model.PaymentCryptographyKey;
import jakarta.enterprise.context.ApplicationScoped;
@@ -28,6 +32,15 @@ public class PaymentCryptographyJsonHandler {
/** The error a bad page size or a bad token is refused with. */
private static final String PAGINATION_ERROR = "ValidationException";
+ /**
+ * The reader of a resource policy, which arrives as a JSON document in a string.
+ *
+ * The whole string is what the key keeps, so a string that carries anything after
+ * the document is not one policy and is refused.
+ */
+ private static final ObjectMapper POLICY_READER = new ObjectMapper()
+ .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
+
private final PaymentCryptographyService service;
@Inject
@@ -70,6 +83,9 @@ public class PaymentCryptographyJsonHandler {
case "TagResource" -> () -> tagResource(request, region);
case "UntagResource" -> () -> untagResource(request, region);
case "ListTagsForResource" -> () -> listTagsForResource(request, region);
+ case "PutResourcePolicy" -> () -> putResourcePolicy(request, region);
+ case "GetResourcePolicy" -> () -> getResourcePolicy(request, region);
+ case "DeleteResourcePolicy" -> () -> deleteResourcePolicy(request, region);
default -> throw new AwsException("UnknownOperationException",
"Operation " + action + " is not supported by floci", 400);
};
@@ -273,6 +289,173 @@ public class PaymentCryptographyJsonHandler {
return out;
}
+ // ---- resource policies ----------------------------------------------------
+
+ /**
+ * Attaches or replaces the resource-based policy of a key.
+ *
+ * The policy is a JSON document in a string, and a document that does not parse is
+ * refused before it is attached. A policy that hands the key to everyone and carries no
+ * condition is refused with the reference's own error, so the key is never left open by
+ * a policy no one bounds.
+ */
+ private Map The policy is a JSON document in a string, and a document that does not parse, or
+ * that carries anything after the document, is refused before it is attached: the whole
+ * string is what the key keeps, so a string that is not one document is not a policy.
+ *
+ * @param policy the policy as it was given
+ * @return the policy document
+ */
+ private static JsonNode readPolicy(String policy) {
+ JsonNode document;
+ try {
+ document = POLICY_READER.readTree(policy);
+ } catch (JsonProcessingException e) {
+ throw new AwsException("ValidationException",
+ "Policy is not a valid JSON policy document: " + e.getOriginalMessage(), 400);
+ }
+ if (document == null || !document.isObject()) {
+ throw new AwsException("ValidationException",
+ "Policy is not a valid JSON policy document", 400);
+ }
+ return document;
+ }
+
+ /** The resource-based policy of a key, which a key without one does not have. */
+ private Map The reference says the resource of a policy must be every resource or the ARN of
+ * the key the policy is on, so a policy that names another key is refused.
+ *
+ * @param statements the statements of the policy
+ * @param arn the ARN of the key the policy is attached to
+ * @return whether the policy names the key
+ */
+ private static boolean namesTheKey(List The grammar a resource policy follows names an effect, a principal, an action and
+ * a resource in every statement, and a document that carries no statement, or a
+ * statement that names none of them, grants nothing, so it is refused rather than
+ * stored on the key.
+ *
+ * @param statements the statements of the policy
+ * @return the statements
+ */
+ private static List The reference refuses such a policy, so the service does too: an Allow statement
+ * whose principal is everyone, and that carries no condition, is public access.
+ *
+ * @param statements the statements of the policy
+ * @return whether the policy grants public access
+ */
+ private static boolean grantsPublicAccess(List The store holds the key itself, and a key is mutable, so a read takes the two
+ * values the answer carries while it holds the lock. A policy taken away after the
+ * read cannot change the answer.
+ *
+ * @param arn the ARN of the key the policy is on
+ * @param policy the policy document
+ */
+ public record ResourcePolicy(String arn, String policy) {
+ }
+
+ /**
+ * Attaches or replaces the resource-based policy of a key.
+ *
+ * The policy belongs to the key, so it is written with the key and goes when the key
+ * goes. A policy the service has not seen is replaced, as the reference replaces one.
+ */
+ public synchronized ResourcePolicy putResourcePolicy(PaymentCryptographyKey key, String policy) {
+ PaymentCryptographyKey current = liveKey(key);
+ // A replica is read-only, and the reference attaches a policy to the primary alone.
+ requireNotReplica(current, "a policy may only be attached to the primary");
+ current.setResourcePolicy(policy);
+ storeKey(current);
+ return new ResourcePolicy(current.getArn(), current.getResourcePolicy());
+ }
+
+ /**
+ * The resource-based policy attached to a key.
+ *
+ * A key without a policy is refused as the resource the reference cannot find, not
+ * answered with an empty policy: the two are different answers.
+ */
+ public synchronized ResourcePolicy resourcePolicy(PaymentCryptographyKey key) {
+ PaymentCryptographyKey current = keyWithPolicy(key);
+ return new ResourcePolicy(current.getArn(), current.getResourcePolicy());
+ }
+
+ /**
+ * Removes the resource-based policy of a key.
+ *
+ * A key without a policy is refused, as it is by the read.
+ */
+ public synchronized void deleteResourcePolicy(PaymentCryptographyKey key) {
+ PaymentCryptographyKey current = keyWithPolicy(key);
+ current.setResourcePolicy(null);
+ storeKey(current);
+ }
+
+ /**
+ * The key as it is in the store now, with the policy it carries.
+ *
+ * A key without a policy is refused as the resource the reference cannot find, not
+ * answered with an empty policy: the two are different answers.
+ *
+ * @param key the key the request named
+ * @return the key, with its policy
+ */
+ private PaymentCryptographyKey keyWithPolicy(PaymentCryptographyKey key) {
+ PaymentCryptographyKey current = liveKey(key);
+ if (current.getResourcePolicy() == null) {
+ throw new AwsException("ResourceNotFoundException",
+ "Resource policy for key " + key.getArn() + " is not found", 400);
+ }
+ return current;
+ }
+
// ---- the key exchange ----------------------------------------------------
/**
diff --git a/src/main/java/io/floci/aws/services/paymentcryptography/model/PaymentCryptographyKey.java b/src/main/java/io/floci/aws/services/paymentcryptography/model/PaymentCryptographyKey.java
index 04b748e768..0754384c31 100644
--- a/src/main/java/io/floci/aws/services/paymentcryptography/model/PaymentCryptographyKey.java
+++ b/src/main/java/io/floci/aws/services/paymentcryptography/model/PaymentCryptographyKey.java
@@ -69,6 +69,11 @@ public class PaymentCryptographyKey {
private long deletePendingTimestamp;
private long deleteTimestamp;
private volatile Map The policy is a JSON document in a string, so the body that carries it escapes
+ * the quotes and the line breaks the document holds.
+ *
+ * @param arn the ARN of the key the policy is put on
+ * @param policy the policy document
+ * @return the body of the request
+ */
+ private static String putPolicyBody(String arn, String policy) {
+ return PaymentCryptographyTestFixtures.request(Map.of(
+ "ResourceArn", arn, "Policy", policy)).toString();
+ }
+
@Test
void aKeyIsCreatedAndReadBack() {
String arn = call("CreateKey", CREATE_KEY)
@@ -647,6 +663,240 @@ class PaymentCryptographyIntegrationTest {
.body("Tags", hasSize(0));
}
+ @Test
+ void aResourcePolicyIsPutReadAndDeleted() {
+ String arn = keyArn();
+ String policy = PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY;
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(200)
+ .body("ResourceArn", equalTo(arn))
+ .body("Policy", equalTo(policy));
+
+ call("GetResourcePolicy", "{\"ResourceArn\":\"" + arn + "\"}")
+ .then().statusCode(200)
+ .body("ResourceArn", equalTo(arn))
+ .body("Policy", equalTo(policy));
+
+ call("DeleteResourcePolicy", "{\"ResourceArn\":\"" + arn + "\"}")
+ .then().statusCode(200);
+
+ call("GetResourcePolicy", "{\"ResourceArn\":\"" + arn + "\"}")
+ .then().statusCode(400)
+ .body("__type", containsString("ResourceNotFoundException"));
+ }
+
+ @Test
+ void thePolicyOfTheReferenceIsAttachedAndReadBack() {
+ // The reference's own page shows this policy, and the service keeps the document as
+ // it was given.
+ String arn = keyArn();
+
+ call("PutResourcePolicy", putPolicyBody(arn, PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY))
+ .then().statusCode(200)
+ .body("ResourceArn", equalTo(arn))
+ .body("Policy", equalTo(PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY));
+
+ call("GetResourcePolicy", "{\"ResourceArn\":\"" + arn + "\"}")
+ .then().statusCode(200)
+ .body("Policy", equalTo(PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY));
+ }
+
+ @Test
+ void aPolicyThatNamesAnotherKeyIsRefused() {
+ // The reference says the resource of a policy must be every resource or the ARN of
+ // the key the policy is on.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"},"
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"arn:aws:payment-cryptography:us-east-1:000000000000:"
+ + "key/1234abcd1234abcd\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void aPolicyThatGrantsPublicAccessIsRefused() {
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":\"*\",\"Action\":[\"payment-cryptography:EncryptData\"],"
+ + "\"Resource\":\"*\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(400)
+ .body("__type", containsString("PublicPolicyException"));
+ }
+
+ @Test
+ void aPolicyThatIsNotJsonIsRefused() {
+ String arn = keyArn();
+
+ call("PutResourcePolicy", putPolicyBody(arn, "not json"))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void aPolicyThatNamesTheKeyItIsOnIsAttached() {
+ // The resource may be the key's own ARN as well as every resource.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"},"
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"" + arn + "\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(200)
+ .body("Policy", equalTo(policy));
+ }
+
+ @Test
+ void aPolicyOfOneStatementIsAttached() {
+ // The statement may stand alone rather than in a list.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"},"
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"*\"}}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(200)
+ .body("Policy", equalTo(policy));
+ }
+
+ @Test
+ void aPolicyThatNamesNoResourceIsRefused() {
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"},"
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"arn:aws:payment-cryptography:us-east-1:000000000000:"
+ + "key/1234abcd1234abcd\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void aPolicyThatCarriesNoStatementIsRefused() {
+ String arn = keyArn();
+
+ call("PutResourcePolicy", putPolicyBody(arn, "{\"Version\":\"2012-10-17\"}"))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void aPolicyThatGrantsEveryoneAccessThroughItsPrincipalIsRefused() {
+ // The principal may be written as a list of principals, and a wildcard among them
+ // is everyone.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":[\"arn:aws:iam::111122223333:role/ExampleRole\",\"*\"]},"
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"*\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(400)
+ .body("__type", containsString("PublicPolicyException"));
+ }
+
+ @Test
+ void aPolicyThatCarriesAConditionIsAttached() {
+ // A condition narrows the grant, so the grant is not to everyone.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":\"*\","
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"*\","
+ + "\"Condition\":{\"StringEquals\":{\"aws:PrincipalAccount\":\"111122223333\"}}}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(200)
+ .body("Policy", equalTo(policy));
+ }
+
+ @Test
+ void aPolicyThatGrantsEveryoneAccessThroughThePrincipalItExcludesIsRefused() {
+ // A grant that names the principals it excludes reaches everyone else, and a
+ // wildcard among them is everyone.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"},"
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"*\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(400)
+ .body("__type", containsString("PublicPolicyException"));
+ }
+
+ @Test
+ void aPolicyThatExcludesEveryoneIsAttached() {
+ // A grant that excludes everyone reaches nobody, so it opens nothing.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"NotPrincipal\":\"*\","
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"*\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(200)
+ .body("Policy", equalTo(policy));
+ }
+
+ @Test
+ void aPolicyThatCarriesAnEmptyStatementIsRefused() {
+ // A policy that grants nothing is not a policy, so it is refused.
+ String arn = keyArn();
+
+ call("PutResourcePolicy", putPolicyBody(arn, "{\"Version\":\"2012-10-17\",\"Statement\":[]}"))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void aPolicyWhoseStatementNamesNoActionIsRefused() {
+ // A grant names an effect, a principal, an action and a resource, and one that
+ // names no action grants nothing.
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"},"
+ + "\"Resource\":\"*\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void aPolicyWhoseStatementNamesNoPrincipalIsRefused() {
+ String arn = keyArn();
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"*\"}]}";
+
+ call("PutResourcePolicy", putPolicyBody(arn, policy))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
+ @Test
+ void aPolicyThatCarriesSomethingAfterTheDocumentIsRefused() {
+ // The whole string is what the key keeps, so a string that is not one document is
+ // not a policy.
+ String arn = keyArn();
+
+ call("PutResourcePolicy", putPolicyBody(arn,
+ "{\"Version\":\"2012-10-17\",\"Statement\":[]} {\"Version\":\"2012-10-17\"}"))
+ .then().statusCode(400)
+ .body("__type", containsString("ValidationException"));
+ }
+
@Test
void aKeyThatDoesNotExistIsNotFound() {
call("GetKey", "{\"KeyIdentifier\":\"arn:aws:payment-cryptography:us-east-1:000000000000:key/"
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 c0ea51d83e..8be532e514 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyServiceTest.java
@@ -396,6 +396,94 @@ class PaymentCryptographyServiceTest {
"the key is in the store again after it was deleted");
}
+ /** The policy that grants different permissions to different accounts. */
+ private static final String TWO_ACCOUNTS_POLICY = """
+ {"Version":"2012-10-17","Statement":[
+ {"Sid":"Allow3DSACSToGenerate","Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::111122223333:role/3dsAcsRole"},
+ "Action":["payment-cryptography:GenerateCardValidationData"],"Resource":"*"},
+ {"Sid":"AllowPaymentAuthToVerify","Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::444455556666:role/PaymentAuthRole"},
+ "Action":["payment-cryptography:VerifyAuthRequestCryptogram"],"Resource":"*"}]}""";
+
+ @Test
+ void aPolicyIsNotAttachedToAReplica() {
+ // The reference attaches a policy to the primary key alone, so a replica takes none.
+ PaymentCryptographyKey primary = createReplicatedKey(service, "us-east-1", List.of("us-west-2"));
+ PaymentCryptographyKey replica = service.findKey("us-west-2", primary.getKeyId());
+
+ AwsException refused = assertThrows(AwsException.class,
+ () -> service.putResourcePolicy(replica, PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY));
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+ @Test
+ void thePolicyOfTheReferenceIsAttachedAndReadBack() {
+ // The reference's own page shows these two policies, and the service keeps the
+ // document as it was given.
+ PaymentCryptographyKey key = createKey("us-east-1");
+ String policy = PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY;
+
+ assertEquals(policy, service.putResourcePolicy(key, policy).policy());
+ assertEquals(policy, service.resourcePolicy(key).policy());
+ assertEquals(TWO_ACCOUNTS_POLICY,
+ service.putResourcePolicy(key, TWO_ACCOUNTS_POLICY).policy());
+ }
+
+ @Test
+ void aPolicyThatNamesTheKeyItIsOnIsAttached() {
+ // The resource may be the key's own ARN as well as every resource.
+ PaymentCryptographyKey key = createKey("us-east-1");
+ String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":\"arn:aws:iam::111122223333:role/ExampleRole\"},"
+ + "\"Action\":[\"payment-cryptography:GenerateCardValidationData\"],"
+ + "\"Resource\":\"" + key.getArn() + "\"}]}";
+
+ assertEquals(policy, service.putResourcePolicy(key, policy).policy());
+ }
+
+ @Test
+ void aResourcePolicyIsPutReadAndDeleted() {
+ PaymentCryptographyKey key = createKey("us-east-1");
+ String policy = PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY;
+
+ assertNull(key.getResourcePolicy(), "a key has a policy before one was put on it");
+
+ assertEquals(policy, service.putResourcePolicy(key, policy).policy());
+ assertEquals(policy, service.resourcePolicy(key).policy());
+
+ service.deleteResourcePolicy(key);
+
+ AwsException gone = assertThrows(AwsException.class,
+ () -> service.resourcePolicy(key));
+ assertEquals("ResourceNotFoundException", gone.getErrorCode());
+ }
+
+ @Test
+ void aResourcePolicyIsReplacedByTheNextOne() {
+ PaymentCryptographyKey key = createKey("us-east-1");
+
+ service.putResourcePolicy(key, PaymentCryptographyTestFixtures.CROSS_ACCOUNT_POLICY);
+ service.putResourcePolicy(key, TWO_ACCOUNTS_POLICY);
+
+ assertEquals(TWO_ACCOUNTS_POLICY, service.resourcePolicy(key).policy());
+ }
+
+ @Test
+ void aDeletedKeyHasNoResourcePolicy() {
+ 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());
+ }
+
@Test
void theKeysAreListedAPageAtATime() {
createKey("us-east-1");
diff --git a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java
index bd62b640c8..459b985ab1 100644
--- a/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java
+++ b/src/test/java/io/floci/aws/services/paymentcryptography/PaymentCryptographyTestFixtures.java
@@ -17,6 +17,13 @@ import java.util.Map;
*/
final class PaymentCryptographyTestFixtures {
+ /** The cross-account grant the reference's own page shows. */
+ static final String CROSS_ACCOUNT_POLICY = """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::111122223333:role/ExampleRole"},
+ "Action":["payment-cryptography:GenerateCardValidationData",
+ "payment-cryptography:VerifyCardValidationData"],"Resource":"*"}]}""";
+
private PaymentCryptographyTestFixtures() {
}
diff --git a/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerJsonHandlerTest.java b/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerJsonHandlerTest.java
index d9568c0060..a9c68bde84 100644
--- a/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerJsonHandlerTest.java
+++ b/src/test/java/io/floci/aws/services/secretsmanager/SecretsManagerJsonHandlerTest.java
@@ -644,6 +644,12 @@ class SecretsManagerJsonHandlerTest {
"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ "\"Principal\":{\"AWS\":\"*\"},\"Action\":\"secretsmanager:GetSecretValue\",\"Resource\":\"*\"}]}";
+ /** The same grant, with the wildcard written as one of a list of principals. */
+ private static final String LIST_RESOURCE_POLICY =
+ "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Principal\":{\"AWS\":[\"arn:aws:iam::123456789012:root\",\"*\"]},"
+ + "\"Action\":\"secretsmanager:GetSecretValue\",\"Resource\":\"*\"}]}";
+
private String createSecretReturningArn(String name) {
ObjectNode request = MAPPER.createObjectNode();
request.put("Name", name);
@@ -1401,6 +1407,17 @@ class SecretsManagerJsonHandlerTest {
assertThat(((AwsErrorResponse) response.getEntity()).type(), is("PublicPolicyException"));
}
+ @Test
+ void putResourcePolicyBlocksAWildcardPrincipalWrittenAsAList() {
+ // The principal may be written as a list of principals, and a wildcard among them
+ // is everyone.
+ createSecret("blocked-list-policy");
+ Response response = putResourcePolicy("blocked-list-policy", LIST_RESOURCE_POLICY, true);
+
+ assertThat(response.getStatus(), is(400));
+ assertThat(((AwsErrorResponse) response.getEntity()).type(), is("PublicPolicyException"));
+ }
+
@Test
void putResourcePolicyAllowsAWildcardPrincipalByDefault() {
// AWS: "By default, public policies aren't blocked."