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

@@ -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.
@@ -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.
+1 -1
View File
@@ -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 |
+21 -3
View File
@@ -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 |
<!-- floci:actions:end -->
## 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
@@ -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.
*
* <p>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<JsonNode> statementsOf(JsonNode policy) {
JsonNode statements = policy.path("Statement");
if (statements.isObject()) {
return List.of(statements);
}
List<JsonNode> out = new ArrayList<>();
if (statements.isArray()) {
statements.forEach(out::add);
}
return out;
}
/**
* Whether a principal names every principal.
*
* <p>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.
*
* <p>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;
}
}
@@ -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.
*
* <p>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.
*
* <p>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<String, Object> putResourcePolicy(JsonNode request, String region) {
PaymentCryptographyKey key = requiredKey(request, region, RESOURCE_ARN);
String policy = request.path("Policy").asText();
JsonNode document = readPolicy(policy);
List<JsonNode> statements = PolicyDocument.statementsOf(document);
if (grantsPublicAccess(statements)) {
throw new AwsException("PublicPolicyException",
"The resource policy grants public access to the key", 400);
}
if (!namesTheKey(grantsOf(statements), key.getArn())) {
throw new AwsException("ValidationException",
"The resource policy names a resource that is not the key it is attached to", 400);
}
return policyAnswer(service.putResourcePolicy(key, policy));
}
/**
* The policy document a request carries.
*
* <p>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<String, Object> getResourcePolicy(JsonNode request, String region) {
PaymentCryptographyKey key = requiredKey(request, region, RESOURCE_ARN);
return policyAnswer(service.resourcePolicy(key));
}
/** Removes the resource-based policy of a key. */
private Map<String, Object> deleteResourcePolicy(JsonNode request, String region) {
PaymentCryptographyKey key = requiredKey(request, region, RESOURCE_ARN);
service.deleteResourcePolicy(key);
return Map.of();
}
private static Map<String, Object> policyAnswer(PaymentCryptographyService.ResourcePolicy policy) {
return Map.of("ResourceArn", policy.arn(), "Policy", policy.policy());
}
/**
* Whether every statement of a policy names the key the policy is attached to.
*
* <p>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<JsonNode> statements, String arn) {
for (JsonNode statement : statements) {
if (!statementNamesTheKey(statement, arn)) {
return false;
}
}
return true;
}
/**
* The statements of a policy that grant something.
*
* <p>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<JsonNode> grantsOf(List<JsonNode> statements) {
if (statements.isEmpty()) {
throw new AwsException("ValidationException",
"The resource policy carries no statement", 400);
}
for (JsonNode statement : statements) {
if (!carriesTheElementsOfAGrant(statement)) {
throw new AwsException("ValidationException",
"The resource policy carries a statement that names no effect, principal, "
+ "action or resource", 400);
}
}
return statements;
}
/** Whether a statement names the elements a grant is made of. */
private static boolean carriesTheElementsOfAGrant(JsonNode statement) {
String effect = statement.path("Effect").asText();
return ("Allow".equalsIgnoreCase(effect) || "Deny".equalsIgnoreCase(effect))
&& (statement.hasNonNull("Principal") || statement.hasNonNull("NotPrincipal"))
&& (statement.hasNonNull("Action") || statement.hasNonNull("NotAction"))
&& statement.hasNonNull("Resource");
}
/** Whether a statement names the key, either alone or in a list of resources. */
private static boolean statementNamesTheKey(JsonNode statement, String arn) {
JsonNode resource = statement.path("Resource");
if (resource.isTextual()) {
return "*".equals(resource.asText()) || arn.equals(resource.asText());
}
if (resource.isArray()) {
for (JsonNode entry : resource) {
if (!"*".equals(entry.asText()) && !arn.equals(entry.asText())) {
return false;
}
}
return resource.size() > 0;
}
return false;
}
/**
* Whether a policy hands the key to every principal without a condition.
*
* <p>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<JsonNode> statements) {
for (JsonNode statement : statements) {
if (statementGrantsPublicAccess(statement)) {
return true;
}
}
return false;
}
private static boolean statementGrantsPublicAccess(JsonNode statement) {
if (!"Allow".equalsIgnoreCase(statement.path("Effect").asText())) {
return false;
}
if (!PolicyDocument.grantsToEveryone(statement) || statement.has("Condition")) {
return false;
}
return true;
}
/** The tags of a request, as the name and the value of each. */
private static Map<String, String> tagsOf(JsonNode request) {
Map<String, String> tags = new LinkedHashMap<>();
@@ -640,6 +640,76 @@ public class PaymentCryptographyService implements Resettable, StoredResourceArn
maxResults, nextToken, DEFAULT_PAGE_SIZE, MAX_RESULTS, PAGINATION_ERROR);
}
// ---- resource policies ----------------------------------------------------
/**
* A key's resource-based policy as it is at one moment.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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.
*
* <p>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 ----------------------------------------------------
/**
@@ -69,6 +69,11 @@ public class PaymentCryptographyKey {
private long deletePendingTimestamp;
private long deleteTimestamp;
private volatile Map<String, String> tags = new HashMap<>();
/**
* The resource-based policy attached to the key, in JSON, or null when the key has none.
* It is the key's own, so it goes when the key goes.
*/
private String resourcePolicy;
/** The region of the primary of a multi-region key, and its own region otherwise. */
private String primaryRegion;
/** The regions a multi-region key is in, besides the primary's. */
@@ -183,4 +188,8 @@ public class PaymentCryptographyKey {
public Map<String, String> getTags() { return tags; }
public void setTags(Map<String, String> tags) { this.tags = tags; }
/** The resource-based policy of the key, or null when it has none. */
public String getResourcePolicy() { return resourcePolicy; }
public void setResourcePolicy(String resourcePolicy) { this.resourcePolicy = resourcePolicy; }
}
@@ -5,11 +5,11 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.floci.aws.core.common.AwsArnUtils;
import io.floci.aws.services.iam.IamPolicyEvaluator;
import io.floci.aws.services.iam.PolicyDocument;
import io.floci.aws.services.iam.PublicAccessConditions;
import org.jboss.logging.Logger;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
@@ -118,10 +118,8 @@ final class S3PublicAccessEvaluator {
return PublicAccessDecision.NEUTRAL;
}
try {
JsonNode statements = objectMapper.readTree(policy).path("Statement");
boolean allowed = false;
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
for (JsonNode statement : iterable) {
for (JsonNode statement : PolicyDocument.statementsOf(objectMapper.readTree(policy))) {
String effect = effectOf(statement);
if (effect.isEmpty()) {
continue;
@@ -156,10 +154,8 @@ final class S3PublicAccessEvaluator {
return PublicAccessDecision.NEUTRAL;
}
try {
JsonNode statements = objectMapper.readTree(policy).path("Statement");
boolean allowed = false;
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
for (JsonNode statement : iterable) {
for (JsonNode statement : PolicyDocument.statementsOf(objectMapper.readTree(policy))) {
String effect = effectOf(statement);
if (effect.isEmpty()) {
continue;
@@ -199,9 +195,7 @@ final class S3PublicAccessEvaluator {
return false;
}
try {
JsonNode statements = objectMapper.readTree(policy).path("Statement");
Iterable<JsonNode> iterable = statements.isArray() ? statements : List.of(statements);
for (JsonNode statement : iterable) {
for (JsonNode statement : PolicyDocument.statementsOf(objectMapper.readTree(policy))) {
if (statementIsPublic(statement)) {
return true;
}
@@ -220,27 +214,12 @@ final class S3PublicAccessEvaluator {
if (!"Allow".equals(effectOf(statement))) {
return false;
}
if (!grantsToEveryone(statement)) {
if (!PolicyDocument.grantsToEveryone(statement)) {
return false;
}
return !conditionPinsToFixedValues(statement.path("Condition"));
}
private static boolean grantsToEveryone(JsonNode statement) {
if (statement.hasNonNull("Principal")) {
return hasPublicPrincipal(statement.path("Principal"));
}
// An Allow on NotPrincipal grants to everyone the statement does not name. Block Public
// Access asks a different question from the readers that decide a request: S3 "begins by
// assuming that the policy is public" and calls it non-public only when it grants "only to
// fixed values" of a principal or of one of the recognised condition keys (S3 User Guide,
// "The meaning of public"). A NotPrincipal pins no principal to a fixed value whether it
// names anybody or not, so the status stays public here even where the grant readers below
// decide the statement covers nobody.
return statement.hasNonNull("NotPrincipal")
&& !hasPublicPrincipal(statement.path("NotPrincipal"));
}
private static boolean conditionPinsToFixedValues(JsonNode conditions) {
if (conditions == null || !conditions.isObject()) {
return false;
@@ -333,10 +312,10 @@ final class S3PublicAccessEvaluator {
private static boolean principalMatchesPublic(JsonNode statement) {
if (statement.hasNonNull("Principal")) {
return hasPublicPrincipal(statement.path("Principal"));
return PolicyDocument.namesEveryone(statement.path("Principal"));
}
if (namesAnyPrincipal(statement.path("NotPrincipal"))) {
return !hasPublicPrincipal(statement.path("NotPrincipal"));
return !PolicyDocument.namesEveryone(statement.path("NotPrincipal"));
}
return false;
}
@@ -497,49 +476,6 @@ final class S3PublicAccessEvaluator {
return false;
}
private static boolean hasPublicPrincipal(JsonNode principal) {
if (principal == null || principal.isMissingNode() || principal.isNull()) {
return false;
}
if (principal.isTextual()) {
return "*".equals(principal.asText());
}
if (principal.isArray()) {
for (JsonNode item : principal) {
if ("*".equals(item.asText())) {
return true;
}
}
return false;
}
if (principal.isObject()) {
Iterator<JsonNode> values = principal.elements();
while (values.hasNext()) {
if (nodeContainsPublicPrincipal(values.next())) {
return true;
}
}
}
return false;
}
private static boolean nodeContainsPublicPrincipal(JsonNode node) {
if (node == null || node.isNull()) {
return false;
}
if (node.isTextual()) {
return "*".equals(node.asText());
}
if (node.isArray()) {
for (JsonNode item : node) {
if ("*".equals(item.asText())) {
return true;
}
}
}
return false;
}
private static boolean nodeCanMatch(JsonNode node) {
if (node == null || node.isNull()) {
return false;
@@ -1,6 +1,7 @@
package io.floci.aws.services.secretsmanager;
import com.fasterxml.jackson.databind.JsonNode;
import io.floci.aws.services.iam.PolicyDocument;
import java.util.ArrayList;
import java.util.List;
@@ -24,8 +25,6 @@ public final class ResourcePolicyValidator {
/** The name AWS reports a broad-principal finding under. */
public static final String REFLEXIVE_PRINCIPAL_CHECK = "REFLEXIVE_PRINCIPAL_CHECK";
private static final String WILDCARD = "*";
/** A single finding: the check that failed and what it found. */
public record ValidationError(String checkName, String errorMessage) {
}
@@ -40,15 +39,8 @@ public final class ResourcePolicyValidator {
*/
public static List<ValidationError> validate(JsonNode policy) {
List<ValidationError> errors = new ArrayList<>();
JsonNode statements = policy.path("Statement");
// A lone statement object is as valid as an array of them.
if (statements.isObject()) {
checkStatement(statements, errors);
} else if (statements.isArray()) {
for (JsonNode statement : statements) {
checkStatement(statement, errors);
}
for (JsonNode statement : PolicyDocument.statementsOf(policy)) {
checkStatement(statement, errors);
}
return errors;
}
@@ -59,45 +51,10 @@ public final class ResourcePolicyValidator {
if (!"Allow".equalsIgnoreCase(statement.path("Effect").asText())) {
return;
}
if (isWildcardPrincipal(statement.path("Principal"))) {
if (PolicyDocument.namesEveryone(statement.path("Principal"))) {
errors.add(new ValidationError(REFLEXIVE_PRINCIPAL_CHECK,
"The resource policy grants broad access to your secret. "
+ "Amend the policy so that it does not use a wildcard principal."));
}
}
/**
* A principal is wildcard either as the bare string {@code "*"} or as a keyed form whose value
* is {@code "*"} - {@code {"AWS": "*"}} and {@code {"AWS": ["*"]}} both grant everyone.
*/
private static boolean isWildcardPrincipal(JsonNode principal) {
if (principal.isMissingNode() || principal.isNull()) {
return false;
}
if (principal.isTextual()) {
return WILDCARD.equals(principal.asText());
}
if (principal.isObject()) {
for (JsonNode value : principal) {
if (containsWildcard(value)) {
return true;
}
}
}
return false;
}
private static boolean containsWildcard(JsonNode value) {
if (value.isTextual()) {
return WILDCARD.equals(value.asText());
}
if (value.isArray()) {
for (JsonNode entry : value) {
if (entry.isTextual() && WILDCARD.equals(entry.asText())) {
return true;
}
}
}
return false;
}
}
@@ -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."