feat(paymentcryptography): the resource policies of a key (#8702)

Payment Cryptography keys now take a resource-based policy through PutResourcePolicy, GetResourcePolicy and DeleteResourcePolicy. The policy is stored on the key, so it goes when the key goes, and it is not enforced. A document that is not a JSON object or carries trailing content, a policy with no statement, a statement that names no effect, principal, action or resource, a Resource that is neither the wildcard nor the key's own ARN, and a policy on a replica key are refused with ValidationException. An unconditional Allow that reaches everyone, through a wildcard Principal or a NotPrincipal that excludes someone, is refused with PublicPolicyException, and GetResourcePolicy on a key without a policy answers ResourceNotFoundException. Reading a policy's statements and checking for an everyone principal now live in iam.PolicyDocument, which S3, Secrets Manager and Payment Cryptography share.
This commit is contained in:
Murtuza Chhil authored and GitHub committed 2026-11-17 09:16:27 -04:00
1 parent e8735be43b
commit 91943a061c
15 files changed
+947 -122

No files matched your search

@@ -0,0 +1,102 @@
package io.floci.aws.services.iam;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class PolicyDocumentTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Test
void aPolicyThatCarriesAListOfStatementsHasThem() {
JsonNode policy = policy("{\"Statement\":[{\"Effect\":\"Allow\"},{\"Effect\":\"Deny\"}]}");
assertEquals(2, PolicyDocument.statementsOf(policy).size());
assertEquals("Allow", PolicyDocument.statementsOf(policy).get(0).path("Effect").asText());
}
@Test
void aPolicyThatCarriesOneStatementHasIt() {
JsonNode policy = policy("{\"Statement\":{\"Effect\":\"Allow\"}}");
assertEquals(1, PolicyDocument.statementsOf(policy).size());
}
@Test
void aPolicyThatCarriesNoStatementHasNone() {
assertTrue(PolicyDocument.statementsOf(policy("{\"Version\":\"2012-10-17\"}")).isEmpty());
assertTrue(PolicyDocument.statementsOf(policy("{\"Statement\":[]}")).isEmpty());
assertTrue(PolicyDocument.statementsOf(policy("{\"Statement\":\"Allow\"}")).isEmpty());
}
@Test
void aWildcardPrincipalNamesEveryone() {
assertTrue(PolicyDocument.namesEveryone(principal("\"*\"")));
assertTrue(PolicyDocument.namesEveryone(principal("{\"AWS\":\"*\"}")));
assertTrue(PolicyDocument.namesEveryone(principal("{\"AWS\":[\"*\"]}")));
assertTrue(PolicyDocument.namesEveryone(principal("[\"*\"]")));
assertTrue(PolicyDocument.namesEveryone(principal("{\"AWS\":[\"arn:aws:iam::123456789012:role/app\",\"*\"]}")));
}
@Test
void aPrincipalThatNamesOnePrincipalNamesNotEveryone() {
assertFalse(PolicyDocument.namesEveryone(principal("\"arn:aws:iam::123456789012:role/app\"")));
assertFalse(PolicyDocument.namesEveryone(principal("{\"AWS\":\"arn:aws:iam::123456789012:role/app\"}")));
assertFalse(PolicyDocument.namesEveryone(principal("{\"AWS\":[\"arn:aws:iam::123456789012:role/app\"]}")));
}
@Test
void aPrincipalThatIsThereNamesNotEveryone() {
assertFalse(PolicyDocument.namesEveryone(null));
assertFalse(PolicyDocument.namesEveryone(principal("null")));
}
@Test
void aGrantThatNamesEveryoneReachesEveryone() {
assertTrue(PolicyDocument.grantsToEveryone(statement("\"Principal\":\"*\"")));
assertTrue(PolicyDocument.grantsToEveryone(statement("\"Principal\":{\"AWS\":\"*\"}")));
}
@Test
void aGrantThatNamesOnePrincipalReachesNotEveryone() {
assertFalse(PolicyDocument.grantsToEveryone(
statement("\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:role/app\"}")));
}
@Test
void aGrantThatExcludesOnePrincipalReachesEveryoneElse() {
assertTrue(PolicyDocument.grantsToEveryone(
statement("\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::123456789012:role/app\"}")));
}
@Test
void aGrantThatExcludesEveryoneReachesNobody() {
assertFalse(PolicyDocument.grantsToEveryone(statement("\"NotPrincipal\":\"*\"")));
}
@Test
void aGrantThatNamesNoPrincipalReachesNobody() {
assertFalse(PolicyDocument.grantsToEveryone(statement("\"Action\":\"s3:GetObject\"")));
}
private static JsonNode policy(String json) {
try {
return MAPPER.readTree(json);
} catch (Exception e) {
throw new IllegalArgumentException("Not JSON: " + json, e);
}
}
private static JsonNode principal(String json) {
return policy(json);
}
private static JsonNode statement(String member) {
return policy("{\"Effect\":\"Allow\"," + member + "}");
}
}
@@ -13,6 +13,7 @@ import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.aMapWithSize;
@@ -79,6 +80,21 @@ class PaymentCryptographyIntegrationTest {
"KeyModesOfUse":{"Sign":true,"Verify":true}},
"Exportable":true}""";
/**
* The body of a request that puts a resource policy on a key.
*
* <p>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/"
@@ -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");
@@ -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() {
}
@@ -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."