Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ses): publish to an SNS topic only when its policy allows SES (#5650)

Priamo Germosen46f4977b23df
diff --git a/docs/services/iam.md b/docs/services/iam.md
index d05311bac1..3aa607808e 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -1131,9 +1131,13 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active, Floci also queries regi
- Resource policy statements are matched against the caller (`Principal` and `NotPrincipal` clauses), each principal type naming only its own kind of caller, as on AWS: `"*"` matches anyone; `{"AWS": "*"}` matches IAM identities and AWS services; any other `AWS` entry (a user, role, account id or account root) matches IAM identities only, and a role session matches a `Principal` naming its role through the role's own ARN, path included; `{"Service": "<name>"}` matches that service exactly. `{"CanonicalUser": "<id>"}`, which S3 bucket policies accept, names an account by its S3 canonical user ID and matches that account's IAM identities, as an account principal does; Floci's canonical ID for an account is the account id, as its S3 ACLs report it. `{"Service": "*"}`, which AWS does not accept, matches nothing, and `Federated` entries never match an IAM caller.
- An explicit **Deny** in a resource policy overrides any allows.
+- A Deny statement's `NotPrincipal` spares an IAM caller only when it names the caller's account as well as the caller itself, the user, role or role session (the account alone for the account root), and never spares a caller that has a permissions boundary attached, as the IAM User Guide's "AWS JSON policy elements: NotPrincipal" describes: without the account, AWS "might deny access to the entire account", and with a boundary it "will always deny". An Allow with `NotPrincipal`, which Access Analyzer warns can grant to anonymous callers, grants everyone it does not name.
- In cross-account scenarios or resource-controlled access, an explicit **Allow** in a resource policy grants access to the principal.
+- A statement that names the caller only through its account, by its id, its root ARN or its S3 canonical user ID, delegates to the account, as the IAM User Guide's "AWS account principals" describes: across accounts it is the resource owner's half of the grant, and within the account it grants nothing on its own, so the caller's identity policies have to allow the request. A statement naming the user, role or role session itself, or `"*"`, grants on its own within the account.
- For detailed S3 bucket policy behavior and configuration, see [S3 Bucket Policy Enforcement](s3.md#bucket-policy-enforcement).
- Lambda function policies, the statements `AddPermission` adds, take part the same way. An invoke of another account's function by ARN runs it in that account, so its function policy has to allow the caller as well; see [Function policies under IAM enforcement](lambda.md#function-policies-under-iam-enforcement).
+- SNS topic policies take part the same way for a request that names the topic in a JSON-protocol body; a topic with no policy set has the default one AWS gives a new topic. See [SNS](sns.md).
+- A call an AWS service makes to another service's resource on its own behalf, such as SES publishing an event or a notification to an SNS topic, has no IAM principal, so the target's resource policy decides it alone and has to allow the calling service, through `{"Service": "<service>.amazonaws.com"}` or `{"AWS": "*"}`. A target with no policy refuses it. Its request context holds `aws:PrincipalIsAWSService` (`true`), `aws:PrincipalServiceName` and `aws:PrincipalServiceNamesList`, `aws:SourceArn` and `aws:SourceAccount` for the resource whose configuration triggered the call, `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`, the key the SNS Developer Guide lists SES among the services setting, which is what the default topic policy checks, so that policy admits SES acting for the topic owner's account and no other. SES is the one service checked this way so far; see [SES IAM enforcement](ses.md#iam-enforcement).
### Service control policies (SCPs)
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index bf8c34e735..067be5c98b 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -93,7 +93,9 @@ part in authorizing calls to the function:
- Other operations act on the caller's own function of the name the ARN gives, whatever account
the ARN names, and are authorized against that function. Floci does not serve them on another
account's function, which AWS allows through a function policy.
-- Within one account, a statement naming the caller grants on its own.
+- Within one account, a statement naming the caller grants on its own. One naming only the
+ account, as `AddPermission --principal <account-id>` writes it, delegates to the account, so the
+ caller's identity policy has to allow the call too.
- An invoke is authorized against the version or alias it names, in the function name or in
`Qualifier`. A grant added with `Qualifier` covers that version or alias only, and a grant on the
function does not cover a qualified invoke. Other operations are authorized against the
diff --git a/docs/services/s3.md b/docs/services/s3.md
index e009d7487c..cf5169ba45 100644
--- a/docs/services/s3.md
+++ b/docs/services/s3.md
@@ -309,7 +309,7 @@ Bucket policy statements can specify principals using `Principal` or `NotPrincip
- **AWS Account:** `{"AWS": "<12-digit-account-id>"}` or `{"AWS": "arn:aws:iam::<account>:root"}` matches any principal belonging to the specified account.
- **Canonical user:** `{"CanonicalUser": "<canonical-id>"}` names an account by its S3 canonical user ID and matches any principal belonging to that account, as an account principal does. Floci's canonical ID for an account is its account id, the owner ID `GetBucketAcl` and `GetObjectAcl` report.
- **Service Principal:** `{"Service": "<service>.amazonaws.com"}`.
-- **NotPrincipal:** Inverts matching so the statement applies to any principal not matching the specified patterns.
+- **NotPrincipal:** Inverts matching so the statement applies to any principal not matching the specified patterns. On a `Deny`, an IAM caller is spared only when the list names its account as well as the caller, and never when it has a permissions boundary attached; see [Resource-based policies](iam.md#resource-based-policies).
The same matching applies to every check S3 makes against a bucket policy, including the source of `CopyObject` and `UploadPartCopy`.
@@ -322,7 +322,7 @@ The same matching applies to every check S3 makes against a bucket policy, inclu
5. Unsigned (anonymous) requests and ACL-based public access fall back to standard S3 ACL and anonymous authorization paths.
6. Unknown access key IDs return HTTP 403 with `InvalidAccessKeyId`.
-With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` also on, the bucket policy and the caller's identity policies are combined the way AWS combines them. For same-account access, an explicit `Allow` in either policy grants the request, so a principal that only the bucket policy names needs no identity policy at all. For cross-account access, both the bucket policy and the caller's identity policy must allow the action. An explicit `Deny` in either policy denies the request in both cases.
+With `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` also on, the bucket policy and the caller's identity policies are combined the way AWS combines them. For same-account access, an explicit `Allow` in either policy grants the request, so a principal that only the bucket policy names, by its user, role or session ARN or as `"*"`, needs no identity policy at all. A statement that names only the account, by its id, its root ARN or its canonical user ID, delegates to the account, as on AWS, so within that account the caller's identity policy has to allow the request. For cross-account access, both the bucket policy and the caller's identity policy must allow the action. An explicit `Deny` in either policy denies the request in both cases.
### Wire Response Shape
diff --git a/docs/services/ses.md b/docs/services/ses.md
index 4710dc79c6..a82c59e496 100644
--- a/docs/services/ses.md
+++ b/docs/services/ses.md
@@ -511,3 +511,23 @@ does not grant them yet. The other actions the service reference lists for some
checked: `ses:TagResource` for the create operations, and `iam:PassRole` (with `iam:PassedToService`
`ses.amazonaws.com`) for creating or updating an event destination. A v2 `SendEmail` is authorized as
`ses:SendEmail` whatever its content: `ses:SendRawEmail` is a v1 action.
+
+SES publishes to an SNS topic as `ses.amazonaws.com`, so the topic's policy decides whether it may,
+whatever the sender's own SNS permissions: an event destination's events with the configuration set's
+ARN as `aws:SourceArn`, and an identity's bounce, complaint and delivery notifications with the ARN of
+the identity that names the topic, the sender's own or its domain's. Both carry the sending account as
+`aws:SourceAccount` and `aws:SourceOwner`. The default policy of a topic in the sending account admits
+SES; a topic whose policy was replaced, or a topic in another account, needs a statement for SES like
+the one in the [SES Developer Guide](https://docs.aws.amazon.com/ses/latest/dg/event-publishing-add-event-destination-sns.html).
+Floci checks the topic when SES publishes, not when an event destination is created or a notification
+topic is set. A refused event is not delivered. When a notification cannot be published because the
+topic is gone or its policy refuses SES, Floci does what SES does: it takes the topic out of the
+identity's bounce and complaint settings that name it and turns email feedback forwarding back on,
+while a delivery setting stays. A topic that is gone counts with enforcement off too. SES also emails the account about
+the change, which Floci does not. Floci delivers only to topics in the sending account, so a
+notification another account's topic allows is not delivered either.
+
+`CreateReceiptRule` and `UpdateReceiptRule` check the same way: an action whose `TopicArn` names a
+topic whose policy does not let SES publish for that rule is refused with `InvalidSnsTopic`, as a
+topic that does not exist is, the rule's ARN being the `aws:SourceArn`. The rules still route no
+mail.
diff --git a/docs/services/sns.md b/docs/services/sns.md
index 9e6eba1858..5e20a2623c 100644
--- a/docs/services/sns.md
+++ b/docs/services/sns.md
@@ -55,8 +55,12 @@ reports or CloudWatch delivery logs.
`AddPermission` and `RemovePermission` edit the topic's `Policy` attribute the way AWS does: the
label becomes the statement's `Sid` and each account becomes its `root` principal. A topic with no
-policy set starts from the default one AWS gives a new topic. Floci stores the policy and returns
-it from `GetTopicAttributes`, but does not evaluate topic policies when authorizing requests.
+policy set starts from the default one AWS gives a new topic, and `GetTopicAttributes` returns it.
+Under IAM enforcement the topic policy decides what AWS services may publish to the topic, such as
+[SES's event destinations and notifications](ses.md#iam-enforcement), and takes part in an IAM
+caller's request the way any [resource-based policy](iam.md#resource-based-policies) does when the
+request names the topic in a JSON-protocol body. A Query-protocol request carries the topic in its
+form body, which enforcement does not read yet, so the topic policy plays no part in it.
## SMS sandbox and opt-out
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java
index 30e40934c2..cbdcdd4d9e 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamConditionContextResolver.java
@@ -56,6 +56,13 @@ public class IamConditionContextResolver {
private static final String BUFFERED_FORM_BODY = "floci.bufferedFormBody";
private static final String REQUEST_TAG_PREFIX = "aws:RequestTag/";
private static final String RESOURCE_TAG_PREFIX = "aws:ResourceTag/";
+ /**
+ * The services that set {@code aws:SourceOwner} when they publish to an SNS topic, a deprecated key
+ * SNS keeps for the integrations that had it (SNS Developer Guide, "aws:SourceAccount versus
+ * aws:SourceOwner"). The guide lists more; these are the ones that call through
+ * {@link ServiceCallAuthorizer}.
+ */
+ private static final Set<String> SNS_SOURCE_OWNER_SERVICES = Set.of("ses");
public static final String EXISTING_OBJECT_TAG_PREFIX = "s3:ExistingObjectTag/";
public static final String REQUEST_OBJECT_TAG_PREFIX = "s3:RequestObjectTag/";
public static final String REQUEST_OBJECT_TAG_KEYS = "s3:RequestObjectTagKeys";
@@ -124,6 +131,38 @@ public class IamConditionContextResolver {
return conditions;
}
+ /**
+ * The request context of a call an AWS service makes on its own behalf, such as SES publishing to
+ * a topic, from the IAM User Guide's global condition keys: {@code aws:PrincipalIsAWSService} is
+ * {@code true}; {@code aws:PrincipalServiceName} and {@code aws:PrincipalServiceNamesList} name the
+ * service; {@code aws:SourceArn} and {@code aws:SourceAccount} name the resource whose
+ * configuration triggered the call, when it has them; and {@code aws:ResourceAccount} and
+ * {@code aws:RequestedRegion} describe the target. The keys that describe an IAM principal,
+ * {@code aws:PrincipalArn} and {@code aws:PrincipalAccount} among them, are left out: no IAM
+ * principal makes the call. A call to an SNS topic from a service SNS lists as setting it also
+ * carries {@code aws:SourceOwner}, the source account, which is what the default topic policy
+ * checks.
+ */
+ public static Map<String, List<String>> serviceCallContext(String servicePrincipal, String resourceArn,
+ String resourceOwnerAccountId,
+ String sourceArn, String sourceAccount) {
+ Map<String, List<String>> conditions = new LinkedHashMap<>();
+ conditions.put("aws:PrincipalIsAWSService", List.of("true"));
+ conditions.put("aws:PrincipalServiceName", List.of(servicePrincipal));
+ conditions.put("aws:PrincipalServiceNamesList", List.of(servicePrincipal));
+ putIfPresent(conditions, "aws:SourceArn", sourceArn);
+ putIfPresent(conditions, "aws:SourceAccount", sourceAccount);
+ if (SNS_SOURCE_OWNER_SERVICES.contains(ServicePrincipals.serviceName(servicePrincipal))
+ && AwsArnUtils.isArnFor(resourceArn, "sns")) {
+ putIfPresent(conditions, "aws:SourceOwner", sourceAccount);
+ }
+ String resourceAccount = accountFromArn(resourceArn);
+ putIfPresent(conditions, "aws:ResourceAccount",
+ resourceAccount == null || resourceAccount.isBlank() ? resourceOwnerAccountId : resourceAccount);
+ putIfPresent(conditions, "aws:RequestedRegion", AwsArnUtils.regionOrDefault(resourceArn, null));
+ return conditions;
+ }
+
private static String accountFromArn(String arn) {
if (arn == null || !arn.startsWith("arn:")) {
return null;
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
index efc0b29db5..479f0f6d9e 100644
--- a/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
+++ b/src/main/java/io/github/hectorvent/floci/core/common/IamEnforcementFilter.java
@@ -14,6 +14,7 @@ import io.github.hectorvent.floci.services.iam.IamService.PresignedScope;
import io.github.hectorvent.floci.services.iam.RequestPrincipal;
import io.github.hectorvent.floci.services.iam.ResourceArnBuilder;
import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
+import io.github.hectorvent.floci.services.iam.ResourcePolicyProviders;
import io.github.hectorvent.floci.services.iam.ScpProvider;
import io.github.hectorvent.floci.services.iam.model.CallerContext;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
@@ -1177,17 +1178,7 @@ public class IamEnforcementFilter implements ContainerRequestFilter {
}
private List<ResourcePolicyProvider.ResourcePolicy> resolveResourcePolicies(String credentialScope, String resourceArn) {
- if (resourcePolicyProviders == null || resourcePolicyProviders.isUnsatisfied()) {
- return List.of();
- }
- List<ResourcePolicyProvider.ResourcePolicy> policies = new ArrayList<>();
- for (ResourcePolicyProvider provider : resourcePolicyProviders) {
- List<ResourcePolicyProvider.ResourcePolicy> providerPolicies = provider.getResourcePolicies(credentialScope, resourceArn);
- if (providerPolicies != null && !providerPolicies.isEmpty()) {
- policies.addAll(providerPolicies);
- }
- }
- return policies;
+ return ResourcePolicyProviders.policiesFor(resourcePolicyProviders, credentialScope, resourceArn);
}
/**
diff --git a/src/main/java/io/github/hectorvent/floci/core/common/ServiceCallAuthorizer.java b/src/main/java/io/github/hectorvent/floci/core/common/ServiceCallAuthorizer.java
new file mode 100644
index 0000000000..72bb91b63a
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/core/common/ServiceCallAuthorizer.java
@@ -0,0 +1,84 @@
+package io.github.hectorvent.floci.core.common;
+
+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 io.github.hectorvent.floci.services.iam.ResourcePolicyProviders;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.enterprise.inject.Instance;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Decides a call one AWS service makes to another's resource on its own behalf, such as SES
+ * publishing an event notification to an SNS topic. These calls never pass through
+ * {@link IamEnforcementFilter}: no IAM principal makes them, so no identity policy, session policy,
+ * boundary or SCP applies, and the target's resource policy decides alone. It has to allow the
+ * calling service principal, under the conditions the guides tell owners to write against the
+ * confused deputy problem: {@code aws:SourceArn} and {@code aws:SourceAccount}, the resource whose
+ * configuration triggered the call.
+ *
+ * <p>The policy comes from the same {@link ResourcePolicyProvider}s the filter reads, picked by the
+ * target ARN's service. A target no provider knows has no policy, and a policy that says nothing
+ * denies, as on AWS.
+ *
+ * <p>Only active with IAM enforcement on. With it off, every call is allowed, as every API call is.
+ * The decision is returned rather than thrown, because what a refusal means is the caller's to
+ * decide: a notification that is not delivered, a delivery that is retried, or an error.
+ */
+@ApplicationScoped
+public class ServiceCallAuthorizer {
+
+ private static final Logger LOG = Logger.getLogger(ServiceCallAuthorizer.class);
+
+ private final EmulatorConfig config;
+ private final IamPolicyEvaluator evaluator;
+ private final Instance<ResourcePolicyProvider> resourcePolicyProviders;
+
+ @Inject
+ public ServiceCallAuthorizer(EmulatorConfig config, IamPolicyEvaluator evaluator,
+ Instance<ResourcePolicyProvider> resourcePolicyProviders) {
+ this.config = config;
+ this.evaluator = evaluator;
+ this.resourcePolicyProviders = resourcePolicyProviders;
+ }
+
+ /**
+ * Decides whether {@code service} may perform {@code action} on {@code resourceArn}.
+ *
+ * @param service the calling service, such as {@code ses}; its principal is
+ * {@code ServicePrincipals.of(service)}
+ * @param action the IAM action, such as {@code sns:Publish}
+ * @param resourceArn the target resource
+ * @param sourceArn the resource whose configuration triggered the call, or null
+ * @param sourceAccount the account that owns it, or null
+ */
+ public Decision authorize(String service, String action, String resourceArn,
+ String sourceArn, String sourceAccount) {
+ if (!config.services().iam().enforcementEnabled()) {
+ return Decision.ALLOW;
+ }
+ String servicePrincipal = ServicePrincipals.of(service);
+ String targetService = AwsArnUtils.isArn(resourceArn) ? AwsArnUtils.parse(resourceArn).service() : null;
+ List<ResourcePolicyProvider.ResourcePolicy> policies =
+ ResourcePolicyProviders.policiesFor(resourcePolicyProviders, targetService, resourceArn);
+ String ownerAccountId = policies.isEmpty() ? null : policies.getFirst().ownerAccountId();
+ List<String> documents = policies.stream()
+ .map(ResourcePolicyProvider.ResourcePolicy::policyDocument)
+ .filter(document -> document != null && !document.isBlank())
+ .toList();
+ Map<String, List<String>> context = IamConditionContextResolver.serviceCallContext(
+ servicePrincipal, resourceArn, ownerAccountId, sourceArn, sourceAccount);
+ Decision decision = evaluator.evaluateServicePrincipal(
+ documents.isEmpty() ? null : documents, servicePrincipal, action, resourceArn, context);
+ if (decision == Decision.DENY) {
+ LOG.infov("IAM enforcement DENY: service={0} action={1} resource={2} source={3}",
+ servicePrincipal, action, resourceArn, sourceArn);
+ }
+ return decision;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
index f95db3d6ac..753c49f87a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluator.java
@@ -73,10 +73,21 @@ public class IamPolicyEvaluator {
public enum ResourcePolicyDecision {
ALLOW,
ALLOW_DIRECT_IAM_USER,
+ /**
+ * An Allow that names the caller only through its account: an account ID, the account's
+ * root ARN or, in an S3 bucket policy, its canonical user ID. That "delegates authority to
+ * the account" (IAM User Guide, "AWS account principals"), so across accounts it is the
+ * owner's half of the grant, while within the account it grants nothing on its own and the
+ * caller's identity-based policies have to allow the request.
+ */
+ ALLOW_ACCOUNT,
EXPLICIT_DENY,
NEUTRAL
}
+ /** How a resource policy statement's principal names a caller: itself, only its account, or not at all. */
+ private enum PrincipalMatch { NONE, ACCOUNT, CALLER }
+
public enum ResourceAccountRelationship {
SAME_ACCOUNT,
CROSS_ACCOUNT
@@ -166,7 +177,8 @@ public class IamPolicyEvaluator {
* Evaluates a principal-filtered resource policy with the caller/resource account relationship.
* Cross-account access requires both identity and resource policy allows. A same-account resource
* policy that directly names an IAM user ARN is not limited by an implicit permissions-boundary
- * deny, although every explicit deny still wins.
+ * deny, although every explicit deny still wins. A same-account Allow that names only the
+ * caller's account ({@link ResourcePolicyDecision#ALLOW_ACCOUNT}) grants nothing on its own.
*/
public Decision evaluateResolvedResourcePolicy(
CallerContext caller,
@@ -183,15 +195,17 @@ public class IamPolicyEvaluator {
? null : parseAll(List.of(caller.boundaryPolicyDocument()));
ResourcePolicyDecision resolvedDecision = resourcePolicyDecision == null
? ResourcePolicyDecision.NEUTRAL : resourcePolicyDecision;
+ ResourceAccountRelationship relationship = accountRelationship == null
+ ? ResourceAccountRelationship.CROSS_ACCOUNT : accountRelationship;
return evaluateParsed(
caller, identityStmts, sessionStmts, boundaryStmts,
resolvedDecision == ResourcePolicyDecision.EXPLICIT_DENY,
resolvedDecision == ResourcePolicyDecision.ALLOW
- || resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
+ || resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER
+ || resolvedDecision == ResourcePolicyDecision.ALLOW_ACCOUNT
+ && relationship == ResourceAccountRelationship.CROSS_ACCOUNT,
resolvedDecision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
- accountRelationship == null
- ? ResourceAccountRelationship.CROSS_ACCOUNT : accountRelationship,
- lowercase(action), resource, ctx);
+ relationship, lowercase(action), resource, ctx);
}
/**
@@ -242,10 +256,11 @@ public class IamPolicyEvaluator {
if (anyResourceDirectIamUserAllow(stmts, principal, loweredAction, resource, ctx)) {
return ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER;
}
- if (anyResourceExplicitAllow(stmts, principal, loweredAction, resource, ctx)) {
- return ResourcePolicyDecision.ALLOW;
- }
- return ResourcePolicyDecision.NEUTRAL;
+ return switch (strongestResourceAllow(stmts, principal, loweredAction, resource, ctx)) {
+ case CALLER -> ResourcePolicyDecision.ALLOW;
+ case ACCOUNT -> ResourcePolicyDecision.ALLOW_ACCOUNT;
+ case NONE -> ResourcePolicyDecision.NEUTRAL;
+ };
}
/**
@@ -820,21 +835,30 @@ public class IamPolicyEvaluator {
private boolean anyResourceExplicitDeny(List<PolicyStatement> stmts, RequestPrincipal principal,
String action, String resource, Map<String, List<String>> ctx) {
for (PolicyStatement stmt : stmts) {
- if (stmt.isDeny() && matchesResourceStatement(stmt, principal, action, resource, ctx)) {
+ if (stmt.isDeny() && resourceStatementMatch(stmt, principal, action, resource, ctx) != PrincipalMatch.NONE) {
return true;
}
}
return false;
}
- private boolean anyResourceExplicitAllow(List<PolicyStatement> stmts, RequestPrincipal principal,
- String action, String resource, Map<String, List<String>> ctx) {
+ /** How closely the closest matching Allow names the caller. */
+ private PrincipalMatch strongestResourceAllow(List<PolicyStatement> stmts, RequestPrincipal principal,
+ String action, String resource, Map<String, List<String>> ctx) {
+ PrincipalMatch strongest = PrincipalMatch.NONE;
for (PolicyStatement stmt : stmts) {
- if (stmt.isAllow() && matchesResourceStatement(stmt, principal, action, resource, ctx)) {
- return true;
+ if (!stmt.isAllow()) {
+ continue;
+ }
+ PrincipalMatch match = resourceStatementMatch(stmt, principal, action, resource, ctx);
+ if (match == PrincipalMatch.CALLER) {
+ return match;
+ }
+ if (match == PrincipalMatch.ACCOUNT) {
+ strongest = match;
}
}
- return false;
+ return strongest;
}
private boolean anyResourceDirectIamUserAllow(List<PolicyStatement> stmts, RequestPrincipal principal,
@@ -911,28 +935,66 @@ public class IamPolicyEvaluator {
return false;
}
- private boolean matchesResourceStatement(PolicyStatement stmt, RequestPrincipal principal,
- String action, String resource, Map<String, List<String>> ctx) {
+ private PrincipalMatch resourceStatementMatch(PolicyStatement stmt, RequestPrincipal principal,
+ String action, String resource, Map<String, List<String>> ctx) {
// A resource-policy statement with no Principal matches nothing (per AWS specification)
if (stmt.getPrincipals() == null && stmt.getNotPrincipals() == null) {
- return false;
+ return PrincipalMatch.NONE;
}
- if (!matchesPrincipal(stmt, principal)) {
- return false;
+ PrincipalMatch match = principalMatch(stmt, principal);
+ if (match == PrincipalMatch.NONE
+ || !matchesAction(stmt, action)
+ || !matchesResource(stmt, resource)
+ || !matchesConditions(stmt.getConditions(), ctx)) {
+ return PrincipalMatch.NONE;
}
- return matchesAction(stmt, action)
- && matchesResource(stmt, resource)
- && matchesConditions(stmt.getConditions(), ctx);
+ return match;
}
- private boolean matchesPrincipal(PolicyStatement stmt, RequestPrincipal principal) {
+ /** A {@code NotPrincipal} statement applies to every caller it does not spare. */
+ private PrincipalMatch principalMatch(PolicyStatement stmt, RequestPrincipal principal) {
if (stmt.getPrincipals() != null) {
- return matchesAnyPrincipal(stmt.getPrincipals(), principal);
+ return matchAnyPrincipal(stmt.getPrincipals(), principal);
}
if (stmt.getNotPrincipals() != null) {
- return !matchesAnyPrincipal(stmt.getNotPrincipals(), principal);
+ boolean spared = stmt.isDeny()
+ ? sparedFromDeny(stmt.getNotPrincipals(), principal)
+ : matchAnyPrincipal(stmt.getNotPrincipals(), principal) != PrincipalMatch.NONE;
+ return spared ? PrincipalMatch.NONE : PrincipalMatch.CALLER;
}
- return false;
+ return PrincipalMatch.NONE;
+ }
+
+ /**
+ * Whether a Deny's {@code NotPrincipal} spares the caller. The IAM User Guide ("AWS JSON policy
+ * elements: NotPrincipal") says it "will always deny any IAM principal that has a permissions
+ * boundary policy attached, regardless of the values specified", and that AWS may check the
+ * caller's account before the caller, so a list naming a user or role without its account "might
+ * deny access to the entire account". Floci takes that reading: an IAM caller is spared only when
+ * the list names its account and the caller itself, user, role or role session, or only its
+ * account when the caller is the account root. Anyone else is spared when the list names it.
+ */
+ private boolean sparedFromDeny(Map<String, List<String>> notPrincipals, RequestPrincipal principal) {
+ if (principal.type() != RequestPrincipal.Type.IAM || principal.arn() == null) {
+ return matchAnyPrincipal(notPrincipals, principal) != PrincipalMatch.NONE;
+ }
+ if (principal.permissionsBoundary()) {
+ return false;
+ }
+ boolean accountNamed = false;
+ boolean callerNamed = false;
+ for (Map.Entry<String, List<String>> entry : notPrincipals.entrySet()) {
+ List<String> patterns = entry.getValue() == null ? List.of() : entry.getValue();
+ for (String pattern : patterns) {
+ PrincipalMatch match = matchAnyPrincipal(Map.of(entry.getKey(), List.of(pattern)), principal);
+ if (match == PrincipalMatch.CALLER && "*".equals(pattern)) {
+ return true;
+ }
+ accountNamed |= match == PrincipalMatch.ACCOUNT;
+ callerNamed |= match == PrincipalMatch.CALLER;
+ }
+ }
+ return accountNamed && (callerNamed || ROOT_PRINCIPAL_ARN.matcher(principal.arn()).matches());
}
/**
@@ -946,9 +1008,11 @@ public class IamPolicyEvaluator {
* by its S3 canonical user ID, and matches the IAM identities of that account as an account
* principal does; Floci's canonical ID for an account is the account id, as its S3 ACLs report
* it. {@code Federated} and any other type name callers this evaluator never sees, and so match
- * nothing, rather than being compared with an IAM ARN.
+ * nothing, rather than being compared with an IAM ARN. An entry naming the caller itself wins
+ * over one naming only its account.
*/
- private boolean matchesAnyPrincipal(Map<String, List<String>> principals, RequestPrincipal principal) {
+ private PrincipalMatch matchAnyPrincipal(Map<String, List<String>> principals, RequestPrincipal principal) {
+ PrincipalMatch strongest = PrincipalMatch.NONE;
for (Map.Entry<String, List<String>> entry : principals.entrySet()) {
String type = entry.getKey();
List<String> patterns = entry.getValue();
@@ -958,27 +1022,32 @@ public class IamPolicyEvaluator {
if ("*".equals(type)) {
for (String pattern : patterns) {
if ("*".equals(pattern)) {
- return true;
+ return PrincipalMatch.CALLER;
}
if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null
&& globMatches(pattern, principal.arn())) {
- return true;
+ return PrincipalMatch.CALLER;
}
}
} else if ("AWS".equalsIgnoreCase(type)) {
if (patterns.contains("*") && principal.type() != RequestPrincipal.Type.ANONYMOUS) {
- return true;
+ return PrincipalMatch.CALLER;
}
- if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null
- && matchesAwsPrincipal(patterns, principal)) {
- return true;
+ if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null) {
+ PrincipalMatch match = matchAwsPrincipal(patterns, principal);
+ if (match == PrincipalMatch.CALLER) {
+ return match;
+ }
+ if (match == PrincipalMatch.ACCOUNT) {
+ strongest = match;
+ }
}
} else if ("Service".equalsIgnoreCase(type)) {
if (principal.type() == RequestPrincipal.Type.SERVICE && principal.servicePrincipal() != null) {
String wanted = ServicePrincipals.canonical(principal.servicePrincipal());
for (String pattern : patterns) {
if (!"*".equals(pattern) && ServicePrincipals.canonical(pattern).equals(wanted)) {
- return true;
+ return PrincipalMatch.CALLER;
}
}
}
@@ -986,24 +1055,25 @@ public class IamPolicyEvaluator {
if (principal.type() == RequestPrincipal.Type.IAM && principal.arn() != null) {
String accountId = extractAccountId(principal.arn());
if (accountId != null && patterns.contains(accountId)) {
- return true;
+ strongest = PrincipalMatch.ACCOUNT;
}
}
}
}
- return false;
+ return strongest;
}
- private boolean matchesAwsPrincipal(List<String> patterns, RequestPrincipal principal) {
+ private PrincipalMatch matchAwsPrincipal(List<String> patterns, RequestPrincipal principal) {
String principalArn = principal.arn();
String accountId = extractAccountId(principalArn);
String roleArn = principal.roleArn() != null
? principal.roleArn()
: extractRoleArnFromAssumedRole(principalArn);
+ PrincipalMatch strongest = PrincipalMatch.NONE;
for (String pattern : patterns) {
if (pattern.matches("\\d{12}")) {
if (pattern.equals(accountId)) {
- return true;
+ strongest = PrincipalMatch.ACCOUNT;
}
} else if (ROOT_PRINCIPAL_ARN.matcher(pattern).matches()) {
// An account id is scoped to its partition: arn:aws-cn:iam::123:root names
@@ -1011,15 +1081,15 @@ public class IamPolicyEvaluator {
AwsArnUtils.Arn root = AwsArnUtils.parse(pattern);
if (root.accountId().equals(accountId)
&& root.partition().equals(AwsArnUtils.parse(principalArn).partition())) {
- return true;
+ strongest = PrincipalMatch.ACCOUNT;
}
} else if (globMatches(pattern, principalArn)) {
- return true;
+ return PrincipalMatch.CALLER;
} else if (roleArn != null && globMatches(pattern, roleArn)) {
- return true;
+ return PrincipalMatch.CALLER;
}
}
- return false;
+ return strongest;
}
private static String extractAccountId(String arn) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
index 537ae87117..eb49344240 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java
@@ -5107,9 +5107,11 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
* @param userId the request's {@code aws:userid}, in the shape the guide gives for this
* kind of principal, or null when it publishes none
* @param userName the request's {@code aws:username}, which only an IAM user has
+ * @param permissionsBoundary whether a permissions boundary is attached to the user, or to the
+ * role a session assumed, which a Deny's {@code NotPrincipal} never spares
*/
public record CallerArns(String callerArn, String principalArn, String principalType,
- String userId, String userName) {
+ String userId, String userName, boolean permissionsBoundary) {
/**
* The {@code aws:PrincipalType} values, from the IAM User Guide's principal key values
@@ -5128,6 +5130,12 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
this(callerArn, principalArn, null, null, null);
}
+ /** A caller with no permissions boundary attached. */
+ public CallerArns(String callerArn, String principalArn, String principalType, String userId,
+ String userName) {
+ this(callerArn, principalArn, principalType, userId, userName, false);
+ }
+
/**
* Writes the condition keys that say who is calling onto a request context, so every
* context a request is evaluated against sees the same principal: the enforcement
@@ -5165,7 +5173,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
*/
private static CallerArns callerForUser(IamUser user) {
return new CallerArns(user.getArn(), user.getArn(), CallerArns.TYPE_USER,
- user.getUserId(), user.getUserName());
+ user.getUserId(), user.getUserName(), user.getPermissionsBoundaryArn() != null);
}
@@ -5224,7 +5232,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
String sessionArn = AwsArnUtils.Arn.global(partition, "sts", accountId,
"assumed-role/" + roleName + "/" + sessionName).toString();
return Optional.of(new CallerArns(sessionArn, roleArn, CallerArns.TYPE_ASSUMED_ROLE,
- sessionUserId(session).orElse(null), null));
+ sessionUserId(session).orElse(null), null,
+ roleFromArnOrName(roleArn).map(IamRole::getPermissionsBoundaryArn).isPresent()));
}
return Optional.empty();
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/RequestPrincipal.java b/src/main/java/io/github/hectorvent/floci/services/iam/RequestPrincipal.java
index f3f8051360..74d527a055 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/RequestPrincipal.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/RequestPrincipal.java
@@ -13,19 +13,22 @@ package io.github.hectorvent.floci.services.iam;
* which a {@code Principal} naming the role identifies; null otherwise
* @param servicePrincipal a service caller's principal name, such as {@code sns.amazonaws.com};
* null for the other kinds
+ * @param permissionsBoundary whether an IAM caller has a permissions boundary attached, which a
+ * Deny's {@code NotPrincipal} never spares
*/
-public record RequestPrincipal(Type type, String arn, String roleArn, String servicePrincipal) {
+public record RequestPrincipal(Type type, String arn, String roleArn, String servicePrincipal,
+ boolean permissionsBoundary) {
public enum Type { IAM, SERVICE, ANONYMOUS }
/** An IAM user, account root or federated user, or a role session without its role's ARN. */
public static RequestPrincipal iam(String arn) {
- return new RequestPrincipal(Type.IAM, arn, null, null);
+ return new RequestPrincipal(Type.IAM, arn, null, null, false);
}
/** A role session, matched by its session ARN and by the ARN of the role that was assumed. */
public static RequestPrincipal roleSession(String sessionArn, String roleArn) {
- return new RequestPrincipal(Type.IAM, sessionArn, roleArn, null);
+ return new RequestPrincipal(Type.IAM, sessionArn, roleArn, null, false);
}
/**
@@ -38,18 +41,19 @@ public record RequestPrincipal(Type type, String arn, String roleArn, String ser
if (callerArns == null) {
return anonymous();
}
- return callerArns.callerArn().equals(callerArns.principalArn())
- ? iam(callerArns.callerArn())
- : roleSession(callerArns.callerArn(), callerArns.principalArn());
+ return new RequestPrincipal(Type.IAM, callerArns.callerArn(),
+ callerArns.callerArn().equals(callerArns.principalArn()) ? null : callerArns.principalArn(),
+ null, callerArns.permissionsBoundary());
}
/** An AWS service acting on its own behalf, such as SNS delivering to a queue. */
public static RequestPrincipal service(String servicePrincipal) {
- return new RequestPrincipal(Type.SERVICE, null, null, servicePrincipal);
+ return new RequestPrincipal(Type.SERVICE, null, null, servicePrincipal, false);
}
/** A caller with no credentials. */
public static RequestPrincipal anonymous() {
- return new RequestPrincipal(Type.ANONYMOUS, null, null, null);
+ return new RequestPrincipal(Type.ANONYMOUS, null, null, null, false);
}
+
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProviders.java b/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProviders.java
new file mode 100644
index 0000000000..62624f5017
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/ResourcePolicyProviders.java
@@ -0,0 +1,37 @@
+package io.github.hectorvent.floci.services.iam;
+
+import jakarta.enterprise.inject.Instance;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Collects what the registered {@link ResourcePolicyProvider}s supply for one resource. Shared by the
+ * request filter, for the resource a request names, and by the authorizer for calls one AWS service
+ * makes to another's resource, so both see the same policies and the same owning account.
+ */
+public final class ResourcePolicyProviders {
+
+ private ResourcePolicyProviders() {
+ }
+
+ /**
+ * The resource-based policies every provider supplies for {@code resourceArn}, in provider order,
+ * or an empty list when there are no providers or none applies.
+ */
+ public static List<ResourcePolicyProvider.ResourcePolicy> policiesFor(
+ Instance<ResourcePolicyProvider> providers, String credentialScope, String resourceArn) {
+ if (providers == null || providers.isUnsatisfied()) {
+ return List.of();
+ }
+ List<ResourcePolicyProvider.ResourcePolicy> policies = new ArrayList<>();
+ for (ResourcePolicyProvider provider : providers) {
+ List<ResourcePolicyProvider.ResourcePolicy> supplied =
+ provider.getResourcePolicies(credentialScope, resourceArn);
+ if (supplied != null && !supplied.isEmpty()) {
+ policies.addAll(supplied);
+ }
+ }
+ return policies;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
index 80d2543c46..44f3fd1d90 100644
--- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java
@@ -1387,7 +1387,8 @@ public class S3Service implements Resettable, ResourceProvider {
if (decision == ResourcePolicyDecision.EXPLICIT_DENY) {
throw accessDeniedException(bucketName, key);
}
- if (decision == ResourcePolicyDecision.ALLOW || decision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER) {
+ if (decision == ResourcePolicyDecision.ALLOW || decision == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER
+ || decision == ResourcePolicyDecision.ALLOW_ACCOUNT) {
return;
}
if (sameAccountAsOwner) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java
index 180ebe2876..d912eca4d4 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesEventPublisher.java
@@ -5,12 +5,14 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.core.common.ServiceCallAuthorizer;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricDatum;
import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;
import io.github.hectorvent.floci.services.firehose.FirehoseService;
import io.github.hectorvent.floci.services.firehose.model.Record;
+import io.github.hectorvent.floci.services.iam.IamPolicyEvaluator.Decision;
import io.github.hectorvent.floci.services.ses.model.CloudWatchDestination;
import io.github.hectorvent.floci.services.ses.model.CloudWatchDimensionConfiguration;
import io.github.hectorvent.floci.services.ses.model.ConfigurationSet;
@@ -35,6 +37,12 @@ import java.util.Map;
* {@code KinesisFirehoseDestination}, {@code EventBridgeDestination}, and
* {@code CloudWatchDestination} are delivered live; Pinpoint destinations are
* logged and skipped.
+ *
+ * <p>SES publishes to an SNS topic as {@code ses.amazonaws.com}, so the topic's policy decides
+ * whether it may, through {@link ServiceCallAuthorizer}, with the resource whose configuration names
+ * the topic as {@code aws:SourceArn}: the configuration set for an event destination, the identity
+ * for an identity notification (SES Developer Guide, "Set up an Amazon SNS event destination for
+ * event publishing" and "Configuring Amazon SNS notifications for Amazon SES").
*/
@ApplicationScoped
public class SesEventPublisher {
@@ -47,17 +55,19 @@ public class SesEventPublisher {
private final FirehoseService firehoseService;
private final EventBridgeService eventBridgeService;
private final CloudWatchMetricsService cloudWatchMetricsService;
+ private final ServiceCallAuthorizer serviceCallAuthorizer;
private final ObjectMapper objectMapper;
@Inject
public SesEventPublisher(SnsService snsService, FirehoseService firehoseService,
EventBridgeService eventBridgeService,
CloudWatchMetricsService cloudWatchMetricsService,
- ObjectMapper objectMapper) {
+ ServiceCallAuthorizer serviceCallAuthorizer, ObjectMapper objectMapper) {
this.snsService = snsService;
this.firehoseService = firehoseService;
this.eventBridgeService = eventBridgeService;
this.cloudWatchMetricsService = cloudWatchMetricsService;
+ this.serviceCallAuthorizer = serviceCallAuthorizer;
this.objectMapper = objectMapper;
}
@@ -86,7 +96,7 @@ public class SesEventPublisher {
}
try {
dispatch(ed, eventType, payloadJson, sourceArn, configurationSet.getName(),
- emailTags, additionalHeaders, defaultRegion);
+ sendingAccountId, emailTags, additionalHeaders, defaultRegion);
} catch (Exception e) {
LOG.warnf(e, "Failed to publish SES event %s to destination %s",
eventType, ed.getName());
@@ -102,25 +112,44 @@ public class SesEventPublisher {
* configuration set. The payload uses the legacy {@code notificationType} discriminator, omits
* {@code mail.tags}, and includes the original headers only when {@code includeHeaders} is set
* (i.e. the identity has headers-in-notifications enabled for the type).
+ *
+ * @param identityArn the identity the topic is configured on, the sender's own or its domain's,
+ * which SES names as {@code aws:SourceArn}
+ * @return false when SES may not publish to the topic, because it no longer exists or its policy
+ * does not let SES publish for {@code identityArn}, so nothing was sent; true otherwise,
+ * including when the publish itself failed for another reason
*/
- public void publishIdentityNotification(String topicArn, boolean includeHeaders,
+ public boolean publishIdentityNotification(String topicArn, String identityArn, boolean includeHeaders,
SesRecipientEvent event, String messageId, String source, String sourceArn,
String sendingAccountId, String subject, List<String> toAddresses,
List<String> ccAddresses, List<String> bccAddresses,
List<String> envelopeDestinations, List<MessageHeader> additionalHeaders,
Instant timestamp, String defaultRegion) {
if (topicArn == null || topicArn.isBlank()) {
- return;
+ return true;
+ }
+ if (!sesMayPublish(topicArn, identityArn, sendingAccountId)) {
+ LOG.warnf("SES %s notification for %s not delivered (topic %s does not allow SES to publish).",
+ event.eventType(), identityArn, topicArn);
+ return false;
+ }
+ // Read in the topic's own account: a topic of another account that Floci cannot deliver to
+ // still exists, and only a topic that is gone counts as one SES cannot publish to.
+ if (!snsService.topicExists(topicArn, AwsArnUtils.regionOrDefault(topicArn, defaultRegion))) {
+ LOG.warnf("SES %s notification for %s not delivered (topic %s does not exist).",
+ event.eventType(), identityArn, topicArn);
+ return false;
}
ObjectNode payload = SesEventPayload.buildIdentityNotification(objectMapper, event,
messageId, source, sourceArn, sendingAccountId, subject,
toAddresses, ccAddresses, bccAddresses, envelopeDestinations,
additionalHeaders, timestamp, includeHeaders);
publishSns(topicArn, payload.toString(), defaultRegion);
+ return true;
}
private void dispatch(EventDestination ed, String eventType, String payloadJson,
- String sourceArn, String configurationSetName,
+ String sourceArn, String configurationSetName, String sendingAccountId,
List<MessageTag> emailTags, List<MessageHeader> additionalHeaders,
String defaultRegion) {
if (ed.getSnsDestination() != null) {
@@ -130,6 +159,13 @@ public class SesEventPublisher {
ed.getName(), eventType);
return;
}
+ String configurationSetArn = AwsArnUtils.Arn.of("ses", defaultRegion, sendingAccountId,
+ "configuration-set/" + configurationSetName).toString();
+ if (!sesMayPublish(topicArn, configurationSetArn, sendingAccountId)) {
+ LOG.warnf("SES SNS destination %s: event %s not delivered (topic %s does not allow SES to publish).",
+ ed.getName(), eventType, topicArn);
+ return;
+ }
publishSns(topicArn, payloadJson, defaultRegion);
return;
}
@@ -167,6 +203,12 @@ public class SesEventPublisher {
ed.getName(), eventType);
}
+ /** Whether the topic's policy lets SES publish to it for {@code sourceArn}, owned by {@code sourceAccount}. */
+ private boolean sesMayPublish(String topicArn, String sourceArn, String sourceAccount) {
+ return serviceCallAuthorizer.authorize("ses", "sns:Publish", topicArn, sourceArn, sourceAccount)
+ == Decision.ALLOW;
+ }
+
private void publishSns(String topicArn, String payload, String defaultRegion) {
String region = AwsArnUtils.regionOrDefault(topicArn, defaultRegion);
try {
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java
index e9798ea59e..f11cdf4538 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesIdentityService.java
@@ -57,7 +57,8 @@ public class SesIdentityService implements SesTaggable {
private final Clock clock;
private final ConcurrentHashMap<String, DkimLookupCacheEntry> dkimLookupCache = new ConcurrentHashMap<>();
// Serializes every identity check-then-put (v2 CreateEmailIdentity, the v1 verify family, the
- // CVET pending registration) so concurrent creators can't lose each other's writes
+ // CVET pending registration, and the notification settings, which SES also changes on its own
+ // when it cannot publish to a topic) so concurrent writers can't lose each other's writes
// (InMemoryStorage only makes each individual operation thread-safe).
private final Object identityCreationLock = new Object();
@@ -399,15 +400,49 @@ public class SesIdentityService implements SesTaggable {
public void setIdentityNotificationTopic(String identityValue, String notificationType,
String snsTopic, String region) {
- Identity identity = identityStore.get(identityKey(region, identityValue))
- .orElseThrow(() -> new AwsException("InvalidParameterValue",
- "Identity does not exist: " + identityValue, 400));
- if (snsTopic != null && !snsTopic.isBlank()) {
- identity.getNotificationAttributes().put(notificationType + "Topic", snsTopic);
- } else {
- identity.getNotificationAttributes().remove(notificationType + "Topic");
+ synchronized (identityCreationLock) {
+ Identity identity = identityStore.get(identityKey(region, identityValue))
+ .orElseThrow(() -> new AwsException("InvalidParameterValue",
+ "Identity does not exist: " + identityValue, 400));
+ if (snsTopic != null && !snsTopic.isBlank()) {
+ identity.getNotificationAttributes().put(notificationType + "Topic", snsTopic);
+ } else {
+ identity.getNotificationAttributes().remove(notificationType + "Topic");
+ }
+ identityStore.put(identityKey(region, identityValue), identity);
}
- identityStore.put(identityKey(region, identityValue), identity);
+ }
+
+ /**
+ * What SES does when it cannot publish an identity's notification because the topic is gone or no
+ * longer lets SES publish to it: it "removes the configuration for that topic if it's been
+ * configured for bounces or complaints", leaves a delivery setting in place, and turns email
+ * feedback forwarding back on (SES Developer Guide, "Configuring Amazon SNS notifications for
+ * Amazon SES"). So every bounce or complaint setting of the identity that names {@code topicArn}
+ * goes, whichever notification failed, while one changed to another topic since is kept. SES also
+ * emails the owner about the change, which Floci does not send.
+ */
+ public void dropRefusedNotificationTopic(String identityValue, String topicArn, String region) {
+ String key = identityKey(region, identityValue);
+ synchronized (identityCreationLock) {
+ Identity identity = identityStore.get(key).orElse(null);
+ if (identity == null) {
+ return;
+ }
+ boolean removed = false;
+ for (String type : List.of("Bounce", "Complaint")) {
+ if (identity.getNotificationAttributes().remove(type + "Topic", topicArn)) {
+ removed = true;
+ }
+ }
+ if (!removed) {
+ return;
+ }
+ identity.setFeedbackForwardingEnabled(true);
+ identityStore.put(key, identity);
+ }
+ LOG.infov("Removed topic {0}, which SES may not publish to, from the bounce and complaint settings of {1}"
+ + " and enabled feedback forwarding", topicArn, identityValue);
}
public Identity getIdentityNotificationAttributes(String identityValue, String region) {
@@ -415,12 +450,14 @@ public class SesIdentityService implements SesTaggable {
}
public void setFeedbackForwardingEnabled(String identityValue, boolean enabled, String region) {
- Identity identity = identityStore.get(identityKey(region, identityValue))
- .orElseThrow(() -> new AwsException("InvalidParameterValue",
- "Identity " + identityValue
- + " is invalid. Must be a verified email address or domain.", 400));
- identity.setFeedbackForwardingEnabled(enabled);
- identityStore.put(identityKey(region, identityValue), identity);
+ synchronized (identityCreationLock) {
+ Identity identity = identityStore.get(identityKey(region, identityValue))
+ .orElseThrow(() -> new AwsException("InvalidParameterValue",
+ "Identity " + identityValue
+ + " is invalid. Must be a verified email address or domain.", 400));
+ identity.setFeedbackForwardingEnabled(enabled);
+ identityStore.put(identityKey(region, identityValue), identity);
+ }
LOG.infov("Updated feedback forwarding for {0}: enabled={1}", identityValue, enabled);
}
@@ -436,12 +473,14 @@ public class SesIdentityService implements SesTaggable {
+ "constraint: Member must satisfy enum value set: "
+ NOTIFICATION_TYPES, 400);
}
- Identity identity = identityStore.get(identityKey(region, identityValue))
- .orElseThrow(() -> new AwsException("InvalidParameterValue",
- "Identity " + identityValue
- + " is invalid. It must be a verified email address or domain.", 400));
- identity.getHeadersInNotificationsEnabled().put(notificationType, enabled);
- identityStore.put(identityKey(region, identityValue), identity);
+ synchronized (identityCreationLock) {
+ Identity identity = identityStore.get(identityKey(region, identityValue))
+ .orElseThrow(() -> new AwsException("InvalidParameterValue",
+ "Identity " + identityValue
+ + " is invalid. It must be a verified email address or domain.", 400));
+ identity.getHeadersInNotificationsEnabled().put(notificationType, enabled);
+ identityStore.put(identityKey(region, identityValue), identity);
+ }
LOG.infov("Updated headers-in-notifications for {0}: {1}={2}",
identityValue, notificationType, enabled);
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java
index 6fa5ec9ef0..cfff455ed2 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleService.java
@@ -4,8 +4,11 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
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.StorageBackend;
import io.github.hectorvent.floci.core.storage.StorageFactory;
+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;
@@ -82,11 +85,15 @@ public class SesReceiptRuleService {
private final LambdaService lambdaService;
// Serializes filter create (duplicate check, then the 100-filter cap, then put).
private final Object receiptFilterLock = new Object();
+ private final ServiceCallAuthorizer serviceCallAuthorizer;
+ private final RegionResolver regionResolver;
private final Clock clock;
@Inject
public SesReceiptRuleService(StorageFactory storageFactory, S3Service s3Service,
- SnsService snsService, LambdaService lambdaService, Clock clock) {
+ SnsService snsService, LambdaService lambdaService,
+ ServiceCallAuthorizer serviceCallAuthorizer, RegionResolver regionResolver,
+ Clock clock) {
this.receiptRuleSetStore = storageFactory.create("ses", "ses-receipt-rule-sets.json",
new TypeReference<Map<String, ReceiptRuleSet>>() {});
this.receiptFilterStore = storageFactory.create("ses", "ses-receipt-filters.json",
@@ -94,18 +101,23 @@ public class SesReceiptRuleService {
this.s3Service = s3Service;
this.snsService = snsService;
this.lambdaService = lambdaService;
+ this.serviceCallAuthorizer = serviceCallAuthorizer;
+ this.regionResolver = regionResolver;
this.clock = clock;
}
SesReceiptRuleService(StorageBackend<String, ReceiptRuleSet> receiptRuleSetStore,
StorageBackend<String, ReceiptFilter> receiptFilterStore,
S3Service s3Service, SnsService snsService, LambdaService lambdaService,
+ ServiceCallAuthorizer serviceCallAuthorizer, RegionResolver regionResolver,
Clock clock) {
this.receiptRuleSetStore = receiptRuleSetStore;
this.receiptFilterStore = receiptFilterStore;
this.s3Service = s3Service;
this.snsService = snsService;
this.lambdaService = lambdaService;
+ this.serviceCallAuthorizer = serviceCallAuthorizer;
+ this.regionResolver = regionResolver;
this.clock = clock;
}
@@ -218,7 +230,7 @@ public class SesReceiptRuleService {
// AWS inserts at the FRONT when After is absent (probed); After places the rule
// immediately behind the named one.
int index = after == null ? 0 : indexOfRule(rules, after) + 1;
- validateActionTargets(rule, region, verifiedSender);
+ validateActionTargets(rule, ruleSetName, region, verifiedSender);
applyRuleDefaults(rule);
rules.add(index, rule);
replaceRules(ruleSet, rules, ruleSetName, region);
@@ -247,7 +259,7 @@ public class SesReceiptRuleService {
// AWS replaces the whole rule in place (omitted members reset to their defaults) and
// keeps its position; an unknown name is an error, so update cannot rename.
int index = indexOfRule(rules, rule.getName());
- validateActionTargets(rule, region, verifiedSender);
+ validateActionTargets(rule, ruleSetName, region, verifiedSender);
applyRuleDefaults(rule);
rules.set(index, rule);
replaceRules(ruleSet, rules, ruleSetName, region);
@@ -560,8 +572,14 @@ public class SesReceiptRuleService {
* checks real SES runs on create/update: any TopicArn must be a publishable SNS topic, an
* S3 bucket must exist, a Lambda function must be invokable, and a bounce sender must be a
* verified identity. Each check fires only when its member is present, matching AWS.
+ *
+ * <p>A topic is publishable when it exists and, under IAM enforcement, its policy lets SES publish
+ * for this rule: {@code InvalidSnsTopic} covers a topic SES "could not publish to, possibly due
+ * to permissions issues" (SES API Reference, {@code CreateReceiptRule}), and the SES Developer
+ * Guide's grant for it names the rule's ARN as {@code aws:SourceArn}.
*/
- private void validateActionTargets(ReceiptRule rule, String region, Predicate<String> verifiedSender) {
+ private void validateActionTargets(ReceiptRule rule, String ruleSetName, String region,
+ Predicate<String> verifiedSender) {
if (rule.getActions().size() > MAX_ACTIONS_PER_RULE) {
// Probed: the 11th action is rejected at the service layer, like the rules-per-set cap.
throw new AwsException("LimitExceeded", "Too many actions", 400);
@@ -587,7 +605,8 @@ public class SesReceiptRuleService {
if (!SNS_TOPIC_ARN.matcher(topicArn).matches()) {
throw new AwsException("InvalidSnsTopic", "Invalid SNS topic: " + topicArn, 400);
}
- if (!snsService.topicExists(topicArn, region)) {
+ if (!snsService.topicExists(topicArn, region)
+ || !sesMayPublish(topicArn, ruleSetName, rule, region)) {
throw new AwsException("InvalidSnsTopic",
"Could not publish to SNS topic: " + topicArn, 400);
}
@@ -639,6 +658,14 @@ public class SesReceiptRuleService {
}
}
+ /** Whether the topic's policy lets SES publish to it for {@code rule}, as the rule's account. */
+ private boolean sesMayPublish(String topicArn, String ruleSetName, ReceiptRule rule, String region) {
+ String account = regionResolver.getAccountId();
+ String ruleArn = AwsArnUtils.Arn.of("ses", region, account,
+ "receipt-rule-set/" + ruleSetName + ":receipt-rule/" + rule.getName()).toString();
+ return serviceCallAuthorizer.authorize("ses", "sns:Publish", topicArn, ruleArn, account) == Decision.ALLOW;
+ }
+
private static void applyRuleDefaults(ReceiptRule rule) {
if (rule.getTlsPolicy() == null) {
rule.setTlsPolicy("Optional");
diff --git a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java
index 5eda026286..9f245afda5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ses/SesService.java
@@ -691,10 +691,15 @@ public class SesService {
}
IdentityNotificationTarget target = identityTargets.get(event.eventType());
if (target != null) {
- eventPublisher.publishIdentityNotification(target.topicArn(), target.includeHeaders(),
- event, messageId, source, sourceArn, sendingAccountId, publishedSubject,
- toAddresses, ccAddresses, bccAddresses, envelope, publishedHeaders,
- timestamp, region);
+ String identityArn = AwsArnUtils.Arn.of("ses", region, sendingAccountId,
+ "identity/" + target.identity()).toString();
+ boolean allowed = eventPublisher.publishIdentityNotification(target.topicArn(), identityArn,
+ target.includeHeaders(), event, messageId, source, sourceArn, sendingAccountId,
+ publishedSubject, toAddresses, ccAddresses, bccAddresses, envelope,
+ publishedHeaders, timestamp, region);
+ if (!allowed) {
+ identityService.dropRefusedNotificationTopic(target.identity(), target.topicArn(), region);
+ }
}
}
}
@@ -736,7 +741,7 @@ public class SesService {
boolean includeHeaders = Boolean.TRUE.equals(
owner.getHeadersInNotificationsEnabled().get(type));
targets.put(type.toUpperCase(Locale.ROOT),
- new IdentityNotificationTarget(topic, includeHeaders));
+ new IdentityNotificationTarget(owner.getIdentity(), topic, includeHeaders));
}
return targets;
}
@@ -749,7 +754,8 @@ public class SesService {
return topic != null && !topic.isBlank() ? topic : null;
}
- private record IdentityNotificationTarget(String topicArn, boolean includeHeaders) {}
+ /** A notification topic and the identity that names it, the sender's own or its domain's. */
+ private record IdentityNotificationTarget(String identity, String topicArn, boolean includeHeaders) {}
// Package-private: the metric aggregation normalizes a stored Source the same way the
// send path does, so "Name <addr>" still matches an EMAIL_IDENTITY dimension.
diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsResourcePolicyProvider.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsResourcePolicyProvider.java
new file mode 100644
index 0000000000..40210749c1
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsResourcePolicyProvider.java
@@ -0,0 +1,47 @@
+package io.github.hectorvent.floci.services.sns;
+
+import io.github.hectorvent.floci.core.common.AwsArnUtils;
+import io.github.hectorvent.floci.services.iam.ResourcePolicyProvider;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.List;
+import java.util.regex.Pattern;
+
+/**
+ * Supplies SNS topic policies to IAM policy evaluation, together with the account that owns the
+ * topic: the one in its ARN, also when the topic does not exist, so a call to another account's
+ * topic is judged as cross-account. A topic whose {@code Policy} attribute is not set is supplied the
+ * default an API-created topic has.
+ *
+ * <p>Keyed on the ARN rather than the request's credential scope, so the same policy decides a call
+ * an AWS service makes to the topic, such as SES publishing an event notification.
+ */
+@ApplicationScoped
+public class SnsResourcePolicyProvider implements ResourcePolicyProvider {
+
+ private static final Pattern ACCOUNT_ID = Pattern.compile("\\d{12}");
+ /** A topic name, as CreateTopic accepts it; subscriptions, endpoints and applications are not topics. */
+ private static final Pattern TOPIC_NAME = Pattern.compile("[A-Za-z0-9_-]{1,256}(\\.fifo)?");
+
+ private final SnsService snsService;
+
+ @Inject
+ public SnsResourcePolicyProvider(SnsService snsService) {
+ this.snsService = snsService;
+ }
+
+ @Override
+ public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
+ if (!AwsArnUtils.isArnFor(resourceArn, "sns")) {
+ return List.of();
+ }
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
+ if (!ACCOUNT_ID.matcher(arn.accountId()).matches() || arn.region().isBlank()
+ || !TOPIC_NAME.matcher(arn.resource()).matches()) {
+ return List.of();
+ }
+ String policy = snsService.findTopicPolicy(resourceArn).orElse(null);
+ return List.of(new ResourcePolicy(policy, arn.accountId()));
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
index c55570891f..41bf31eaa1 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
@@ -65,6 +65,7 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
+import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@@ -638,16 +639,36 @@ public class SnsService implements Resettable, ResourceProvider {
attrs.putIfAbsent("Owner", regionResolver.getAccountId());
attrs.putIfAbsent("EffectiveDeliveryPolicy", "{\"http\":{\"defaultHealthyRetryPolicy\":{\"minDelayTarget\":20,\"maxDelayTarget\":20,\"numRetries\":3,\"numMaxDelayRetries\":0,\"numNoDelayRetries\":0,\"numMinDelayRetries\":0,\"backoffFunction\":\"linear\"},\"disableSubscriptionOverrides\":false}}");
if (!attrs.containsKey("Policy") || attrs.get("Policy") == null || attrs.get("Policy").isBlank()) {
- attrs.put("Policy", defaultTopicPolicy(topicArn).toString());
+ attrs.put("Policy", defaultTopicPolicy(topicArn, regionResolver.getAccountId()).toString());
}
return attrs;
}
+ /**
+ * The access policy of the topic an ARN names, read in the account and Region the ARN names
+ * rather than the caller's: its {@code Policy} attribute, or the default a new topic has when
+ * that is not set. Empty when there is no such topic.
+ */
+ public Optional<String> findTopicPolicy(String topicArn) {
+ AwsArnUtils.Arn arn = AwsArnUtils.parse(topicArn);
+ String key = topicKey(arn.region(), topicArn);
+ Optional<Topic> topic = topicStore instanceof AccountAwareStorageBackend<Topic> aware
+ ? aware.getForAccountMigratingLegacy(arn.accountId(), key,
+ stored -> topicArn.equals(stored.getTopicArn()))
+ : topicStore.get(key);
+ return topic.map(stored -> {
+ String policy = stored.getAttributes().get("Policy");
+ return policy == null || policy.isBlank()
+ ? defaultTopicPolicy(topicArn, arn.accountId()).toString()
+ : policy;
+ });
+ }
+
/**
* The policy a topic has until one is set, as AWS returns it for a new topic: its owner may
* manage it, subscribe to it and publish to it.
*/
- private ObjectNode defaultTopicPolicy(String topicArn) {
+ private ObjectNode defaultTopicPolicy(String topicArn, String ownerAccountId) {
ObjectNode policy = objectMapper.createObjectNode();
policy.put("Version", "2008-10-17");
policy.put("Id", "__default_policy_ID");
@@ -659,7 +680,7 @@ public class SnsService implements Resettable, ResourceProvider {
DEFAULT_TOPIC_POLICY_ACTIONS.forEach(actions::add);
statement.put("Resource", topicArn);
statement.putObject("Condition").putObject("StringEquals")
- .put("AWS:SourceOwner", regionResolver.getAccountId());
+ .put("AWS:SourceOwner", ownerAccountId);
return policy;
}
@@ -753,7 +774,7 @@ public class SnsService implements Resettable, ResourceProvider {
private ObjectNode topicPolicy(Topic topic, String topicArn) {
String stored = topic.getAttributes().get("Policy");
if (stored == null || stored.isBlank()) {
- return defaultTopicPolicy(topicArn);
+ return defaultTopicPolicy(topicArn, regionResolver.getAccountId());
}
JsonNode parsed;
try {
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java
index 44b8d25a31..c8a6bdabcd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizer.java
@@ -142,8 +142,7 @@ public class LambdaTaskAuthorizer {
// role's own policies have to allow the call too, as they do across accounts anyway.
ResourcePolicyDecision trustGrant = switch (trust) {
case ALLOW -> ResourcePolicyDecision.ALLOW;
- case ALLOW_ACCOUNT -> relationship == ResourceAccountRelationship.CROSS_ACCOUNT
- ? ResourcePolicyDecision.ALLOW : ResourcePolicyDecision.NEUTRAL;
+ case ALLOW_ACCOUNT -> ResourcePolicyDecision.ALLOW_ACCOUNT;
case EXPLICIT_DENY -> ResourcePolicyDecision.EXPLICIT_DENY;
case NEUTRAL -> ResourcePolicyDecision.NEUTRAL;
};
@@ -267,9 +266,10 @@ public class LambdaTaskAuthorizer {
String deniedIn, String kind) {
static ResourceGrant of(ResourcePolicyDecision functionPolicy) {
- boolean allows = functionPolicy == ResourcePolicyDecision.ALLOW
+ boolean sufficient = functionPolicy == ResourcePolicyDecision.ALLOW
|| functionPolicy == ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER;
- return new ResourceGrant(functionPolicy == ResourcePolicyDecision.EXPLICIT_DENY, allows, allows, false,
+ return new ResourceGrant(functionPolicy == ResourcePolicyDecision.EXPLICIT_DENY,
+ sufficient || functionPolicy == ResourcePolicyDecision.ALLOW_ACCOUNT, sufficient, false,
"a resource-based policy", "resource-based policy");
}
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java
index a07ba4cd9c..e196ef4513 100644
--- a/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java
+++ b/src/test/java/io/github/hectorvent/floci/core/common/IamConditionContextResolverTest.java
@@ -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));
diff --git a/src/test/java/io/github/hectorvent/floci/core/common/ServiceCallAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCallAuthorizerTest.java
new file mode 100644
index 0000000000..de85e440cd
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/core/common/ServiceCallAuthorizerTest.java
@@ -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));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
index 06e7c1c572..9ffb173227 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamPolicyEvaluatorTest.java
@@ -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,
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
index 7f4dd3f00c..532d3229d8 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java
@@ -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();
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublisherTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublisherTest.java
index d2b30456f2..00f1eba5ff 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublisherTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesEventPublisherTest.java
@@ -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",
+ "[email protected]", "arn:aws:ses:us-east-1:" + ACCOUNT + ":identity/[email protected]",
+ ACCOUNT, "subj", List.of("[email protected]"), null, null, List.of("[email protected]"), null, null,
+ Instant.parse("2026-01-01T00:00:00Z"), "us-east-1");
+ }
+
+ /** A bounce from {@code [email protected]}, whose domain names the topic. */
+ private boolean publishBounceNotification() {
+ return publisher.publishIdentityNotification(TOPIC_ARN, DOMAIN_ARN, false,
+ SesRecipientEvent.of("BOUNCE", Cause.SIMULATOR, List.of("[email protected]")),
+ "msg-bounce", "[email protected]", "arn:aws:ses:us-east-1:" + ACCOUNT + ":identity/[email protected]",
+ ACCOUNT, "subj", List.of("[email protected]"), null, null,
+ List.of("[email protected]"), 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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java
index ecc8fce37d..51ea1a1a38 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityNotificationTopicPublishV1IntegrationTest.java
@@ -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 = "[email protected]";
+ 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, "[email protected]", "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)
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
index 14f3a13faf..84df7bb21e 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesIdentityServiceTest.java
@@ -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("[email protected]", REGION);
+ for (String type : List.of("Bounce", "Complaint", "Delivery")) {
+ service.setIdentityNotificationTopic("[email protected]", type, TOPIC, REGION);
+ }
+ service.setFeedbackForwardingEnabled("[email protected]", false, REGION);
+
+ service.dropRefusedNotificationTopic("[email protected]", TOPIC, REGION);
+
+ Identity identity = service.find("[email protected]", 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("[email protected]", REGION);
+ service.setIdentityNotificationTopic("[email protected]", "Bounce", TOPIC, REGION);
+ service.setIdentityNotificationTopic("[email protected]", "Complaint", OTHER_TOPIC, REGION);
+
+ service.dropRefusedNotificationTopic("[email protected]", TOPIC, REGION);
+
+ Identity identity = service.find("[email protected]", REGION).orElseThrow();
+ assertFalse(identity.getNotificationAttributes().containsKey("BounceTopic"));
+ assertEquals(OTHER_TOPIC, identity.getNotificationAttributes().get("ComplaintTopic"));
+ }
+
+ @Test
+ void aTopicNamedOnlyForDeliveriesStaysConfigured() {
+ service.verifyEmailIdentity("[email protected]", REGION);
+ service.setIdentityNotificationTopic("[email protected]", "Delivery", TOPIC, REGION);
+ service.setFeedbackForwardingEnabled("[email protected]", false, REGION);
+
+ service.dropRefusedNotificationTopic("[email protected]", TOPIC, REGION);
+
+ Identity identity = service.find("[email protected]", REGION).orElseThrow();
+ assertEquals(TOPIC, identity.getNotificationAttributes().get("DeliveryTopic"));
+ assertFalse(identity.isFeedbackForwardingEnabled());
+ }
+
+ @Test
+ void aTopicSetAgainSinceTheRefusalIsKept() {
+ service.verifyEmailIdentity("[email protected]", REGION);
+ service.setIdentityNotificationTopic("[email protected]", "Bounce", OTHER_TOPIC, REGION);
+ service.setFeedbackForwardingEnabled("[email protected]", false, REGION);
+
+ service.dropRefusedNotificationTopic("[email protected]", TOPIC, REGION);
+
+ Identity identity = service.find("[email protected]", 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(
+ "[email protected]", "Bounce", OTHER_TOPIC, REGION),
+ (Predicate<Identity>) identity ->
+ OTHER_TOPIC.equals(identity.getNotificationAttributes().get("BounceTopic"))),
+ Arguments.of("feedback forwarding",
+ (Consumer<SesIdentityService>) identities -> identities.setFeedbackForwardingEnabled(
+ "[email protected]", false, REGION),
+ (Predicate<Identity>) identity -> !identity.isFeedbackForwardingEnabled()),
+ Arguments.of("headers in notifications",
+ (Consumer<SesIdentityService>) identities -> identities.setHeadersInNotificationsEnabled(
+ "[email protected]", "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("[email protected]", REGION);
+ parked.setIdentityNotificationTopic("[email protected]", "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("[email protected]", 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("[email protected]", REGION).orElseThrow()),
+ "setting " + setting + " was lost");
+ }
+
@Test
void tags_lifecycle_andNotFoundMessage() {
service.verifyEmailIdentity("[email protected]", REGION);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java
index 941e084f65..97aed430f3 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesReceiptRuleServiceTest.java
@@ -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);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ses/SesSnsPublishAuthorizationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ses/SesSnsPublishAuthorizationIntegrationTest.java
new file mode 100644
index 0000000000..40001e59b4
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/ses/SesSnsPublishAuthorizationIntegrationTest.java
@@ -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 = "[email protected]";
+ private static final String SUCCESS = "[email protected]";
+
+ @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();
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsResourcePolicyProviderTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsResourcePolicyProviderTest.java
new file mode 100644
index 0000000000..c7c0d3be54
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsResourcePolicyProviderTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
index 8aab5b2e3c..fee027b9d6 100644
--- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
@@ -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));
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsTopicPolicyEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsTopicPolicyEnforcementIntegrationTest.java
new file mode 100644
index 0000000000..e28dfd0099
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsTopicPolicyEnforcementIntegrationTest.java
@@ -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);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java
index ac0004074a..39f3caddbf 100644
--- a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/LambdaTaskAuthorizerTest.java
@@ -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, """
diff --git a/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java b/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java
index e3789e9043..d14ed09122 100644
--- a/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java
+++ b/src/test/java/io/github/hectorvent/floci/testing/EnforcementFixtures.java
@@ -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)