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

Under IAM enforcement, SES published event-destination events and identity notifications to
whatever SNS topic it was configured with, through an internal call nothing checked, so a caller
refused sns:Publish could still put messages on a topic by pointing a configuration set at it. On
AWS, SES publishes as ses.amazonaws.com and the topic's policy decides: it has to allow SES, under
an aws:SourceArn naming the configuration set or identity whose configuration names the topic.

- ServiceCallAuthorizer decides a call one AWS service makes to another's resource on its own
  behalf from the target's resource policy alone, read through the same providers the request
  filter uses and picked by the target ARN's service. A target with no policy refuses, and with
  enforcement off every call is allowed. ResourcePolicyProviders collects what the providers
  supply, for the filter and the authorizer alike.
- IamConditionContextResolver.serviceCallContext builds that call's request context from the IAM
  User Guide's global keys: aws:PrincipalIsAWSService, aws:PrincipalServiceName and
  aws:PrincipalServiceNamesList, aws:SourceArn and aws:SourceAccount, aws:ResourceAccount and
  aws:RequestedRegion, and none of the keys that describe an IAM principal. A publish to an SNS
  topic from SES also carries aws:SourceOwner, which the SNS Developer Guide lists SES among the
  services setting, and which the default topic policy checks.
- SnsResourcePolicyProvider supplies a topic's policy and the account in its ARN, also when the
  topic does not exist. A topic with no Policy attribute gets the default a new topic has, for the
  topic's own account. Topic policies so also take part in a JSON-protocol request that names a
  topic, as any resource policy does.
- SesEventPublisher asks before publishing to SNS: for an event destination with the configuration
  set's ARN, for an identity notification with the ARN of the identity that names the topic, the
  sender's own or its domain's, both with the sending account. A refused event is dropped. A
  notification SES cannot publish, because the topic is gone from its own account or its policy
  refuses SES, also takes the topic out of the identity's bounce and complaint settings and turns
  email feedback forwarding back on, as the SES Developer Guide describes; a delivery setting
  stays. The identity's notification settings are written under the identity lock, so that
  write and an API call changing them cannot lose each other.
- CreateReceiptRule and UpdateReceiptRule ask the same question of an action's TopicArn, with the
  rule's ARN as aws:SourceArn, and answer InvalidSnsTopic when the topic's policy does not let SES
  publish, which the SES API Reference lists as "could not publish to the topic, possibly due to
  permissions issues". The rules still route no mail.
- A resource policy statement that names the caller only through its account, by its id, root ARN
  or S3 canonical user ID, delegates to that account (IAM User Guide, "AWS account principals"):
  across accounts it is still the owner's half of the grant, but within the account it no longer
  grants on its own, and the caller's identity policies have to allow the request. Floci let such
  a statement grant on its own, for bucket and function policies already, so a topic policy naming
  its own account would have let every user of the account publish.
- A Deny's NotPrincipal follows the IAM User Guide ("AWS JSON policy elements: NotPrincipal"): it
  spares an IAM caller only when it names the caller's account as well as the caller, since without
  the account AWS "might deny access to the entire account", and never spares one with a permissions
  boundary attached, which it "will always deny". CallerArns says whether a boundary is attached to
  the user or to the role a session assumed. An Allow's NotPrincipal still grants everyone it does
  not name, as Access Analyzer warns it can.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-14 17:32:55 -05:00
1 parent 17c40cecbd
commit 46f4977b23
34 files changed
+1924 -129

No files matched your search

@@ -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;
@@ -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);
}
/**
@@ -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;
}
}
@@ -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) {
@@ -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();
@@ -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);
}
}
@@ -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;
}
}
@@ -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) {
@@ -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 {
@@ -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);
}
@@ -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");
@@ -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.
@@ -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()));
}
}
@@ -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 {
@@ -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");
}