mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(ses): publish to an SNS topic only when its policy allows SES (#5650)
Under IAM enforcement, SES published event-destination events and identity notifications to
whatever SNS topic it was configured with, through an internal call nothing checked, so a caller
refused sns:Publish could still put messages on a topic by pointing a configuration set at it. On
AWS, SES publishes as ses.amazonaws.com and the topic's policy decides: it has to allow SES, under
an aws:SourceArn naming the configuration set or identity whose configuration names the topic.
- ServiceCallAuthorizer decides a call one AWS service makes to another's resource on its own
behalf from the target's resource policy alone, read through the same providers the request
filter uses and picked by the target ARN's service. A target with no policy refuses, and with
enforcement off every call is allowed. ResourcePolicyProviders collects what the providers
supply, for the filter and the authorizer alike.
- IamConditionContextResolver.serviceCallContext builds that call's request context from the IAM
User Guide's global keys: aws:PrincipalIsAWSService, aws:PrincipalServiceName and
aws:PrincipalServiceNamesList, aws:SourceArn and aws:SourceAccount, aws:ResourceAccount and
aws:RequestedRegion, and none of the keys that describe an IAM principal. A publish to an SNS
topic from SES also carries aws:SourceOwner, which the SNS Developer Guide lists SES among the
services setting, and which the default topic policy checks.
- SnsResourcePolicyProvider supplies a topic's policy and the account in its ARN, also when the
topic does not exist. A topic with no Policy attribute gets the default a new topic has, for the
topic's own account. Topic policies so also take part in a JSON-protocol request that names a
topic, as any resource policy does.
- SesEventPublisher asks before publishing to SNS: for an event destination with the configuration
set's ARN, for an identity notification with the ARN of the identity that names the topic, the
sender's own or its domain's, both with the sending account. A refused event is dropped. A
notification SES cannot publish, because the topic is gone from its own account or its policy
refuses SES, also takes the topic out of the identity's bounce and complaint settings and turns
email feedback forwarding back on, as the SES Developer Guide describes; a delivery setting
stays. The identity's notification settings are written under the identity lock, so that
write and an API call changing them cannot lose each other.
- CreateReceiptRule and UpdateReceiptRule ask the same question of an action's TopicArn, with the
rule's ARN as aws:SourceArn, and answer InvalidSnsTopic when the topic's policy does not let SES
publish, which the SES API Reference lists as "could not publish to the topic, possibly due to
permissions issues". The rules still route no mail.
- A resource policy statement that names the caller only through its account, by its id, root ARN
or S3 canonical user ID, delegates to that account (IAM User Guide, "AWS account principals"):
across accounts it is still the owner's half of the grant, but within the account it no longer
grants on its own, and the caller's identity policies have to allow the request. Floci let such
a statement grant on its own, for bucket and function policies already, so a topic policy naming
its own account would have let every user of the account publish.
- A Deny's NotPrincipal follows the IAM User Guide ("AWS JSON policy elements: NotPrincipal"): it
spares an IAM caller only when it names the caller's account as well as the caller, since without
the account AWS "might deny access to the entire account", and never spares one with a permissions
boundary attached, which it "will always deny". CallerArns says whether a boundary is attached to
the user or to the role a session assumed. An Allow's NotPrincipal still grants everyone it does
not name, as Access Analyzer warns it can.
This commit is contained in:
1 parent
17c40cecbd
commit
46f4977b23
34 files changed
+1924
-129
No files matched your search
+41
@@ -688,6 +688,47 @@ class IamConditionContextResolverTest {
|
||||
assertEquals(List.of("000000000000"), conditions.get("aws:PrincipalAccount"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceCallCarriesTheServiceAndItsSourceButNoIamPrincipal() {
|
||||
Map<String, List<String>> conditions = IamConditionContextResolver.serviceCallContext(
|
||||
"ses.amazonaws.com", "arn:aws:sns:eu-west-2:111122223333:events", "111122223333",
|
||||
"arn:aws:ses:eu-west-2:444455556666:configuration-set/my-set", "444455556666");
|
||||
|
||||
assertEquals(Map.of(
|
||||
"aws:PrincipalIsAWSService", List.of("true"),
|
||||
"aws:PrincipalServiceName", List.of("ses.amazonaws.com"),
|
||||
"aws:PrincipalServiceNamesList", List.of("ses.amazonaws.com"),
|
||||
"aws:SourceArn", List.of("arn:aws:ses:eu-west-2:444455556666:configuration-set/my-set"),
|
||||
"aws:SourceAccount", List.of("444455556666"),
|
||||
"aws:SourceOwner", List.of("444455556666"),
|
||||
"aws:ResourceAccount", List.of("111122223333"),
|
||||
"aws:RequestedRegion", List.of("eu-west-2")), conditions);
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyACallToATopicFromAServiceSnsListsCarriesSourceOwner() {
|
||||
Map<String, List<String>> fromS3 = IamConditionContextResolver.serviceCallContext(
|
||||
"s3.amazonaws.com", "arn:aws:sns:eu-west-2:111122223333:events", "111122223333",
|
||||
"arn:aws:s3:::bucket", "111122223333");
|
||||
Map<String, List<String>> toQueue = IamConditionContextResolver.serviceCallContext(
|
||||
"ses.amazonaws.com", "arn:aws:sqs:eu-west-2:111122223333:events", "111122223333",
|
||||
"arn:aws:ses:eu-west-2:111122223333:configuration-set/my-set", "111122223333");
|
||||
|
||||
assertFalse(fromS3.containsKey("aws:SourceOwner"));
|
||||
assertEquals(List.of("111122223333"), fromS3.get("aws:SourceAccount"));
|
||||
assertFalse(toQueue.containsKey("aws:SourceOwner"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aServiceCallWithNoSourceLeavesTheSourceKeysOut() {
|
||||
Map<String, List<String>> conditions = IamConditionContextResolver.serviceCallContext(
|
||||
"ses.amazonaws.com", "arn:aws:s3:::bucket", "111122223333", null, null);
|
||||
|
||||
assertFalse(conditions.containsKey("aws:SourceArn"));
|
||||
assertFalse(conditions.containsKey("aws:SourceAccount"));
|
||||
assertEquals(List.of("111122223333"), conditions.get("aws:ResourceAccount"));
|
||||
}
|
||||
|
||||
private Decision decisionForEveryTarget(String policy, String action, ContainerRequestContext request) {
|
||||
Decision first = evaluator.simulateCustomPolicy(List.of(policy), action, "*",
|
||||
resolver.resolve("ec2", action, request));
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
package io.github.hectorvent.floci.core.common;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class ServiceCallAuthorizerTest {
|
||||
|
||||
private static final String OWNER = "111122223333";
|
||||
private static final String OTHER = "444455556666";
|
||||
private static final String TOPIC = "arn:aws:sns:us-east-1:" + OWNER + ":events";
|
||||
private static final String CONFIG_SET = "arn:aws:ses:us-east-1:" + OWNER + ":configuration-set/my-set";
|
||||
|
||||
/** The topic policy the SES Developer Guide gives for an SNS event destination. */
|
||||
private static final String SES_GUIDE_POLICY = """
|
||||
{"Version":"2012-10-17","Id":"notification-policy","Statement":[{
|
||||
"Effect":"Allow","Principal":{"Service":"ses.amazonaws.com"},"Action":"sns:Publish",
|
||||
"Resource":"%s",
|
||||
"Condition":{"StringEquals":{"AWS:SourceAccount":"%s","AWS:SourceArn":"%s"}}}]}"""
|
||||
.formatted(TOPIC, OWNER, CONFIG_SET);
|
||||
|
||||
/** The policy a new topic starts with. */
|
||||
private static final String DEFAULT_TOPIC_POLICY = """
|
||||
{"Version":"2008-10-17","Id":"__default_policy_ID","Statement":[{
|
||||
"Sid":"__default_statement_ID","Effect":"Allow","Principal":{"AWS":"*"},
|
||||
"Action":["SNS:GetTopicAttributes","SNS:SetTopicAttributes","SNS:AddPermission",
|
||||
"SNS:RemovePermission","SNS:DeleteTopic","SNS:Subscribe","SNS:ListSubscriptionsByTopic",
|
||||
"SNS:Publish"],
|
||||
"Resource":"%s","Condition":{"StringEquals":{"AWS:SourceOwner":"%s"}}}]}"""
|
||||
.formatted(TOPIC, OWNER);
|
||||
|
||||
private EmulatorConfig.IamServiceConfig iamConfig;
|
||||
private final List<ResourcePolicyProvider> providers = new ArrayList<>();
|
||||
private final List<String> scopesAsked = new ArrayList<>();
|
||||
private ServiceCallAuthorizer authorizer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
EmulatorConfig config = mock(EmulatorConfig.class);
|
||||
EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
|
||||
iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
|
||||
when(config.services()).thenReturn(services);
|
||||
when(services.iam()).thenReturn(iamConfig);
|
||||
when(iamConfig.enforcementEnabled()).thenReturn(true);
|
||||
@SuppressWarnings("unchecked")
|
||||
Instance<ResourcePolicyProvider> instance = mock(Instance.class);
|
||||
when(instance.isUnsatisfied()).thenAnswer(invocation -> providers.isEmpty());
|
||||
when(instance.iterator()).thenAnswer(invocation -> providers.iterator());
|
||||
authorizer = new ServiceCallAuthorizer(config, new IamPolicyEvaluator(new ObjectMapper()), instance);
|
||||
}
|
||||
|
||||
private void topicPolicy(String policy) {
|
||||
providers.add((scope, arn) -> {
|
||||
scopesAsked.add(scope);
|
||||
return TOPIC.equals(arn) ? List.of(new ResourcePolicyProvider.ResourcePolicy(policy, OWNER)) : List.of();
|
||||
});
|
||||
}
|
||||
|
||||
private Decision sesPublish(String sourceArn, String sourceAccount) {
|
||||
return authorizer.authorize("ses", "sns:Publish", TOPIC, sourceArn, sourceAccount);
|
||||
}
|
||||
|
||||
@Test
|
||||
void withEnforcementOffEveryCallIsAllowed() {
|
||||
when(iamConfig.enforcementEnabled()).thenReturn(false);
|
||||
|
||||
assertEquals(Decision.ALLOW, sesPublish(CONFIG_SET, OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSesGuidesTopicPolicyAdmitsTheConfigurationSetItNames() {
|
||||
topicPolicy(SES_GUIDE_POLICY);
|
||||
|
||||
assertEquals(Decision.ALLOW, sesPublish(CONFIG_SET, OWNER));
|
||||
assertEquals(List.of("sns"), scopesAsked);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantNamingOneConfigurationSetDoesNotAdmitAnother() {
|
||||
topicPolicy(SES_GUIDE_POLICY);
|
||||
|
||||
assertEquals(Decision.DENY,
|
||||
sesPublish("arn:aws:ses:us-east-1:" + OWNER + ":configuration-set/other-set", OWNER));
|
||||
assertEquals(Decision.DENY,
|
||||
sesPublish("arn:aws:ses:us-east-1:" + OTHER + ":configuration-set/my-set", OTHER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantToAnotherServiceDoesNotAdmitSes() {
|
||||
topicPolicy(SES_GUIDE_POLICY.replace("ses.amazonaws.com", "s3.amazonaws.com"));
|
||||
|
||||
assertEquals(Decision.DENY, sesPublish(CONFIG_SET, OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultTopicPolicyAdmitsAServiceActingForTheOwnersAccountOnly() {
|
||||
topicPolicy(DEFAULT_TOPIC_POLICY);
|
||||
|
||||
assertEquals(Decision.ALLOW, sesPublish(CONFIG_SET, OWNER));
|
||||
assertEquals(Decision.DENY,
|
||||
sesPublish("arn:aws:ses:us-east-1:" + OTHER + ":configuration-set/my-set", OTHER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultTopicPolicyAdmitsNoServiceThatSetsOnlySourceAccount() {
|
||||
topicPolicy(DEFAULT_TOPIC_POLICY);
|
||||
|
||||
assertEquals(Decision.DENY,
|
||||
authorizer.authorize("s3", "sns:Publish", TOPIC, "arn:aws:s3:::bucket", OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyInTheTopicPolicyWins() {
|
||||
topicPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"Service":"ses.amazonaws.com"},"Action":"sns:Publish","Resource":"%1$s"},
|
||||
{"Effect":"Deny","Principal":"*","Action":"sns:Publish","Resource":"%1$s",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalServiceName":"ses.amazonaws.com"}}}]}"""
|
||||
.formatted(TOPIC));
|
||||
|
||||
assertEquals(Decision.DENY, sesPublish(CONFIG_SET, OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTargetWithNoPolicyIsRefused() {
|
||||
assertEquals(Decision.DENY, sesPublish(CONFIG_SET, OWNER));
|
||||
|
||||
topicPolicy(null);
|
||||
assertEquals(Decision.DENY, sesPublish(CONFIG_SET, OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantConditionedOnAnIamPrincipalDoesNotMatchAServiceCall() {
|
||||
topicPolicy("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sns:Publish","Resource":"%s",
|
||||
"Condition":{"StringLike":{"aws:PrincipalArn":"*"}}}]}""".formatted(TOPIC));
|
||||
|
||||
assertEquals(Decision.DENY, sesPublish(CONFIG_SET, OWNER));
|
||||
}
|
||||
}
|
||||
@@ -184,6 +184,47 @@ class IamPolicyEvaluatorTest {
|
||||
null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantToTheCallersOwnAccountDelegatesToItsIdentityPolicies() {
|
||||
// IAM User Guide, "AWS account principals": naming an account "delegates authority to the
|
||||
// account", so within it the caller's own policies decide; a grant naming the caller
|
||||
// itself, or anyone, grants on its own.
|
||||
String accountGrant = resourcePolicy("Allow", "\"Principal\":{\"AWS\":\"arn:aws:iam::123456789012:root\"}");
|
||||
String everyoneGrant = resourcePolicy("Allow", "\"Principal\":{\"AWS\":\"*\"}");
|
||||
RequestPrincipal alice = RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice");
|
||||
ResourcePolicyDecision delegated = resourceDecision(accountGrant, alice);
|
||||
|
||||
assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT, delegated);
|
||||
assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(CallerContext.of(List.of()),
|
||||
delegated, ResourceAccountRelationship.SAME_ACCOUNT, "s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy(CallerContext.of(List.of(ALLOW_ALL)),
|
||||
delegated, ResourceAccountRelationship.SAME_ACCOUNT, "s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy(CallerContext.of(List.of()),
|
||||
resourceDecision(everyoneGrant, alice), ResourceAccountRelationship.SAME_ACCOUNT,
|
||||
"s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantToTheCallersAccountIsTheOwnersHalfOfACrossAccountGrant() {
|
||||
assertEquals(Decision.ALLOW, evaluator.evaluateResolvedResourcePolicy(CallerContext.of(List.of(ALLOW_ALL)),
|
||||
ResourcePolicyDecision.ALLOW_ACCOUNT, ResourceAccountRelationship.CROSS_ACCOUNT,
|
||||
"s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(CallerContext.of(List.of()),
|
||||
ResourcePolicyDecision.ALLOW_ACCOUNT, ResourceAccountRelationship.CROSS_ACCOUNT,
|
||||
"s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantNamingTheCallerWinsOverOneNamingOnlyItsAccount() {
|
||||
String both = resourcePolicy("Allow",
|
||||
"\"Principal\":{\"AWS\":[\"123456789012\",\"arn:aws:iam::123456789012:role/App\"]}");
|
||||
|
||||
assertEquals(ResourcePolicyDecision.ALLOW, resourceDecision(both, RequestPrincipal.roleSession(
|
||||
"arn:aws:sts::123456789012:assumed-role/App/s", "arn:aws:iam::123456789012:role/App")));
|
||||
assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT, resourceDecision(both, RequestPrincipal.roleSession(
|
||||
"arn:aws:sts::123456789012:assumed-role/Other/s", "arn:aws:iam::123456789012:role/Other")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void crossAccountResourceAllowRequiresIdentityAllow() {
|
||||
CallerContext caller = CallerContext.of(List.of());
|
||||
@@ -747,7 +788,7 @@ class IamPolicyEvaluatorTest {
|
||||
List.of(rolePolicy), "arn:aws-cn:sts::123456789012:assumed-role/r/sess", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
|
||||
String chinaRootPolicy = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws-cn:iam::123456789012:root"},"Action":"s3:*","Resource":"*"}]}""";
|
||||
assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(
|
||||
assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT, evaluator.evaluateResourcePolicy(
|
||||
List.of(chinaRootPolicy), "arn:aws-cn:iam::123456789012:user/alice", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
|
||||
List.of(chinaRootPolicy), "arn:aws-cn:iam::999999999999:user/bob", "s3:GetObject", "arn:aws-cn:s3:::b/k", null));
|
||||
@@ -766,7 +807,7 @@ class IamPolicyEvaluatorTest {
|
||||
String rootPolicy = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::123456789012:root"},"Action":"s3:*","Resource":"*"}]}""";
|
||||
for (String p : List.of(acctPolicy, rootPolicy)) {
|
||||
assertEquals(ResourcePolicyDecision.ALLOW, evaluator.evaluateResourcePolicy(
|
||||
assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT, evaluator.evaluateResourcePolicy(
|
||||
List.of(p), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
|
||||
List.of(p), "arn:aws:iam::999999999999:user/bob", "s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
@@ -859,9 +900,9 @@ class IamPolicyEvaluatorTest {
|
||||
// S3 bucket policies can name an account by its canonical user ID (IAM User Guide, "AWS
|
||||
// account principals"); Floci's canonical ID for an account is the account id.
|
||||
String canonical = resourcePolicy("Allow", "\"Principal\":{\"CanonicalUser\":\"123456789012\"}");
|
||||
assertEquals(ResourcePolicyDecision.ALLOW,
|
||||
assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT,
|
||||
resourceDecision(canonical, RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice")));
|
||||
assertEquals(ResourcePolicyDecision.ALLOW, resourceDecision(canonical, RequestPrincipal.roleSession(
|
||||
assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT, resourceDecision(canonical, RequestPrincipal.roleSession(
|
||||
"arn:aws:sts::123456789012:assumed-role/App/s", "arn:aws:iam::123456789012:role/team/App")));
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL,
|
||||
resourceDecision(canonical, RequestPrincipal.iam("arn:aws:iam::210987654321:user/alice")));
|
||||
@@ -911,9 +952,10 @@ class IamPolicyEvaluatorTest {
|
||||
|
||||
@Test
|
||||
void evaluatesResourcePolicyDenyAndNotPrincipal() {
|
||||
// NotPrincipal inversion: anyone NOT alice is denied
|
||||
// NotPrincipal inversion: anyone NOT alice is denied; alice is spared when her account is
|
||||
// named with her (IAM User Guide, "AWS JSON policy elements: NotPrincipal")
|
||||
String notPrincipal = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","NotPrincipal":{"AWS":"arn:aws:iam::123456789012:user/alice"},"Action":"s3:*","Resource":"*"}]}""";
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Deny","NotPrincipal":{"AWS":["arn:aws:iam::123456789012:user/alice","arn:aws:iam::123456789012:root"]},"Action":"s3:*","Resource":"*"}]}""";
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL, evaluator.evaluateResourcePolicy(
|
||||
List.of(notPrincipal), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
assertEquals(ResourcePolicyDecision.EXPLICIT_DENY, evaluator.evaluateResourcePolicy(
|
||||
@@ -937,6 +979,54 @@ class IamPolicyEvaluatorTest {
|
||||
List.of(noPrincipal), "arn:aws:iam::123456789012:user/alice", "s3:GetObject", "arn:aws:s3:::b/k", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenysNotPrincipalSparesAnIamCallerOnlyWhenItNamesItsAccountToo() {
|
||||
// IAM User Guide, "AWS JSON policy elements: NotPrincipal": without the account ARN, "the
|
||||
// policy might deny access to the entire account containing the principal".
|
||||
RequestPrincipal alice = RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice");
|
||||
RequestPrincipal session = RequestPrincipal.roleSession(
|
||||
"arn:aws:sts::123456789012:assumed-role/App/s", "arn:aws:iam::123456789012:role/App");
|
||||
RequestPrincipal root = RequestPrincipal.iam("arn:aws:iam::123456789012:root");
|
||||
|
||||
assertEquals(ResourcePolicyDecision.EXPLICIT_DENY, resourceDecision(resourcePolicy("Deny",
|
||||
"\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::123456789012:user/alice\"}"), alice));
|
||||
assertEquals(ResourcePolicyDecision.EXPLICIT_DENY, resourceDecision(resourcePolicy("Deny",
|
||||
"\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::123456789012:role/App\"}"), session));
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(resourcePolicy("Deny",
|
||||
"\"NotPrincipal\":{\"AWS\":[\"arn:aws:iam::123456789012:role/App\",\"123456789012\"]}"), session));
|
||||
assertEquals(ResourcePolicyDecision.EXPLICIT_DENY, resourceDecision(resourcePolicy("Deny",
|
||||
"\"NotPrincipal\":{\"AWS\":\"123456789012\"}"), alice));
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(resourcePolicy("Deny",
|
||||
"\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::123456789012:root\"}"), root));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenysNotPrincipalNeverSparesACallerWithAPermissionsBoundary() {
|
||||
// IAM User Guide: it "will always deny any IAM principal that has a permissions boundary
|
||||
// policy attached, regardless of the values specified in the NotPrincipal element".
|
||||
String sparesAlice = resourcePolicy("Deny", "\"NotPrincipal\":{\"AWS\":"
|
||||
+ "[\"arn:aws:iam::123456789012:user/alice\",\"arn:aws:iam::123456789012:root\"]}");
|
||||
RequestPrincipal alice = RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice");
|
||||
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL, resourceDecision(sparesAlice, alice));
|
||||
assertEquals(ResourcePolicyDecision.EXPLICIT_DENY,
|
||||
resourceDecision(sparesAlice, new RequestPrincipal(RequestPrincipal.Type.IAM, alice.arn(), null, null, true)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAllowsNotPrincipalGrantsEveryoneItDoesNotName() {
|
||||
// Access Analyzer warns that Allow with NotPrincipal "can grant permissions to anonymous
|
||||
// principals"; whoever it names, at any level, is left out.
|
||||
String allButAlice = resourcePolicy("Allow",
|
||||
"\"NotPrincipal\":{\"AWS\":\"arn:aws:iam::123456789012:user/alice\"}");
|
||||
|
||||
assertEquals(ResourcePolicyDecision.NEUTRAL,
|
||||
resourceDecision(allButAlice, RequestPrincipal.iam("arn:aws:iam::123456789012:user/alice")));
|
||||
assertEquals(ResourcePolicyDecision.ALLOW,
|
||||
resourceDecision(allButAlice, RequestPrincipal.iam("arn:aws:iam::123456789012:user/bob")));
|
||||
assertEquals(ResourcePolicyDecision.ALLOW, resourceDecision(allButAlice, RequestPrincipal.anonymous()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void evaluatesResourcePolicyConditionsAndIdentityParity() {
|
||||
String condPolicy = """
|
||||
@@ -1062,7 +1152,7 @@ class IamPolicyEvaluatorTest {
|
||||
}]}""";
|
||||
ResourcePolicyDecision accountDecision = evaluator.evaluateResourcePolicy(
|
||||
List.of(accountGrantPolicy), "arn:aws:iam::111111111111:user/alice", "s3:GetObject", "arn:aws:s3:::bucket/k", null);
|
||||
assertEquals(ResourcePolicyDecision.ALLOW, accountDecision);
|
||||
assertEquals(ResourcePolicyDecision.ALLOW_ACCOUNT, accountDecision);
|
||||
assertEquals(Decision.DENY, evaluator.evaluateResolvedResourcePolicy(
|
||||
caller,
|
||||
accountDecision,
|
||||
|
||||
@@ -396,6 +396,27 @@ class IamServiceTest {
|
||||
assertEquals(user.getArn(), arns.callerArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void callerArnsSayWhetherAPermissionsBoundaryIsAttached() {
|
||||
IamService service = iamService(false);
|
||||
String boundaryArn = service.createPolicy("bound", "/", null, ALL_S3, null).getArn();
|
||||
service.createUser("alice", "/");
|
||||
String aliceKey = service.createAccessKey("alice").getAccessKeyId();
|
||||
service.createRole("Worker", "/", "{}", null, 3600, null);
|
||||
service.registerSession("ASIABOUNDEDROLE", "secret", "token",
|
||||
"arn:aws:iam::000000000000:role/Worker", Instant.parse("2100-01-01T00:00:00Z"), null,
|
||||
"000000000000", "s", "AROAWORKER:s");
|
||||
|
||||
assertFalse(service.resolveCallerArns(aliceKey).orElseThrow().permissionsBoundary());
|
||||
assertFalse(service.resolveCallerArns("ASIABOUNDEDROLE").orElseThrow().permissionsBoundary());
|
||||
|
||||
service.putUserPermissionsBoundary("alice", boundaryArn);
|
||||
service.putRolePermissionsBoundary("Worker", boundaryArn);
|
||||
|
||||
assertTrue(service.resolveCallerArns(aliceKey).orElseThrow().permissionsBoundary());
|
||||
assertTrue(service.resolveCallerArns("ASIABOUNDEDROLE").orElseThrow().permissionsBoundary());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sessionExpiryFollowsTheInjectedClock() {
|
||||
MutableClock clock = new MutableClock();
|
||||
|
||||
@@ -2,13 +2,16 @@ package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
|
||||
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
|
||||
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
|
||||
import io.github.hectorvent.floci.services.firehose.FirehoseService;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.ses.SesRecipientEvent.Cause;
|
||||
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
|
||||
import io.github.hectorvent.floci.services.ses.model.EventBridgeDestination;
|
||||
import io.github.hectorvent.floci.services.ses.model.EventDestination;
|
||||
import io.github.hectorvent.floci.services.ses.model.SnsDestination;
|
||||
import io.github.hectorvent.floci.services.sns.SnsService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -23,11 +26,15 @@ import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@@ -48,18 +55,76 @@ class SesEventPublisherTest {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final String DEFAULT_BUS_ARN =
|
||||
"arn:aws:events:us-east-1:000000000000:event-bus/default";
|
||||
private static final String ACCOUNT = "111122223333";
|
||||
private static final String TOPIC_ARN = "arn:aws:sns:us-east-1:" + ACCOUNT + ":ses-events";
|
||||
private static final String CONFIGURATION_SET_ARN =
|
||||
"arn:aws:ses:us-east-1:" + ACCOUNT + ":configuration-set/cs-test";
|
||||
private static final String DOMAIN_ARN = "arn:aws:ses:us-east-1:" + ACCOUNT + ":identity/example.com";
|
||||
|
||||
@Mock private SnsService snsService;
|
||||
@Mock private FirehoseService firehoseService;
|
||||
@Mock private EventBridgeService eventBridgeService;
|
||||
@Mock private CloudWatchMetricsService cloudWatchMetricsService;
|
||||
@Mock private ServiceCallAuthorizer serviceCallAuthorizer;
|
||||
|
||||
private SesEventPublisher publisher;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
publisher = new SesEventPublisher(snsService, firehoseService, eventBridgeService,
|
||||
cloudWatchMetricsService, MAPPER);
|
||||
cloudWatchMetricsService, serviceCallAuthorizer, MAPPER);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anSnsEventDestinationPublishesAsSesForItsConfigurationSet() {
|
||||
when(serviceCallAuthorizer.authorize("ses", "sns:Publish", TOPIC_ARN, CONFIGURATION_SET_ARN, ACCOUNT))
|
||||
.thenReturn(Decision.ALLOW);
|
||||
|
||||
publishSendEvent(configurationSetWithSnsDestination(TOPIC_ARN));
|
||||
|
||||
verify(snsService).publish(eq(TOPIC_ARN), isNull(), anyString(), isNull(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anSnsEventDestinationWhoseTopicRefusesSesGetsNothing() {
|
||||
when(serviceCallAuthorizer.authorize("ses", "sns:Publish", TOPIC_ARN, CONFIGURATION_SET_ARN, ACCOUNT))
|
||||
.thenReturn(Decision.DENY);
|
||||
|
||||
publishSendEvent(configurationSetWithSnsDestination(TOPIC_ARN));
|
||||
|
||||
verify(snsService, never()).publish(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdentityNotificationPublishesAsSesForTheIdentityThatNamesTheTopic() {
|
||||
when(serviceCallAuthorizer.authorize("ses", "sns:Publish", TOPIC_ARN, DOMAIN_ARN, ACCOUNT))
|
||||
.thenReturn(Decision.ALLOW);
|
||||
when(snsService.topicExists(TOPIC_ARN, "us-east-1")).thenReturn(true);
|
||||
|
||||
assertTrue(publishBounceNotification());
|
||||
|
||||
verify(snsService).publish(eq(TOPIC_ARN), isNull(), anyString(), isNull(), eq("us-east-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdentityNotificationToATopicThatIsGoneIsNotSentAndSaysSo() {
|
||||
when(serviceCallAuthorizer.authorize("ses", "sns:Publish", TOPIC_ARN, DOMAIN_ARN, ACCOUNT))
|
||||
.thenReturn(Decision.ALLOW);
|
||||
when(snsService.topicExists(TOPIC_ARN, "us-east-1")).thenReturn(false);
|
||||
|
||||
assertFalse(publishBounceNotification());
|
||||
|
||||
verify(snsService, never()).publish(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIdentityNotificationWhoseTopicRefusesSesIsNotSentAndSaysSo() {
|
||||
when(serviceCallAuthorizer.authorize("ses", "sns:Publish", TOPIC_ARN, DOMAIN_ARN, ACCOUNT))
|
||||
.thenReturn(Decision.DENY);
|
||||
|
||||
assertFalse(publishBounceNotification());
|
||||
|
||||
verify(snsService, never()).publish(any(), any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -143,6 +208,35 @@ class SesEventPublisherTest {
|
||||
return entries.get(0);
|
||||
}
|
||||
|
||||
private void publishSendEvent(ConfigurationSet configurationSet) {
|
||||
publisher.publish(configurationSet, SesRecipientEvent.of("SEND", Cause.SIMULATOR, List.of()), "msg-sns",
|
||||
"sender@example.com", "arn:aws:ses:us-east-1:" + ACCOUNT + ":identity/sender@example.com",
|
||||
ACCOUNT, "subj", List.of("to@example.com"), null, null, List.of("to@example.com"), null, null,
|
||||
Instant.parse("2026-01-01T00:00:00Z"), "us-east-1");
|
||||
}
|
||||
|
||||
/** A bounce from {@code sender@example.com}, whose domain names the topic. */
|
||||
private boolean publishBounceNotification() {
|
||||
return publisher.publishIdentityNotification(TOPIC_ARN, DOMAIN_ARN, false,
|
||||
SesRecipientEvent.of("BOUNCE", Cause.SIMULATOR, List.of("bounce@simulator.amazonses.com")),
|
||||
"msg-bounce", "sender@example.com", "arn:aws:ses:us-east-1:" + ACCOUNT + ":identity/sender@example.com",
|
||||
ACCOUNT, "subj", List.of("bounce@simulator.amazonses.com"), null, null,
|
||||
List.of("bounce@simulator.amazonses.com"), null, Instant.parse("2026-01-01T00:00:00Z"), "us-east-1");
|
||||
}
|
||||
|
||||
private ConfigurationSet configurationSetWithSnsDestination(String topicArn) {
|
||||
SnsDestination snsDestination = new SnsDestination();
|
||||
snsDestination.setTopicArn(topicArn);
|
||||
EventDestination ed = new EventDestination();
|
||||
ed.setName("ed-sns");
|
||||
ed.setEnabled(true);
|
||||
ed.setMatchingEventTypes(List.of("SEND"));
|
||||
ed.setSnsDestination(snsDestination);
|
||||
ConfigurationSet cs = new ConfigurationSet("cs-test");
|
||||
cs.setEventDestinations(List.of(ed));
|
||||
return cs;
|
||||
}
|
||||
|
||||
private ConfigurationSet configurationSetWithEventBridgeDestination(String busArn) {
|
||||
EventBridgeDestination ebd = new EventBridgeDestination();
|
||||
ebd.setEventBusArn(busArn);
|
||||
|
||||
+59
@@ -246,6 +246,65 @@ class SesIdentityNotificationTopicPublishV1IntegrationTest {
|
||||
assertEquals(SENDER, bounce.path("mail").path("source").asText());
|
||||
}
|
||||
|
||||
/**
|
||||
* SES Developer Guide, "Configuring Amazon SNS notifications for Amazon SES": when a publish fails
|
||||
* "because the topic has been deleted", SES removes a bounce or complaint topic from the identity
|
||||
* and re-enables email feedback forwarding. That holds with IAM enforcement off too.
|
||||
*/
|
||||
@Test
|
||||
@Order(10)
|
||||
void aDeletedBounceTopicIsTakenOutOfTheIdentityAndForwardingTurnsBackOn() {
|
||||
String gone = "id-notif-gone@floci.test";
|
||||
verifyEmailIdentity(gone);
|
||||
String goneTopic = given()
|
||||
.contentType(JSON_10)
|
||||
.header("Authorization", SNS_AUTH)
|
||||
.header("X-Amz-Target", "SNS_20100331.CreateTopic")
|
||||
.body("{\"Name\":\"ses-id-notif-gone-topic\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("TopicArn");
|
||||
setIdentityNotificationTopic(gone, "Bounce", goneTopic);
|
||||
setIdentityNotificationTopic(gone, "Complaint", goneTopic);
|
||||
given()
|
||||
.contentType(FORM)
|
||||
.header("Authorization", SES_AUTH)
|
||||
.body("Action=SetIdentityFeedbackForwardingEnabled&Identity="
|
||||
+ URLEncoder.encode(gone, StandardCharsets.UTF_8)
|
||||
+ "&ForwardingEnabled=false&Version=2010-12-01")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
given()
|
||||
.contentType(JSON_10)
|
||||
.header("Authorization", SNS_AUTH)
|
||||
.header("X-Amz-Target", "SNS_20100331.DeleteTopic")
|
||||
.body("{\"TopicArn\":\"" + goneTopic + "\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
sendEmail(gone, "bounce@simulator.amazonses.com", "id-notif-gone");
|
||||
|
||||
String attributes = given()
|
||||
.contentType(FORM)
|
||||
.header("Authorization", SES_AUTH)
|
||||
.body("Action=GetIdentityNotificationAttributes&Identities.member.1="
|
||||
+ URLEncoder.encode(gone, StandardCharsets.UTF_8) + "&Version=2010-12-01")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.extract().asString();
|
||||
assertTrue(attributes.contains("<BounceTopic></BounceTopic>"), attributes);
|
||||
assertTrue(attributes.contains("<ComplaintTopic></ComplaintTopic>"), attributes);
|
||||
assertTrue(attributes.contains("<ForwardingEnabled>true</ForwardingEnabled>"), attributes);
|
||||
}
|
||||
|
||||
private void verifyEmailIdentity(String email) {
|
||||
given()
|
||||
.contentType(FORM)
|
||||
|
||||
@@ -6,22 +6,37 @@ import io.github.hectorvent.floci.services.ses.model.Identity;
|
||||
import io.github.hectorvent.floci.services.ses.model.Tag;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.mockito.Mockito;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static io.github.hectorvent.floci.testing.ThreadStates.awaitBlockedOrDone;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.doAnswer;
|
||||
|
||||
/**
|
||||
* Unit test for the extracted identity domain: store ownership, key validation, verification
|
||||
* (email and domain), listing, MAIL FROM, the CVET pending registration, identity tags, and the
|
||||
* find/save escape hatches the facade's notification flows rely on. The DKIM state machine moved
|
||||
* find/save escape hatches the facade's notification flows rely on, and what SES does to an
|
||||
* identity's notification settings when it may not publish to a topic. The DKIM state machine moved
|
||||
* here too and keeps its behavioral coverage in the existing facade-level unit and integration
|
||||
* tests, which now exercise it through the delegation; only its creation-time surface is pinned
|
||||
* here.
|
||||
@@ -29,6 +44,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
class SesIdentityServiceTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String TOPIC = "arn:aws:sns:us-east-1:000000000000:feedback";
|
||||
private static final String OTHER_TOPIC = "arn:aws:sns:us-east-1:000000000000:other-feedback";
|
||||
private SesIdentityService service;
|
||||
|
||||
@BeforeEach
|
||||
@@ -339,6 +356,123 @@ class SesIdentityServiceTest {
|
||||
service.createEmailIdentity(identity, null, null, REGION, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedTopicIsTakenOutOfEveryBounceAndComplaintSettingThatNamesIt() {
|
||||
service.verifyEmailIdentity("alice@example.com", REGION);
|
||||
for (String type : List.of("Bounce", "Complaint", "Delivery")) {
|
||||
service.setIdentityNotificationTopic("alice@example.com", type, TOPIC, REGION);
|
||||
}
|
||||
service.setFeedbackForwardingEnabled("alice@example.com", false, REGION);
|
||||
|
||||
service.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION);
|
||||
|
||||
Identity identity = service.find("alice@example.com", REGION).orElseThrow();
|
||||
assertFalse(identity.getNotificationAttributes().containsKey("BounceTopic"));
|
||||
assertFalse(identity.getNotificationAttributes().containsKey("ComplaintTopic"));
|
||||
assertEquals(TOPIC, identity.getNotificationAttributes().get("DeliveryTopic"));
|
||||
assertTrue(identity.isFeedbackForwardingEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSettingNamingAnotherTopicIsKept() {
|
||||
service.verifyEmailIdentity("alice@example.com", REGION);
|
||||
service.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION);
|
||||
service.setIdentityNotificationTopic("alice@example.com", "Complaint", OTHER_TOPIC, REGION);
|
||||
|
||||
service.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION);
|
||||
|
||||
Identity identity = service.find("alice@example.com", REGION).orElseThrow();
|
||||
assertFalse(identity.getNotificationAttributes().containsKey("BounceTopic"));
|
||||
assertEquals(OTHER_TOPIC, identity.getNotificationAttributes().get("ComplaintTopic"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicNamedOnlyForDeliveriesStaysConfigured() {
|
||||
service.verifyEmailIdentity("alice@example.com", REGION);
|
||||
service.setIdentityNotificationTopic("alice@example.com", "Delivery", TOPIC, REGION);
|
||||
service.setFeedbackForwardingEnabled("alice@example.com", false, REGION);
|
||||
|
||||
service.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION);
|
||||
|
||||
Identity identity = service.find("alice@example.com", REGION).orElseThrow();
|
||||
assertEquals(TOPIC, identity.getNotificationAttributes().get("DeliveryTopic"));
|
||||
assertFalse(identity.isFeedbackForwardingEnabled());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicSetAgainSinceTheRefusalIsKept() {
|
||||
service.verifyEmailIdentity("alice@example.com", REGION);
|
||||
service.setIdentityNotificationTopic("alice@example.com", "Bounce", OTHER_TOPIC, REGION);
|
||||
service.setFeedbackForwardingEnabled("alice@example.com", false, REGION);
|
||||
|
||||
service.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION);
|
||||
|
||||
Identity identity = service.find("alice@example.com", REGION).orElseThrow();
|
||||
assertEquals(OTHER_TOPIC, identity.getNotificationAttributes().get("BounceTopic"));
|
||||
assertFalse(identity.isFeedbackForwardingEnabled());
|
||||
}
|
||||
|
||||
static Stream<Arguments> notificationSettings() {
|
||||
return Stream.of(
|
||||
Arguments.of("a topic",
|
||||
(Consumer<SesIdentityService>) identities -> identities.setIdentityNotificationTopic(
|
||||
"alice@example.com", "Bounce", OTHER_TOPIC, REGION),
|
||||
(Predicate<Identity>) identity ->
|
||||
OTHER_TOPIC.equals(identity.getNotificationAttributes().get("BounceTopic"))),
|
||||
Arguments.of("feedback forwarding",
|
||||
(Consumer<SesIdentityService>) identities -> identities.setFeedbackForwardingEnabled(
|
||||
"alice@example.com", false, REGION),
|
||||
(Predicate<Identity>) identity -> !identity.isFeedbackForwardingEnabled()),
|
||||
Arguments.of("headers in notifications",
|
||||
(Consumer<SesIdentityService>) identities -> identities.setHeadersInNotificationsEnabled(
|
||||
"alice@example.com", "Bounce", true, REGION),
|
||||
(Predicate<Identity>) identity ->
|
||||
Boolean.TRUE.equals(identity.getHeadersInNotificationsEnabled().get("Bounce"))));
|
||||
}
|
||||
|
||||
@ParameterizedTest(name = "setting {0}")
|
||||
@MethodSource("notificationSettings")
|
||||
void aNotificationSettingWaitsWhileSesDropsARefusedTopic(String setting, Consumer<SesIdentityService> change,
|
||||
Predicate<Identity> applied) throws Exception {
|
||||
InMemoryStorage<String, Identity> store = Mockito.spy(new InMemoryStorage<String, Identity>());
|
||||
SesIdentityService parked = new SesIdentityService(store, null, Clock.systemUTC());
|
||||
parked.verifyEmailIdentity("alice@example.com", REGION);
|
||||
parked.setIdentityNotificationTopic("alice@example.com", "Bounce", TOPIC, REGION);
|
||||
CountDownLatch read = new CountDownLatch(1);
|
||||
CountDownLatch release = new CountDownLatch(1);
|
||||
// The removal parks right after reading the identity, before writing it back.
|
||||
doAnswer(invocation -> {
|
||||
Object identity = invocation.callRealMethod();
|
||||
read.countDown();
|
||||
release.await(2, TimeUnit.SECONDS);
|
||||
return identity;
|
||||
}).doCallRealMethod().when(store).get(anyString());
|
||||
|
||||
ExecutorService pool = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
Future<?> drop = pool.submit(() ->
|
||||
parked.dropRefusedNotificationTopic("alice@example.com", TOPIC, REGION));
|
||||
assertTrue(read.await(2, TimeUnit.SECONDS), "the removal must reach its read of the identity");
|
||||
AtomicReference<Thread> settingThread = new AtomicReference<>();
|
||||
Future<?> set = pool.submit(() -> {
|
||||
settingThread.set(Thread.currentThread());
|
||||
change.accept(parked);
|
||||
});
|
||||
awaitBlockedOrDone(settingThread, set);
|
||||
assertFalse(set.isDone(), "setting " + setting + " did not wait for the removal");
|
||||
|
||||
release.countDown();
|
||||
drop.get(2, TimeUnit.SECONDS);
|
||||
set.get(2, TimeUnit.SECONDS);
|
||||
} finally {
|
||||
release.countDown();
|
||||
pool.shutdownNow();
|
||||
}
|
||||
|
||||
assertTrue(applied.test(parked.find("alice@example.com", REGION).orElseThrow()),
|
||||
"setting " + setting + " was lost");
|
||||
}
|
||||
|
||||
@Test
|
||||
void tags_lifecycle_andNotFoundMessage() {
|
||||
service.verifyEmailIdentity("alice@example.com", REGION);
|
||||
|
||||
+29
-1
@@ -2,7 +2,10 @@ package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import io.github.hectorvent.floci.core.common.PaginatedResult;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaService;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.ses.model.ReceiptAction;
|
||||
@@ -42,6 +45,7 @@ class SesReceiptRuleServiceTest {
|
||||
private S3Service s3Service;
|
||||
private SnsService snsService;
|
||||
private LambdaService lambdaService;
|
||||
private ServiceCallAuthorizer serviceCallAuthorizer;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
@@ -51,8 +55,12 @@ class SesReceiptRuleServiceTest {
|
||||
when(s3Service.bucketExists(anyString())).thenReturn(true);
|
||||
when(snsService.topicExists(anyString(), anyString())).thenReturn(true);
|
||||
when(lambdaService.functionExists(anyString(), anyString())).thenReturn(true);
|
||||
serviceCallAuthorizer = mock(ServiceCallAuthorizer.class);
|
||||
when(serviceCallAuthorizer.authorize(anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(Decision.ALLOW);
|
||||
service = new SesReceiptRuleService(new InMemoryStorage<>(), new InMemoryStorage<>(),
|
||||
s3Service, snsService, lambdaService, Clock.systemUTC());
|
||||
s3Service, snsService, lambdaService, serviceCallAuthorizer,
|
||||
new RegionResolver(REGION, "000000000000"), Clock.systemUTC());
|
||||
}
|
||||
|
||||
private static ReceiptFilter filter(String name, String policy, String cidr) {
|
||||
@@ -367,6 +375,26 @@ class SesReceiptRuleServiceTest {
|
||||
service.describeReceiptRule("rules-a", "r1", REGION).getActions().get(0).property("Encoding"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicWhosePolicyRefusesSesForTheRuleIsNotPublishable() {
|
||||
service.createReceiptRuleSet("rules-a", REGION);
|
||||
String arn = "arn:aws:sns:us-east-1:000000000000:topic";
|
||||
when(serviceCallAuthorizer.authorize("ses", "sns:Publish", arn,
|
||||
"arn:aws:ses:us-east-1:000000000000:receipt-rule-set/rules-a:receipt-rule/r1", "000000000000"))
|
||||
.thenReturn(Decision.DENY);
|
||||
|
||||
AwsException create = assertThrows(AwsException.class, () -> service.createReceiptRule("rules-a",
|
||||
rule("r1", action("SNSAction", "TopicArn", arn)), null, REGION, ANY_SENDER_VERIFIED));
|
||||
service.createReceiptRule("rules-a", rule("r1"), null, REGION, ANY_SENDER_VERIFIED);
|
||||
AwsException update = assertThrows(AwsException.class, () -> service.updateReceiptRule("rules-a",
|
||||
rule("r1", action("S3Action", "BucketName", "inbox", "TopicArn", arn)), REGION, ANY_SENDER_VERIFIED));
|
||||
|
||||
for (AwsException e : List.of(create, update)) {
|
||||
assertEquals("InvalidSnsTopic", e.getErrorCode());
|
||||
assertEquals("Could not publish to SNS topic: " + arn, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateRule_replacesWholeRuleAndKeepsPosition() {
|
||||
service.createReceiptRuleSet("rules-a", REGION);
|
||||
|
||||
+385
@@ -0,0 +1,385 @@
|
||||
package io.github.hectorvent.floci.services.ses;
|
||||
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.allOf;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
|
||||
import static org.hamcrest.Matchers.lessThan;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* SES publishing to SNS under IAM enforcement: SES publishes as {@code ses.amazonaws.com}, so the
|
||||
* topic's policy decides, with the configuration set as {@code aws:SourceArn} for an event
|
||||
* destination and the identity for an identity notification. The caller's own SNS permissions play
|
||||
* no part, so a caller refused {@code sns:Publish} cannot reach a topic through SES that the topic's
|
||||
* policy does not open to SES.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class SesSnsPublishAuthorizationIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String OWNER = "131313131313";
|
||||
private static final String OTHER = "242424242424";
|
||||
private static final String BOUNCE = "bounce@simulator.amazonses.com";
|
||||
private static final String SUCCESS = "success@simulator.amazonses.com";
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI baseUri;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCallerRefusedSnsPublishCannotReachATopicThatRefusesSesThroughAConfigurationSet() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
setTopicPolicy(OWNER, topicArn, rootOnly(topicArn));
|
||||
String sender = createSender();
|
||||
String user = "ses-only-" + suffix();
|
||||
String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(),
|
||||
EnforcementFixtures.auth(OWNER, "iam"), user).accessKeyId();
|
||||
query(OWNER, "iam", "PutUserPolicy", Map.of("Version", "2010-05-08", "UserName", user,
|
||||
"PolicyName", "ses-only", "PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"ses:*","Resource":"*"}]}""")).statusCode(200);
|
||||
given()
|
||||
.header("Authorization", EnforcementFixtures.auth(accessKeyId, "sns"))
|
||||
.header("X-Amz-Target", "SNS_20100331.Publish")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("{\"TopicArn\":\"" + topicArn + "\",\"Message\":\"hello\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(allOf(greaterThanOrEqualTo(400), lessThan(500)));
|
||||
|
||||
String configurationSet = createConfigurationSet(accessKeyId, topicArn);
|
||||
sendEmail(accessKeyId, sender, SUCCESS, configurationSet);
|
||||
|
||||
assertEquals(0, receive(OWNER, queueUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventDestinationOnATopicWithTheDefaultPolicyGetsTheEvent() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
String sender = createSender();
|
||||
String configurationSet = createConfigurationSet(topicArn);
|
||||
|
||||
sendEmail(sender, SUCCESS, configurationSet);
|
||||
|
||||
assertEquals(1, receive(OWNER, queueUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventDestinationTopicGrantingSesForAnotherConfigurationSetGetsNothing() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
String sender = createSender();
|
||||
String configurationSet = createConfigurationSet(topicArn);
|
||||
setTopicPolicy(OWNER, topicArn, sesGrant(topicArn, "configuration-set/other-" + suffix()));
|
||||
|
||||
sendEmail(sender, SUCCESS, configurationSet);
|
||||
|
||||
assertEquals(0, receive(OWNER, queueUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anEventDestinationTopicGrantingSesForItsConfigurationSetGetsTheEvent() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
String sender = createSender();
|
||||
String configurationSet = createConfigurationSet(topicArn);
|
||||
setTopicPolicy(OWNER, topicArn, sesGrant(topicArn, "configuration-set/" + configurationSet));
|
||||
|
||||
sendEmail(sender, SUCCESS, configurationSet);
|
||||
|
||||
assertEquals(1, receive(OWNER, queueUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBounceTopicWithTheDefaultPolicyGetsTheNotification() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
String sender = createSender();
|
||||
setIdentityNotificationTopic(sender, "Bounce", topicArn);
|
||||
|
||||
sendEmail(sender, BOUNCE, null);
|
||||
|
||||
assertEquals(1, receive(OWNER, queueUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBounceTopicGrantingSesForTheDomainOfTheSenderGetsTheNotification() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
String domain = "authz-" + suffix() + ".floci.test";
|
||||
ses(OWNER, "VerifyDomainIdentity", Map.of("Domain", domain)).statusCode(200);
|
||||
cleanup.register(() -> ses(OWNER, "DeleteIdentity", Map.of("Identity", domain)).statusCode(200));
|
||||
String sender = "sender@" + domain;
|
||||
verifyEmailIdentity(sender);
|
||||
setIdentityNotificationTopic(domain, "Bounce", topicArn);
|
||||
setTopicPolicy(OWNER, topicArn, sesGrant(topicArn, "identity/" + domain));
|
||||
|
||||
sendEmail(sender, BOUNCE, null);
|
||||
|
||||
assertEquals(1, receive(OWNER, queueUrl));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicThatRefusesSesIsTakenOutOfTheBounceAndComplaintSettingsAndForwardingTurnsBackOn() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
String sender = createSender();
|
||||
setIdentityNotificationTopic(sender, "Bounce", topicArn);
|
||||
setIdentityNotificationTopic(sender, "Complaint", topicArn);
|
||||
setIdentityNotificationTopic(sender, "Delivery", topicArn);
|
||||
ses(OWNER, "SetIdentityFeedbackForwardingEnabled",
|
||||
Map.of("Identity", sender, "ForwardingEnabled", "false")).statusCode(200);
|
||||
setTopicPolicy(OWNER, topicArn, rootOnly(topicArn));
|
||||
|
||||
sendEmail(sender, BOUNCE, null);
|
||||
|
||||
assertEquals(0, receive(OWNER, queueUrl));
|
||||
notificationAttributes(sender)
|
||||
.body(containsString("<BounceTopic></BounceTopic>"))
|
||||
.body(containsString("<ComplaintTopic></ComplaintTopic>"))
|
||||
.body(containsString("<DeliveryTopic>" + topicArn + "</DeliveryTopic>"))
|
||||
.body(containsString("<ForwardingEnabled>true</ForwardingEnabled>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeliveryTopicThatRefusesSesStaysConfigured() {
|
||||
String queueUrl = createQueue(OWNER);
|
||||
String topicArn = createSubscribedTopic(OWNER, queueUrl);
|
||||
String sender = createSender();
|
||||
setIdentityNotificationTopic(sender, "Delivery", topicArn);
|
||||
setTopicPolicy(OWNER, topicArn, rootOnly(topicArn));
|
||||
|
||||
sendEmail(sender, SUCCESS, null);
|
||||
|
||||
assertEquals(0, receive(OWNER, queueUrl));
|
||||
notificationAttributes(sender)
|
||||
.body(containsString("<DeliveryTopic>" + topicArn + "</DeliveryTopic>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherAccountsTopicWithoutAnSesGrantRefusesTheNotification() {
|
||||
String topicArn = createTopic(OTHER, "foreign-" + suffix());
|
||||
String sender = createSender();
|
||||
setIdentityNotificationTopic(sender, "Bounce", topicArn);
|
||||
|
||||
sendEmail(sender, BOUNCE, null);
|
||||
|
||||
notificationAttributes(sender).body(containsString("<BounceTopic></BounceTopic>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anotherAccountsTopicThatGrantsSesKeepsItsSettingThoughFlociCannotDeliverThere() {
|
||||
String sender = createSender();
|
||||
String topicArn = createTopic(OTHER, "foreign-granted-" + suffix());
|
||||
setTopicPolicy(OTHER, topicArn, sesGrant(topicArn, "identity/" + sender));
|
||||
setIdentityNotificationTopic(sender, "Bounce", topicArn);
|
||||
|
||||
sendEmail(sender, BOUNCE, null);
|
||||
|
||||
notificationAttributes(sender).body(containsString("<BounceTopic>" + topicArn + "</BounceTopic>"));
|
||||
}
|
||||
|
||||
/**
|
||||
* CreateReceiptRule answers InvalidSnsTopic when "Amazon SES could not publish to the topic,
|
||||
* possibly due to permissions issues" (SES API Reference).
|
||||
*/
|
||||
@Test
|
||||
void aReceiptRuleCannotNameATopicThatRefusesSes() {
|
||||
String ruleSet = "authz-" + suffix();
|
||||
ses(OWNER, "CreateReceiptRuleSet", Map.of("RuleSetName", ruleSet)).statusCode(200);
|
||||
cleanup.register(() -> ses(OWNER, "DeleteReceiptRuleSet", Map.of("RuleSetName", ruleSet)).statusCode(200));
|
||||
String open = createTopic(OWNER, "rule-open-" + suffix());
|
||||
String closed = createTopic(OWNER, "rule-closed-" + suffix());
|
||||
setTopicPolicy(OWNER, closed, rootOnly(closed));
|
||||
String foreign = createTopic(OTHER, "rule-foreign-" + suffix());
|
||||
|
||||
receiptRule(ruleSet, "to-open", open).statusCode(200);
|
||||
for (String topicArn : List.of(closed, foreign)) {
|
||||
receiptRule(ruleSet, "to-" + suffix(), topicArn)
|
||||
.statusCode(400)
|
||||
.body(containsString("<Code>InvalidSnsTopic</Code>"))
|
||||
.body(containsString("Could not publish to SNS topic: " + topicArn));
|
||||
}
|
||||
}
|
||||
|
||||
private static ValidatableResponse receiptRule(String ruleSet, String name, String topicArn) {
|
||||
return ses(OWNER, "CreateReceiptRule", Map.of("RuleSetName", ruleSet, "Rule.Name", name,
|
||||
"Rule.Actions.member.1.SNSAction.TopicArn", topicArn));
|
||||
}
|
||||
|
||||
/** The SES Developer Guide's topic policy, granting SES for one resource of the owner's account. */
|
||||
private static String sesGrant(String topicArn, String sesResource) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Id":"notification-policy","Statement":[{
|
||||
"Effect":"Allow","Principal":{"Service":"ses.amazonaws.com"},"Action":"sns:Publish",
|
||||
"Resource":"%s",
|
||||
"Condition":{"StringEquals":{"AWS:SourceAccount":"%s","AWS:SourceArn":"arn:aws:ses:%s:%s:%s"}}}]}"""
|
||||
.formatted(topicArn, OWNER, REGION, OWNER, sesResource);
|
||||
}
|
||||
|
||||
/** A topic policy that lets only the owner's account publish, replacing the default. */
|
||||
private static String rootOnly(String topicArn) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sns:Publish",
|
||||
"Resource":"%s"}]}""".formatted(OWNER, topicArn);
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private String createSender() {
|
||||
String sender = "sender-" + suffix() + "@floci.test";
|
||||
verifyEmailIdentity(sender);
|
||||
return sender;
|
||||
}
|
||||
|
||||
private void verifyEmailIdentity(String email) {
|
||||
ses(OWNER, "VerifyEmailIdentity", Map.of("EmailAddress", email)).statusCode(200);
|
||||
cleanup.register(() -> ses(OWNER, "DeleteIdentity", Map.of("Identity", email)).statusCode(200));
|
||||
}
|
||||
|
||||
private String createConfigurationSet(String topicArn) {
|
||||
return createConfigurationSet(OWNER, topicArn);
|
||||
}
|
||||
|
||||
/** A configuration set whose one event destination sends its send events to {@code topicArn}. */
|
||||
private String createConfigurationSet(String accessKeyId, String topicArn) {
|
||||
String name = "authz-" + suffix();
|
||||
ses(accessKeyId, "CreateConfigurationSet", Map.of("ConfigurationSet.Name", name)).statusCode(200);
|
||||
cleanup.register(() -> ses(OWNER, "DeleteConfigurationSet", Map.of("ConfigurationSetName", name))
|
||||
.statusCode(200));
|
||||
ses(accessKeyId, "CreateConfigurationSetEventDestination", Map.of(
|
||||
"ConfigurationSetName", name,
|
||||
"EventDestination.Name", "to-sns",
|
||||
"EventDestination.Enabled", "true",
|
||||
"EventDestination.MatchingEventTypes.member.1", "send",
|
||||
"EventDestination.SNSDestination.TopicARN", topicArn)).statusCode(200);
|
||||
return name;
|
||||
}
|
||||
|
||||
private static void setIdentityNotificationTopic(String identity, String type, String topicArn) {
|
||||
ses(OWNER, "SetIdentityNotificationTopic",
|
||||
Map.of("Identity", identity, "NotificationType", type, "SnsTopic", topicArn)).statusCode(200);
|
||||
}
|
||||
|
||||
private static ValidatableResponse notificationAttributes(String identity) {
|
||||
return ses(OWNER, "GetIdentityNotificationAttributes", Map.of("Identities.member.1", identity))
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
private static void sendEmail(String sender, String recipient, String configurationSet) {
|
||||
sendEmail(OWNER, sender, recipient, configurationSet);
|
||||
}
|
||||
|
||||
private static void sendEmail(String accessKeyId, String sender, String recipient, String configurationSet) {
|
||||
RequestSpecification spec = given()
|
||||
.header("Authorization", EnforcementFixtures.auth(accessKeyId, "ses"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "SendEmail")
|
||||
.formParam("Source", sender)
|
||||
.formParam("Destination.ToAddresses.member.1", recipient)
|
||||
.formParam("Message.Subject.Data", "hello")
|
||||
.formParam("Message.Body.Text.Data", "hello");
|
||||
if (configurationSet != null) {
|
||||
spec.formParam("ConfigurationSetName", configurationSet);
|
||||
}
|
||||
spec.when().post("/").then().statusCode(200);
|
||||
}
|
||||
|
||||
private String createTopic(String account, String name) {
|
||||
return EnforcementFixtures.createTopic(cleanup, baseUri.getPort(), EnforcementFixtures.auth(account, "sns"), name);
|
||||
}
|
||||
|
||||
private String createSubscribedTopic(String account, String queueUrl) {
|
||||
String topicArn = createTopic(account, "ses-authz-" + suffix());
|
||||
String queueArn = sqs(account, "GetQueueAttributes",
|
||||
"{\"QueueUrl\":\"" + queueUrl + "\",\"AttributeNames\":[\"QueueArn\"]}")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("Attributes.QueueArn");
|
||||
sns(account, "Subscribe", Map.of("TopicArn", topicArn, "Protocol", "sqs", "Endpoint", queueArn))
|
||||
.statusCode(200);
|
||||
return topicArn;
|
||||
}
|
||||
|
||||
private void setTopicPolicy(String account, String topicArn, String policy) {
|
||||
EnforcementFixtures.setTopicPolicy(baseUri.getPort(), EnforcementFixtures.auth(account, "sns"), topicArn, policy);
|
||||
}
|
||||
|
||||
private String createQueue(String account) {
|
||||
String queueUrl = sqs(account, "CreateQueue", "{\"QueueName\":\"ses-authz-" + suffix() + "\"}")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getString("QueueUrl");
|
||||
cleanup.register(() -> sqs(account, "DeleteQueue", "{\"QueueUrl\":\"" + queueUrl + "\"}").statusCode(200));
|
||||
return queueUrl;
|
||||
}
|
||||
|
||||
/** How many messages the queue holds; SNS delivers to SQS before the publish returns. */
|
||||
private static int receive(String account, String queueUrl) {
|
||||
List<Object> messages = sqs(account, "ReceiveMessage",
|
||||
"{\"QueueUrl\":\"" + queueUrl + "\",\"MaxNumberOfMessages\":10,\"WaitTimeSeconds\":0}")
|
||||
.statusCode(200)
|
||||
.extract().jsonPath().getList("Messages");
|
||||
return messages == null ? 0 : messages.size();
|
||||
}
|
||||
|
||||
private static ValidatableResponse ses(String account, String action, Map<String, String> params) {
|
||||
return query(account, "ses", action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse sns(String account, String action, Map<String, String> params) {
|
||||
return query(account, "sns", action, params);
|
||||
}
|
||||
|
||||
private static ValidatableResponse query(String account, String service, String action,
|
||||
Map<String, String> params) {
|
||||
RequestSpecification spec = given()
|
||||
.header("Authorization", EnforcementFixtures.auth(account, service))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", action);
|
||||
params.forEach(spec::formParam);
|
||||
return spec.when().post("/").then();
|
||||
}
|
||||
|
||||
private static ValidatableResponse sqs(String account, String action, String body) {
|
||||
return given()
|
||||
.header("Authorization", EnforcementFixtures.auth(account, "sqs"))
|
||||
.header("X-Amz-Target", "AmazonSQS." + action)
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body(body)
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package io.github.hectorvent.floci.services.sns;
|
||||
|
||||
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider.ResourcePolicy;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class SnsResourcePolicyProviderTest {
|
||||
|
||||
private static final String OWNER = "111122223333";
|
||||
private static final String TOPIC = "arn:aws:sns:us-east-1:" + OWNER + ":events";
|
||||
private static final String POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[]}";
|
||||
|
||||
private SnsService snsService;
|
||||
private SnsResourcePolicyProvider provider;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
snsService = mock(SnsService.class);
|
||||
when(snsService.findTopicPolicy(anyString())).thenReturn(Optional.empty());
|
||||
provider = new SnsResourcePolicyProvider(snsService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicComesWithItsPolicyAndTheAccountInItsArn() {
|
||||
when(snsService.findTopicPolicy(TOPIC)).thenReturn(Optional.of(POLICY));
|
||||
|
||||
assertEquals(List.of(new ResourcePolicy(POLICY, OWNER)), provider.getResourcePolicies("sns", TOPIC));
|
||||
assertEquals(List.of(new ResourcePolicy(POLICY, OWNER)), provider.getResourcePolicies("ses", TOPIC));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicThatDoesNotExistStillHasItsOwner() {
|
||||
assertEquals(List.of(new ResourcePolicy(null, OWNER)), provider.getResourcePolicies("sns", TOPIC));
|
||||
assertEquals(List.of(new ResourcePolicy(null, OWNER)),
|
||||
provider.getResourcePolicies("sns", TOPIC + ".fifo"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anythingThatIsNotATopicIsLeftToOtherProviders() {
|
||||
assertTrue(provider.getResourcePolicies("sns", "*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sns", "arn:aws:sns:us-east-1:" + OWNER + ":*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sns",
|
||||
TOPIC + ":6f1b3c2e-0d5a-4b8e-9c71-2a4d8e9f0b13").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sns",
|
||||
"arn:aws:sns:us-east-1:" + OWNER + ":app/GCM/my-app").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sqs", "arn:aws:sqs:us-east-1:" + OWNER + ":queue").isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
@@ -836,6 +837,38 @@ class SnsServiceTest {
|
||||
assertTrue(raw.get("000000000002/" + key).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void findTopicPolicy_readsTheTopicInTheAccountItsArnNames() {
|
||||
String arn = "arn:aws:sns:us-east-1:000000000002:owned-elsewhere";
|
||||
Topic topic = new Topic("owned-elsewhere", arn);
|
||||
topic.getAttributes().put("Policy", "{\"Version\":\"2012-10-17\",\"Statement\":[]}");
|
||||
AccountAwareStorageBackend<Topic> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
store.putForAccount("000000000002", "topic::" + REGION + "::" + arn, topic);
|
||||
SnsService service = new SnsService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT), null, null);
|
||||
|
||||
assertEquals(Optional.of("{\"Version\":\"2012-10-17\",\"Statement\":[]}"), service.findTopicPolicy(arn));
|
||||
}
|
||||
|
||||
@Test
|
||||
void findTopicPolicy_givesATopicWithoutOneTheDefaultForItsOwnAccount() {
|
||||
String arn = "arn:aws:sns:us-east-1:000000000002:no-policy";
|
||||
AccountAwareStorageBackend<Topic> store = AccountAwareStorageBackend.inMemory(ACCOUNT);
|
||||
store.putForAccount("000000000002", "topic::" + REGION + "::" + arn, new Topic("no-policy", arn));
|
||||
SnsService service = new SnsService(store, new InMemoryStorage<>(),
|
||||
new RegionResolver(REGION, ACCOUNT), null, null);
|
||||
|
||||
String policy = service.findTopicPolicy(arn).orElseThrow();
|
||||
|
||||
assertTrue(policy.contains("\"AWS:SourceOwner\":\"000000000002\""), policy);
|
||||
assertTrue(policy.contains("\"Resource\":\"" + arn + "\""), policy);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findTopicPolicy_isEmptyForATopicThatDoesNotExist() {
|
||||
assertEquals(Optional.empty(), snsService.findTopicPolicy("arn:aws:sns:us-east-1:000000000000:ghost-topic"));
|
||||
}
|
||||
|
||||
private static Map<String, MessageAttributeValue> attr(String name, String value, String dataType) {
|
||||
return Map.of(name, new MessageAttributeValue(value, dataType));
|
||||
}
|
||||
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
package io.github.hectorvent.floci.services.sns;
|
||||
|
||||
import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
|
||||
import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
|
||||
import io.github.hectorvent.floci.testing.EnforcementFixtures;
|
||||
import io.github.hectorvent.floci.testing.IamEnforcementProfile;
|
||||
import io.github.hectorvent.floci.testing.PartitionCleanup;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.quarkus.test.junit.TestProfile;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.allOf;
|
||||
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
|
||||
import static org.hamcrest.Matchers.lessThan;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
/**
|
||||
* SNS topic policies under IAM enforcement: they decide the calls AWS services make to a topic,
|
||||
* through {@link ServiceCallAuthorizer}, and take part in IAM callers' requests the way any resource
|
||||
* policy does.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class SnsTopicPolicyEnforcementIntegrationTest {
|
||||
|
||||
private static final String REGION = "us-east-1";
|
||||
private static final String OWNER = "121212121212";
|
||||
private static final String OTHER = "343434343434";
|
||||
|
||||
@Inject
|
||||
ServiceCallAuthorizer authorizer;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@TestHTTPResource("/")
|
||||
URI baseUri;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultTopicPolicyAdmitsAServiceActingForTheOwnersAccount() {
|
||||
String topicArn = createTopic(OWNER, "default-" + suffix());
|
||||
|
||||
assertEquals(Decision.ALLOW, sesPublish(topicArn, configurationSet(OWNER, "my-set"), OWNER));
|
||||
assertEquals(Decision.DENY, sesPublish(topicArn, configurationSet(OTHER, "my-set"), OTHER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicPolicyGrantingSesAdmitsTheConfigurationSetItNames() {
|
||||
String topicArn = createTopic(OWNER, "granted-" + suffix());
|
||||
setTopicPolicy(OWNER, topicArn, """
|
||||
{"Version":"2012-10-17","Id":"notification-policy","Statement":[{
|
||||
"Effect":"Allow","Principal":{"Service":"ses.amazonaws.com"},"Action":"sns:Publish",
|
||||
"Resource":"%s",
|
||||
"Condition":{"StringEquals":{"AWS:SourceAccount":"%s","AWS:SourceArn":"%s"}}}]}"""
|
||||
.formatted(topicArn, OWNER, configurationSet(OWNER, "my-set")));
|
||||
|
||||
assertEquals(Decision.ALLOW, sesPublish(topicArn, configurationSet(OWNER, "my-set"), OWNER));
|
||||
assertEquals(Decision.DENY, sesPublish(topicArn, configurationSet(OWNER, "other-set"), OWNER));
|
||||
assertEquals(Decision.DENY, sesPublish(topicArn, configurationSet(OTHER, "my-set"), OTHER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicWhosePolicyNoLongerAdmitsSesRefusesIt() {
|
||||
String topicArn = createTopic(OWNER, "replaced-" + suffix());
|
||||
setTopicPolicy(OWNER, topicArn, """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sns:Publish",
|
||||
"Resource":"%s"}]}""".formatted(OWNER, topicArn));
|
||||
|
||||
assertEquals(Decision.DENY, sesPublish(topicArn, configurationSet(OWNER, "my-set"), OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTopicThatDoesNotExistRefusesEveryService() {
|
||||
String topicArn = "arn:aws:sns:" + REGION + ":" + OWNER + ":missing-" + suffix();
|
||||
|
||||
assertEquals(Decision.DENY, sesPublish(topicArn, configurationSet(OWNER, "my-set"), OWNER));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPublishToAnotherAccountsTopicNeedsItsTopicPolicy() {
|
||||
String topicArn = createTopic(OWNER, "foreign-" + suffix());
|
||||
String publisher = createUser(OTHER, "publisher-" + suffix(), """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"sns:Publish","Resource":"*"}]}""");
|
||||
|
||||
publish(publisher, topicArn)
|
||||
.statusCode(allOf(greaterThanOrEqualTo(400), lessThan(500)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSameAccountTopicPolicyGrantsOnItsOwn() {
|
||||
String topicArn = createTopic(OWNER, "own-grant-" + suffix());
|
||||
String userName = "granted-" + suffix();
|
||||
String publisher = createUser(OWNER, userName, """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"s3:ListAllMyBuckets","Resource":"*"}]}""");
|
||||
setTopicPolicy(OWNER, topicArn, """
|
||||
{"Version":"2012-10-17","Statement":[{
|
||||
"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%s:user/%s"},"Action":"sns:Publish",
|
||||
"Resource":"%s"}]}""".formatted(OWNER, userName, topicArn));
|
||||
|
||||
publish(publisher, topicArn).statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* IAM User Guide, "AWS JSON policy elements: NotPrincipal": a Deny's NotPrincipal naming a user
|
||||
* without its account "might deny access to the entire account", and it "will always deny any IAM
|
||||
* principal that has a permissions boundary policy attached".
|
||||
*/
|
||||
@Test
|
||||
void aDenysNotPrincipalSparesAUserNamedWithItsAccountAndNoBoundary() {
|
||||
String topicArn = createTopic(OWNER, "not-principal-" + suffix());
|
||||
String userName = "spared-" + suffix();
|
||||
String publisher = createUser(OWNER, userName, """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"sns:Publish","Resource":"*"}]}""");
|
||||
String userArn = "arn:aws:iam::" + OWNER + ":user/" + userName;
|
||||
|
||||
setTopicPolicy(OWNER, topicArn, denyAllBut(topicArn, userArn));
|
||||
publish(publisher, topicArn).statusCode(allOf(greaterThanOrEqualTo(400), lessThan(500)));
|
||||
|
||||
setTopicPolicy(OWNER, topicArn, denyAllBut(topicArn, userArn, "arn:aws:iam::" + OWNER + ":root"));
|
||||
publish(publisher, topicArn).statusCode(200);
|
||||
|
||||
String boundaryArn = "arn:aws:iam::" + OWNER + ":policy/boundary-" + suffix();
|
||||
cleanup.register(() -> EnforcementFixtures.removePolicy(baseUri.getPort(),
|
||||
EnforcementFixtures.auth(OWNER, "iam"), boundaryArn));
|
||||
iam(OWNER, "CreatePolicy", Map.of("PolicyName", boundaryArn.substring(boundaryArn.lastIndexOf('/') + 1),
|
||||
"PolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"sns:*","Resource":"*"}]}"""));
|
||||
iam(OWNER, "PutUserPermissionsBoundary", Map.of("UserName", userName, "PermissionsBoundary", boundaryArn));
|
||||
publish(publisher, topicArn).statusCode(allOf(greaterThanOrEqualTo(400), lessThan(500)));
|
||||
}
|
||||
|
||||
private static String denyAllBut(String topicArn, String... spared) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sns:Publish","Resource":"%1$s"},
|
||||
{"Effect":"Deny","NotPrincipal":{"AWS":["%2$s"]},"Action":"sns:Publish","Resource":"%1$s"}]}"""
|
||||
.formatted(topicArn, String.join("\",\"", spared));
|
||||
}
|
||||
|
||||
private Decision sesPublish(String topicArn, String sourceArn, String sourceAccount) {
|
||||
return authorizer.authorize("ses", "sns:Publish", topicArn, sourceArn, sourceAccount);
|
||||
}
|
||||
|
||||
private static String configurationSet(String account, String name) {
|
||||
return "arn:aws:ses:" + REGION + ":" + account + ":configuration-set/" + name;
|
||||
}
|
||||
|
||||
private String createTopic(String account, String name) {
|
||||
return EnforcementFixtures.createTopic(cleanup, baseUri.getPort(), EnforcementFixtures.auth(account, "sns"), name);
|
||||
}
|
||||
|
||||
private void setTopicPolicy(String account, String topicArn, String policy) {
|
||||
EnforcementFixtures.setTopicPolicy(baseUri.getPort(), EnforcementFixtures.auth(account, "sns"), topicArn, policy);
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes through SNS's JSON protocol, whose body the request filter reads the topic from. A
|
||||
* Query-protocol request carries the topic in its form body, which the filter does not read yet.
|
||||
*/
|
||||
private static ValidatableResponse publish(String accessKeyId, String topicArn) {
|
||||
return given()
|
||||
.header("Authorization", EnforcementFixtures.auth(accessKeyId, "sns"))
|
||||
.header("X-Amz-Target", "SNS_20100331.Publish")
|
||||
.contentType("application/x-amz-json-1.0")
|
||||
.body("{\"TopicArn\":\"" + topicArn + "\",\"Message\":\"hello\"}")
|
||||
.when()
|
||||
.post("/")
|
||||
.then();
|
||||
}
|
||||
|
||||
/** An IAM user of {@code account} holding {@code policyDocument} inline; returns its access key ID. */
|
||||
private String createUser(String account, String userName, String policyDocument) {
|
||||
String accessKeyId = EnforcementFixtures.createUser(cleanup, baseUri.getPort(),
|
||||
EnforcementFixtures.auth(account, "iam"), userName).accessKeyId();
|
||||
iam(account, "PutUserPolicy", Map.of("UserName", userName, "PolicyName", "inline",
|
||||
"PolicyDocument", policyDocument));
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
private static void iam(String account, String action, Map<String, String> params) {
|
||||
RequestSpecification spec = given()
|
||||
.header("Authorization", EnforcementFixtures.auth(account, "iam"))
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", action)
|
||||
.formParam("Version", "2010-05-08");
|
||||
params.forEach(spec::formParam);
|
||||
spec.when().post("/").then().statusCode(200);
|
||||
}
|
||||
}
|
||||
+9
@@ -99,6 +99,15 @@ class LambdaTaskAuthorizerTest {
|
||||
authorizer.refusal(ROLE, FUNCTION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aGrantToTheRolesAccountIsTheFunctionsHalfOnlySoTheRoleNeedsItsOwnPermission() {
|
||||
roleWithPolicies(READ_OBJECTS);
|
||||
functionPolicy(FUNCTION, FUNCTION_ACCOUNT, grant("{\"AWS\":\"arn:aws:iam::" + SFN_ACCOUNT + ":root\"}", FUNCTION));
|
||||
|
||||
assertEquals(denied(FUNCTION, "because no identity-based policy allows the lambda:InvokeFunction action"),
|
||||
authorizer.refusal(ROLE, FUNCTION));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDenyInTheRolesPolicyRefusesAGrantedFunction() {
|
||||
roleWithPolicies(INVOKE_ANYTHING, """
|
||||
|
||||
@@ -13,8 +13,8 @@ import static io.restassured.RestAssured.given;
|
||||
|
||||
/**
|
||||
* Takes an IAM user or an S3 bucket that a test created back out of the shared application, and
|
||||
* makes the users an enforcement test signs as ({@link #createUser}, {@link #auth}), registering
|
||||
* each one's removal as it goes. A {@code @QuarkusTest} shares one application with every other
|
||||
* makes the users an enforcement test signs as ({@link #createUser}, {@link #auth}) and the SNS
|
||||
* topics it publishes to ({@link #createTopic}), registering each one's removal as it goes. A {@code @QuarkusTest} shares one application with every other
|
||||
* test class, so a fixture left behind outlives the class that made it and is visible to the next
|
||||
* class that lists users or buckets unscoped. Registered with {@link PartitionCleanup} as each
|
||||
* fixture is made.
|
||||
@@ -253,6 +253,29 @@ public final class EnforcementFixtures {
|
||||
s3(port, authorization).when().delete("/" + bucket).then().statusCode(204);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SNS topic in the account {@code authorization} signs for, registering its deletion
|
||||
* with {@code cleanup} as soon as it exists, and returns its ARN.
|
||||
*
|
||||
* @param authorization an SNS-scoped header for the account the topic belongs to
|
||||
*/
|
||||
public static String createTopic(PartitionCleanup cleanup, int port, String authorization, String name) {
|
||||
String topicArn = query(port, authorization, "CreateTopic", "Name", name)
|
||||
.statusCode(200).extract().path("CreateTopicResponse.CreateTopicResult.TopicArn");
|
||||
cleanup.register(() -> query(port, authorization, "DeleteTopic", "TopicArn", topicArn).statusCode(200));
|
||||
return topicArn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces a topic's access policy.
|
||||
*
|
||||
* @param authorization an SNS-scoped header for the topic's owner
|
||||
*/
|
||||
public static void setTopicPolicy(int port, String authorization, String topicArn, String policy) {
|
||||
query(port, authorization, "SetTopicAttributes", "TopicArn", topicArn,
|
||||
"AttributeName", "Policy", "AttributeValue", policy).statusCode(200);
|
||||
}
|
||||
|
||||
private static void addVersions(List<ObjectVersion> page, XmlPath listing, String element) {
|
||||
List<String> keys = listing.getList("ListVersionsResult." + element + ".Key", String.class);
|
||||
List<String> versionIds = listing.getList("ListVersionsResult." + element + ".VersionId", String.class);
|
||||
@@ -266,6 +289,12 @@ public final class EnforcementFixtures {
|
||||
|
||||
private static ValidatableResponse iam(int port, String authorization, String action,
|
||||
String... params) {
|
||||
return query(port, authorization, action, params);
|
||||
}
|
||||
|
||||
/** A Query-protocol request: the action and its parameters as form fields. */
|
||||
private static ValidatableResponse query(int port, String authorization, String action,
|
||||
String... params) {
|
||||
RequestSpecification request = given().port(port)
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", authorization)
|
||||
|
||||
Reference in new issue
Block a user