Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(sts): evaluate AssumeRole trust-policy conditions against the real caller (#4716)

Priamo Germosen4e2c1d11ffe6
diff --git a/docs/services/iam.md b/docs/services/iam.md
index 3b7b922e56..1b7c17e504 100644
--- a/docs/services/iam.md
+++ b/docs/services/iam.md
@@ -714,7 +714,10 @@ floci populates:
operator on an absent key makes the whole statement *not apply*: it neither matches nor
blocks. A `DenyRootUser`-style guardrail keyed on `aws:PrincipalArn` therefore fires against
the account root the same way it does on real AWS, consistent with the account root already
-being bounded by SCPs (below): both forms of root enforcement now agree.
+being bounded by SCPs (below): both forms of root enforcement now agree. A negated operator
+(`StringNotEquals`, `ArnNotLike`, `NotIpAddress` and the rest) is the exception, as on AWS: an
+absent key cannot equal what the policy names, so the condition holds, and a `Deny` written
+that way applies when the key is missing.
**Caveat:** `resolveCallerArn` hardcodes the assumed-role session name as `floci-session`,
so `aws:PrincipalArn` for an assumed-role caller will not match a condition that pins a
diff --git a/docs/services/sts.md b/docs/services/sts.md
index ff5c68ed29..cfbf738fee 100644
--- a/docs/services/sts.md
+++ b/docs/services/sts.md
@@ -30,14 +30,27 @@ explicit `Deny` always wins. Both `Action` and `NotAction` elements are honored
`sts:AssumeRole`. Roles that Floci has no record of stay permissive, so this only affects roles
created through IAM with a real trust policy.
+The caller is the account that owns the request's credentials, whether they sign the
+`Authorization` header or a presigned query string: an IAM user's or a role session's access key
+belongs to its own account, not to the default one. A role session matches a `Principal` that
+names its session ARN or its role's ARN, path included.
+
+`Condition` blocks are evaluated with the same operators as identity and resource policies. The
+request context holds `sts:RoleSessionName`, `sts:ExternalId` when the caller passes `ExternalId`,
+`aws:PrincipalArn` (for a caller using assumed-role credentials, the role's ARN with its path, as on AWS),
+`aws:PrincipalAccount`, `aws:ResourceAccount`, `aws:RequestedRegion` and
+`aws:PrincipalIsAWSService`. A trust policy that requires `sts:ExternalId`, the confused-deputy
+guard, refuses a call that omits it or passes another value, and a conditional `Deny` applies only
+when its condition matches.
+
### Known limitations
-- **`Condition` blocks are not evaluated for `AssumeRole`.** A trust policy that requires
- `sts:ExternalId` (the confused-deputy guard) is matched on its principal alone, so the role is
- assumable without passing `ExternalId`, and the `ExternalId` request parameter is ignored. This
- matches moto/LocalStack. Conditions *are* evaluated on the `AssumeRoleWithWebIdentity` path (see below).
-- **Only the trust policy is checked.** Cross-account `AssumeRole` in AWS also requires the caller's
- own identity policy to allow `sts:AssumeRole`; that side is not enforced.
+- **Session tags and source identity are not modelled.** `aws:RequestTag/*`, `aws:TagKeys`,
+ `sts:TransitiveTagKeys` and `sts:SourceIdentity` are not in the request context, so a condition
+ on them does not match, and `sts:TagSession` and `sts:SetSourceIdentity` are not checked.
+- **The caller's own permission is checked against `*`.** The caller's identity policy must allow
+ `sts:AssumeRole`, but it is evaluated for resource `*` rather than the role's ARN, so a policy
+ that names the role in `Resource` does not grant it.
## Web Identity Validation (IRSA)
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
index 21243da4c8..c2268dfddd 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java
@@ -8,8 +8,8 @@ import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
-import java.util.Iterator;
-import java.util.Locale;
+import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -20,14 +20,16 @@ import java.util.regex.Pattern;
*
* <p>Trust policies are principal-centric and carry no {@code Resource} element, so they cannot be
* evaluated by {@link IamPolicyEvaluator} (which is identity/resource oriented). This focused
- * evaluator matches each statement's {@code Action} and {@code Principal} against the caller and
- * applies AWS precedence: an explicit {@code Deny} wins, otherwise a matching {@code Allow} grants.
+ * evaluator matches each statement's {@code Action} and {@code Principal} against the caller, hands
+ * its {@code Condition} to {@link IamPolicyEvaluator#conditionMatches} with the request's context,
+ * and applies AWS precedence: an explicit {@code Deny} wins, otherwise a matching {@code Allow}
+ * grants.
*
* <p>Only AWS principals are modeled (account-root, bare account id, exact principal ARN, and
* {@code "*"}); {@code Service} and {@code Federated} principals never match a SigV4 caller and are
- * ignored. A caller using assumed-role temporary credentials (whose ARN is an STS
- * {@code assumed-role} ARN) also matches a trust policy that names the underlying IAM role ARN, as
- * AWS resolves the session back to its role for trust-policy evaluation.
+ * ignored. A caller using assumed-role temporary credentials matches a trust policy that names its
+ * session ARN or its role: IAM stores a {@code Principal} naming a role as the role's unique ID, so
+ * the session matches through the role's own ARN, path included, which the caller passes in.
*/
@ApplicationScoped
public class AssumeRolePolicyEvaluator {
@@ -36,23 +38,30 @@ public class AssumeRolePolicyEvaluator {
private static final String ASSUME_ROLE_ACTION = "sts:AssumeRole";
private static final Pattern ACCOUNT_ROOT_ARN =
Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::(\\d{12}):root$");
- private static final Pattern ASSUMED_ROLE_ARN = Pattern.compile(
- "^arn:(" + AwsArnUtils.PARTITION_REGEX + "):sts::(\\d{12}):assumed-role/([^/]+)/.*$");
private final ObjectMapper objectMapper;
+ private final IamPolicyEvaluator policyEvaluator;
@Inject
- public AssumeRolePolicyEvaluator(ObjectMapper objectMapper) {
+ public AssumeRolePolicyEvaluator(ObjectMapper objectMapper, IamPolicyEvaluator policyEvaluator) {
this.objectMapper = objectMapper;
+ this.policyEvaluator = policyEvaluator;
}
/**
* Returns true if {@code trustPolicyDocument} allows the caller (identified by
* {@code callerArn}, in {@code callerAccount}) to perform {@code sts:AssumeRole}.
*
+ * <p>{@code principalArn} is the caller's IAM identity: the user's ARN, or for a role session
+ * the role's own ARN, path included, which the session ARN does not carry. A {@code Principal}
+ * naming a role is matched against it, and it is the request's {@code aws:PrincipalArn}.
+ * {@code requestContext} holds the other condition keys the request carries, such as
+ * {@code sts:ExternalId}; each statement's {@code Condition} is evaluated against both.
+ *
* <p>A null/blank/unparseable document or one with no matching {@code Allow} denies.
*/
- public boolean allows(String trustPolicyDocument, String callerArn, String callerAccount) {
+ public boolean allows(String trustPolicyDocument, String callerArn, String principalArn,
+ String callerAccount, Map<String, List<String>> requestContext) {
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
return false;
}
@@ -63,21 +72,24 @@ public class AssumeRolePolicyEvaluator {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return false;
}
- if (!hasValidEffects(statements)) {
+ if (!isWellFormed(statements)) {
return false;
}
-
+ Map<String, List<String>> context = new HashMap<>(requestContext);
+ if (principalArn != null) {
+ context.put("aws:PrincipalArn", List.of(principalArn));
+ }
boolean allow = false;
if (statements.isArray()) {
for (JsonNode stmt : statements) {
- switch (evaluateStatement(stmt, callerArn, callerAccount)) {
+ switch (evaluateStatement(stmt, callerArn, principalArn, callerAccount, context)) {
case DENY -> { return false; }
case ALLOW -> allow = true;
case NO_MATCH -> { }
}
}
} else if (statements.isObject()) {
- return evaluateStatement(statements, callerArn, callerAccount) == Match.ALLOW;
+ return evaluateStatement(statements, callerArn, principalArn, callerAccount, context) == Match.ALLOW;
}
return allow;
}
@@ -96,7 +108,7 @@ public class AssumeRolePolicyEvaluator {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return false;
}
- if (!hasValidEffects(statements)) {
+ if (!isWellFormed(statements)) {
return false;
}
boolean allow = false;
@@ -116,8 +128,9 @@ public class AssumeRolePolicyEvaluator {
/**
* Checks a service trust policy in the context of an AppSync API. AWS supports narrowing
- * service trust with aws:SourceAccount and aws:SourceArn. Unknown condition keys or operators
- * are rejected rather than silently turning a conditional Allow into an unconditional one.
+ * service trust with aws:SourceAccount and aws:SourceArn, which form the request context here;
+ * a condition on any other key finds it absent and does not match, so it never turns a
+ * conditional Allow into an unconditional one.
*/
public boolean allowsService(String trustPolicyDocument, String servicePrincipal,
String sourceArn, String sourceAccount) {
@@ -131,55 +144,86 @@ public class AssumeRolePolicyEvaluator {
LOG.warnv("Failed to parse trust policy: {0}", e.getMessage());
return false;
}
- if (!hasValidEffects(statements)) {
+ if (!isWellFormed(statements)) {
return false;
}
+ Map<String, List<String>> context = new HashMap<>();
+ if (sourceArn != null) {
+ context.put("aws:SourceArn", List.of(sourceArn));
+ }
+ if (sourceAccount != null) {
+ context.put("aws:SourceAccount", List.of(sourceAccount));
+ }
boolean allow = false;
if (statements.isArray()) {
for (JsonNode statement : statements) {
- switch (evaluateServiceStatement(statement, servicePrincipal, sourceArn, sourceAccount)) {
+ switch (evaluateServiceStatement(statement, servicePrincipal, context)) {
case DENY -> { return false; }
case ALLOW -> allow = true;
case NO_MATCH -> { }
}
}
} else if (statements.isObject()) {
- return evaluateServiceStatement(statements, servicePrincipal,
- sourceArn, sourceAccount) == Match.ALLOW;
+ return evaluateServiceStatement(statements, servicePrincipal, context) == Match.ALLOW;
}
return allow;
}
private enum Match { ALLOW, DENY, NO_MATCH }
- private boolean hasValidEffects(JsonNode statements) {
+ /**
+ * A statement without a valid {@code Effect}, or with a {@code Condition} that is not an object
+ * of non-empty operator objects, invalidates the whole document. IAM refuses such a document
+ * when it is written; Floci stores it as given, so it is refused here instead of being read as
+ * a statement with no condition.
+ */
+ private boolean isWellFormed(JsonNode statements) {
if (statements.isArray()) {
if (statements.isEmpty()) {
return false;
}
for (JsonNode statement : statements) {
- if (!validEffect(statement)) {
+ if (!validStatement(statement)) {
return false;
}
}
return true;
}
- return validEffect(statements);
+ return validStatement(statements);
}
- private boolean validEffect(JsonNode statement) {
+ private boolean validStatement(JsonNode statement) {
if (!statement.isObject()) {
return false;
}
String effect = statement.path("Effect").asText("");
- return "Allow".equals(effect) || "Deny".equals(effect);
+ if (!"Allow".equals(effect) && !"Deny".equals(effect)) {
+ return false;
+ }
+ JsonNode condition = statement.get("Condition");
+ if (condition == null) {
+ return true;
+ }
+ if (!condition.isObject() || condition.isEmpty()) {
+ return false;
+ }
+ for (JsonNode operator : condition) {
+ if (!operator.isObject() || operator.isEmpty()) {
+ return false;
+ }
+ }
+ return true;
}
- private Match evaluateStatement(JsonNode stmt, String callerArn, String callerAccount) {
+ private Match evaluateStatement(JsonNode stmt, String callerArn, String principalArn,
+ String callerAccount, Map<String, List<String>> context) {
if (!actionApplies(stmt)) {
return Match.NO_MATCH;
}
- if (!matchesPrincipal(stmt.get("Principal"), callerArn, callerAccount)) {
+ if (!matchesPrincipal(stmt.get("Principal"), callerArn, principalArn, callerAccount)) {
+ return Match.NO_MATCH;
+ }
+ if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context)) {
return Match.NO_MATCH;
}
return effectOf(stmt);
@@ -193,13 +237,12 @@ public class AssumeRolePolicyEvaluator {
}
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal,
- String sourceArn, String sourceAccount) {
+ Map<String, List<String>> context) {
if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
return Match.NO_MATCH;
}
- Match condition = serviceCondition(stmt.get("Condition"), sourceArn, sourceAccount);
- if (condition != Match.ALLOW) {
- return condition;
+ if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context)) {
+ return Match.NO_MATCH;
}
return effectOf(stmt);
}
@@ -212,64 +255,6 @@ public class AssumeRolePolicyEvaluator {
};
}
- /** ALLOW means the condition matches, NO_MATCH means it does not, DENY means unsupported. */
- private Match serviceCondition(JsonNode condition, String sourceArn, String sourceAccount) {
- if (condition == null) {
- return Match.ALLOW;
- }
- if (!condition.isObject() || condition.isEmpty()) {
- return Match.DENY;
- }
- for (Iterator<Map.Entry<String, JsonNode>> operators = condition.fields();
- operators.hasNext();) {
- Map.Entry<String, JsonNode> operator = operators.next();
- if (!"StringEquals".equals(operator.getKey()) && !"StringLike".equals(operator.getKey())
- && !"ArnEquals".equals(operator.getKey()) && !"ArnLike".equals(operator.getKey())) {
- return Match.DENY;
- }
- if (!operator.getValue().isObject() || operator.getValue().isEmpty()) {
- return Match.DENY;
- }
- for (Iterator<Map.Entry<String, JsonNode>> keys = operator.getValue().fields();
- keys.hasNext();) {
- Map.Entry<String, JsonNode> key = keys.next();
- String actual = switch (key.getKey().toLowerCase(Locale.ROOT)) {
- case "aws:sourcearn" -> sourceArn;
- case "aws:sourceaccount" -> sourceAccount;
- default -> null;
- };
- if (!"aws:sourcearn".equalsIgnoreCase(key.getKey())
- && !"aws:sourceaccount".equalsIgnoreCase(key.getKey())) {
- return Match.DENY;
- }
- if (actual == null || !matchesServiceConditionValue(operator.getKey(), key.getValue(), actual)) {
- return Match.NO_MATCH;
- }
- }
- }
- return Match.ALLOW;
- }
-
- private boolean matchesServiceConditionValue(String operator, JsonNode values, String actual) {
- if (values.isArray()) {
- for (JsonNode value : values) {
- if (matchesServiceConditionValue(operator, value, actual)) {
- return true;
- }
- }
- return false;
- }
- if (!values.isTextual()) {
- return false;
- }
- return switch (operator) {
- case "StringEquals" -> values.asText().equals(actual);
- case "StringLike" -> IamPolicyEvaluator.caseSensitiveGlobMatches(values.asText(), actual);
- case "ArnEquals", "ArnLike" -> IamPolicyEvaluator.matchesArnCondition(values.asText(), actual);
- default -> false;
- };
- }
-
private boolean matchesServicePrincipal(JsonNode principalNode, String servicePrincipal) {
if (principalNode == null || servicePrincipal == null) {
return false;
@@ -330,7 +315,8 @@ public class AssumeRolePolicyEvaluator {
return false;
}
- private boolean matchesPrincipal(JsonNode principalNode, String callerArn, String callerAccount) {
+ private boolean matchesPrincipal(JsonNode principalNode, String callerArn, String principalArn,
+ String callerAccount) {
if (principalNode == null) {
return false;
}
@@ -347,11 +333,12 @@ public class AssumeRolePolicyEvaluator {
return false;
}
if (aws.isTextual()) {
- return matchesAwsPrincipal(aws.asText(), callerArn, callerAccount);
+ return matchesAwsPrincipal(aws.asText(), callerArn, principalArn, callerAccount);
}
if (aws.isArray()) {
for (JsonNode entry : aws) {
- if (entry.isTextual() && matchesAwsPrincipal(entry.asText(), callerArn, callerAccount)) {
+ if (entry.isTextual()
+ && matchesAwsPrincipal(entry.asText(), callerArn, principalArn, callerAccount)) {
return true;
}
}
@@ -359,7 +346,8 @@ public class AssumeRolePolicyEvaluator {
return false;
}
- private boolean matchesAwsPrincipal(String principal, String callerArn, String callerAccount) {
+ private boolean matchesAwsPrincipal(String principal, String callerArn, String principalArn,
+ String callerAccount) {
if (principal == null) {
return false;
}
@@ -374,36 +362,11 @@ public class AssumeRolePolicyEvaluator {
if (rootMatcher.matches()) {
return rootMatcher.group(1).equals(callerAccount);
}
- // Otherwise an exact (glob-capable) principal ARN.
- if (callerArn == null) {
- return false;
- }
- if (IamPolicyEvaluator.globMatches(principal, callerArn)) {
+ // Otherwise an exact (glob-capable) principal ARN: the caller's own ARN, which for a role
+ // session is its assumed-role session ARN, or the role's ARN for a Principal naming the role.
+ if (callerArn != null && IamPolicyEvaluator.globMatches(principal, callerArn)) {
return true;
}
- // When the caller used assumed-role temporary credentials, callerArn is the STS
- // assumed-role ARN (arn:aws:sts::ACCT:assumed-role/Role/session). A role's trust policy is
- // written with the role's *IAM* principal ARN (arn:aws:iam::ACCT:role/Role) — AWS resolves
- // the session back to the role for trust matching — so also match that canonical form.
- String roleArn = assumedRoleToRoleArn(callerArn);
- return roleArn != null && IamPolicyEvaluator.globMatches(principal, roleArn);
- }
-
- /**
- * Maps an STS assumed-role ARN ({@code arn:aws:sts::ACCT:assumed-role/Role/session}) to the
- * underlying IAM role ARN ({@code arn:aws:iam::ACCT:role/Role}), or {@code null} if {@code arn}
- * is not an assumed-role ARN.
- *
- * <p>The caller's partition is carried across rather than assumed. IAM ARNs are regionless, so
- * {@code Arn.of} cannot derive it, and hardcoding {@code aws} here would rewrite a GovCloud
- * caller into a commercial role ARN that no GovCloud trust policy can match: the caller would
- * be denied a role they are entitled to, with nothing in the response saying why.
- */
- private static String assumedRoleToRoleArn(String arn) {
- Matcher m = ASSUMED_ROLE_ARN.matcher(arn);
- if (!m.matches()) {
- return null;
- }
- return new AwsArnUtils.Arn(m.group(1), "iam", "", m.group(2), "role/" + m.group(3)).toString();
+ return principalArn != null && IamPolicyEvaluator.globMatches(principal, principalArn);
}
}
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 0f6ef2b29e..ba8127e5d2 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
@@ -821,6 +821,17 @@ public class IamPolicyEvaluator {
// Condition evaluation (Phase 4)
// -----------------------------------------------------------------------
+ /**
+ * Evaluates one statement's {@code Condition} element against a request context, with the
+ * same operator semantics as every other policy this class reads. For policies this class
+ * does not match statements for itself: trust policies carry no {@code Resource} element, so
+ * {@link AssumeRolePolicyEvaluator} matches their principal and action and asks here for the
+ * condition.
+ */
+ boolean conditionMatches(JsonNode condition, Map<String, List<String>> conditionCtx) {
+ return matchesConditions(parseConditions(condition), normalizeConditionContext(conditionCtx));
+ }
+
/**
* Evaluates all condition blocks. AND between blocks, OR within each block's value list.
* Returns true if ALL blocks pass (or there are no conditions).
@@ -925,6 +936,12 @@ public class IamPolicyEvaluator {
if (ifExists) {
continue; // key missing + IfExists → pass this key
}
+ // A negated operator asks for the key not to match, and an absent key matches
+ // nothing, so the condition holds (IAM User Guide, condition operators). The set
+ // operators keep their own rule for an absent key.
+ if (parsed.quantifier() == SetQuantifier.NONE && isNegatedOperator(baseOp)) {
+ continue;
+ }
return false; // key missing, no IfExists → fail entire block
}
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 52c89ab7c0..d40a3e9b4b 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
@@ -2648,6 +2648,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
return Optional.empty();
}
+ /**
+ * The caller's {@code aws:PrincipalArn}. For an IAM user it is the user's ARN, as
+ * {@link #resolveCallerArn} returns. For a role session AWS reports the ARN of the role that
+ * was assumed, path included, rather than the assumed-role session ARN, which names the role
+ * without its path. That is the ARN the session recorded when it was issued, read back as is:
+ * looking the role up by name would hand an old session the ARN of a same-named role created
+ * after it.
+ */
+ public Optional<String> resolvePrincipalArn(String accessKeyId) {
+ Optional<String> callerArn = resolveCallerArn(accessKeyId);
+ if (callerArn.isEmpty() || accessKeys.get(accessKeyId).isPresent()) {
+ return callerArn;
+ }
+ return findSessionForCallerContext(accessKeyId).map(SessionCredential::getRoleArn);
+ }
+
public Optional<String> resolveCallerUserId(String accessKeyId) {
Optional<SessionCredential> sessionOpt = findSessionForCallerContext(accessKeyId);
if (sessionOpt.isEmpty()) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
index 96ac9618d2..e01a138d4e 100644
--- a/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
+++ b/src/main/java/io/github/hectorvent/floci/services/iam/StsQueryHandler.java
@@ -1,12 +1,14 @@
package io.github.hectorvent.floci.services.iam;
import io.github.hectorvent.floci.config.EmulatorConfig;
+import io.github.hectorvent.floci.core.common.AccountResolver;
import io.github.hectorvent.floci.core.common.AwsArnUtils;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.AwsNamespaces;
import io.github.hectorvent.floci.core.common.AwsQueryController;
import io.github.hectorvent.floci.core.common.AwsQueryResponse;
-import io.github.hectorvent.floci.core.common.AccountResolver;
+import io.github.hectorvent.floci.core.common.IamConditionContextResolver;
+import io.github.hectorvent.floci.core.common.IamEnforcementFilter;
import io.github.hectorvent.floci.core.common.OidcIssuerKeyLookup;
import io.github.hectorvent.floci.core.common.RegionResolver;
import io.github.hectorvent.floci.core.common.WebIdentityToken;
@@ -19,6 +21,7 @@ import jakarta.ws.rs.core.Context;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MultivaluedMap;
import jakarta.ws.rs.core.Response;
+import jakarta.ws.rs.core.UriInfo;
import org.jboss.logging.Logger;
import java.security.SecureRandom;
@@ -59,6 +62,9 @@ public class StsQueryHandler {
@Context
HttpHeaders headers;
+ @Context
+ UriInfo uriInfo;
+
@Inject
public StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver,
EmulatorConfig config, AssumeRolePolicyEvaluator trustPolicyEvaluator,
@@ -119,7 +125,8 @@ public class StsQueryHandler {
String callerAccountId = regionResolver.getAccountId();
String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId);
- Response trustDenied = enforceTrustPolicy(roleArn, roleName, accountId);
+ IamRole role = iamService.findRole(accountId, roleName).orElse(null);
+ Response trustDenied = enforceTrustPolicy(roleArn, role, accountId, params);
if (trustDenied != null) {
return trustDenied;
}
@@ -129,10 +136,13 @@ public class StsQueryHandler {
// Register session so IAM enforcement can resolve the role's policies, RDS/ElastiCache
// IAM token validation can find the temporary secret key, and account routing can map
- // these temporary credentials to the assumed role's account.
+ // these temporary credentials to the assumed role's account. The session records the
+ // role's own ARN, path included: it is the session's aws:PrincipalArn, and it keeps naming
+ // the role that issued the session even if a role of the same name replaces it later.
String sessionPolicy = getParam(params, "Policy");
+ String sessionRoleArn = role != null ? role.getArn() : roleArn;
iamService.registerSession(
- accessKeyId, secretKey, sessionToken, roleArn, expiration, sessionPolicy, callerAccountId,
+ accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, sessionPolicy, callerAccountId,
sessionName, assumedRoleId);
String result = new XmlBuilder()
@@ -150,21 +160,36 @@ public class StsQueryHandler {
* When IAM enforcement is enabled, denies AssumeRole if the target role's trust policy does not
* permit the caller. Returns {@code null} to allow — enforcement disabled, the role is unknown
* to Floci (permissive, backward-compatible), or the caller is permitted.
+ *
+ * <p>The caller's account is the one the request was resolved to from its credentials, signed
+ * in the header or presigned in the query, which for an IAM user or a session is the account
+ * that owns the key rather than the default one. A role session is matched as the role that
+ * issued it, whose ARN keeps the path the session ARN drops. The trust policy's conditions see
+ * the request's keys: the global keys, {@code aws:PrincipalArn}, {@code sts:RoleSessionName},
+ * and {@code sts:ExternalId} when the caller sends one.
*/
- private Response enforceTrustPolicy(String roleArn, String roleName, String roleAccountId) {
- if (!config.services().iam().enforcementEnabled()) {
- return null;
- }
- Optional<IamRole> role = iamService.findRole(roleAccountId, roleName);
- if (role.isEmpty()) {
+ private Response enforceTrustPolicy(String roleArn, IamRole role, String roleAccountId,
+ MultivaluedMap<String, String> params) {
+ if (!config.services().iam().enforcementEnabled() || role == null) {
return null;
}
- String auth = headers == null ? null : headers.getHeaderString("Authorization");
- String callerAccount = accountResolver.resolve(auth);
- String callerArn = iamService.resolveCallerArn(
- auth == null ? null : accountResolver.extractAccessKeyId(auth))
+ String auth = IamEnforcementFilter.requestAuthorization(
+ headers == null ? null : headers.getHeaderString("Authorization"),
+ uriInfo == null ? null : uriInfo.getQueryParameters());
+ String callerAccount = regionResolver.getAccountId();
+ String accessKeyId = auth == null ? null : accountResolver.extractAccessKeyId(auth);
+ String callerArn = iamService.resolveCallerArn(accessKeyId)
.orElse(AwsArnUtils.Arn.of("iam", "", callerAccount, "root").toString());
- if (trustPolicyEvaluator.allows(role.get().getAssumeRolePolicyDocument(), callerArn, callerAccount)) {
+ String principalArn = iamService.resolvePrincipalArn(accessKeyId).orElse(callerArn);
+ Map<String, List<String>> requestContext = IamConditionContextResolver.withGlobalContext(
+ null, roleArn, regionResolver.getRegion(), callerAccount, roleAccountId);
+ requestContext.put("sts:RoleSessionName", List.of(getParam(params, "RoleSessionName")));
+ String externalId = getParam(params, "ExternalId");
+ if (externalId != null) {
+ requestContext.put("sts:ExternalId", List.of(externalId));
+ }
+ if (trustPolicyEvaluator.allows(role.getAssumeRolePolicyDocument(), callerArn, principalArn,
+ callerAccount, requestContext)) {
return null;
}
return AwsQueryResponse.error("AccessDenied",
diff --git a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java
index 73f26e42ab..94fc92e2c5 100644
--- a/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java
+++ b/src/main/java/io/github/hectorvent/floci/services/redshift/proxy/RedshiftRoleAccess.java
@@ -45,7 +45,7 @@ final class RedshiftRoleAccess {
// dependency through the whole proxy chain for this one check.
private static final IamPolicyEvaluator ROLE_POLICY_EVALUATOR = new IamPolicyEvaluator(new ObjectMapper());
private static final AssumeRolePolicyEvaluator ROLE_TRUST_POLICY_EVALUATOR =
- new AssumeRolePolicyEvaluator(new ObjectMapper());
+ new AssumeRolePolicyEvaluator(new ObjectMapper(), ROLE_POLICY_EVALUATOR);
private RedshiftRoleAccess() {
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizerTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizerTest.java
index 38328943f8..8d879827d9 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceAuthorizerTest.java
@@ -39,11 +39,12 @@ class AppSyncDataSourceAuthorizerTest {
private final IamService iam = mock(IamService.class);
private final RegionResolver regionResolver = mock(RegionResolver.class);
private final ObjectMapper mapper = new ObjectMapper();
+ private final IamPolicyEvaluator policyEvaluator = new IamPolicyEvaluator(mapper);
private final EmulatorConfig config = mock(EmulatorConfig.class);
private final EmulatorConfig.ServicesConfig services = mock(EmulatorConfig.ServicesConfig.class);
private final EmulatorConfig.IamServiceConfig iamConfig = mock(EmulatorConfig.IamServiceConfig.class);
private final AppSyncDataSourceAuthorizer authorizer = new AppSyncDataSourceAuthorizer(
- iam, new AssumeRolePolicyEvaluator(mapper), new IamPolicyEvaluator(mapper),
+ iam, new AssumeRolePolicyEvaluator(mapper, policyEvaluator), policyEvaluator,
regionResolver, mapper, config);
@BeforeEach
diff --git a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokersTest.java b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokersTest.java
index 8efa538fc6..b8e8a81ced 100644
--- a/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokersTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/appsync/graphql/datasource/AppSyncDataSourceInvokersTest.java
@@ -95,8 +95,9 @@ class AppSyncDataSourceInvokersTest {
when(services.iam()).thenReturn(iamConfig);
when(iamConfig.enforcementEnabled()).thenReturn(true);
ObjectMapper mapper = new ObjectMapper();
+ IamPolicyEvaluator policyEvaluator = new IamPolicyEvaluator(mapper);
AppSyncDataSourceAuthorizer authorizer = new AppSyncDataSourceAuthorizer(iam,
- new AssumeRolePolicyEvaluator(mapper), new IamPolicyEvaluator(mapper),
+ new AssumeRolePolicyEvaluator(mapper, policyEvaluator), policyEvaluator,
mock(RegionResolver.class), mapper, config);
AppSyncDataSourceInvoker invoker = mock(AppSyncDataSourceInvoker.class);
when(invoker.type()).thenReturn(DataSourceType.AWS_LAMBDA);
@@ -138,8 +139,9 @@ class AppSyncDataSourceInvokersTest {
when(iamConfig.enforcementEnabled()).thenReturn(false);
IamService iam = mock(IamService.class);
ObjectMapper mapper = new ObjectMapper();
+ IamPolicyEvaluator policyEvaluator = new IamPolicyEvaluator(mapper);
AppSyncDataSourceAuthorizer authorizer = new AppSyncDataSourceAuthorizer(iam,
- new AssumeRolePolicyEvaluator(mapper), new IamPolicyEvaluator(mapper),
+ new AssumeRolePolicyEvaluator(mapper, policyEvaluator), policyEvaluator,
mock(RegionResolver.class), mapper, config);
AppSyncDataSourceInvoker invoker = mock(AppSyncDataSourceInvoker.class);
when(invoker.type()).thenReturn(DataSourceType.AWS_LAMBDA);
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java
index fa9da96c19..41b9bbc955 100644
--- a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java
@@ -3,12 +3,17 @@ package io.github.hectorvent.floci.services.iam;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
+import java.util.List;
+import java.util.Map;
+
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class AssumeRolePolicyEvaluatorTest {
- private final AssumeRolePolicyEvaluator evaluator = new AssumeRolePolicyEvaluator(new ObjectMapper());
+ private final ObjectMapper mapper = new ObjectMapper();
+ private final AssumeRolePolicyEvaluator evaluator =
+ new AssumeRolePolicyEvaluator(mapper, new IamPolicyEvaluator(mapper));
private static final String CALLER_ARN = "arn:aws:iam::111111111111:user/alice";
private static final String CALLER_ACCOUNT = "111111111111";
@@ -55,43 +60,48 @@ class AssumeRolePolicyEvaluatorTest {
@Test
void allowsAccountRootPrincipal() {
assertTrue(evaluator.allows(
- trust("{\"AWS\":\"arn:aws:iam::111111111111:root\"}"), CALLER_ARN, CALLER_ACCOUNT));
+ trust("{\"AWS\":\"arn:aws:iam::111111111111:root\"}"),
+ CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void allowsBareAccountPrincipal() {
- assertTrue(evaluator.allows(trust("{\"AWS\":\"111111111111\"}"), CALLER_ARN, CALLER_ACCOUNT));
+ assertTrue(evaluator.allows(trust("{\"AWS\":\"111111111111\"}"),
+ CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void allowsExactPrincipalArn() {
assertTrue(evaluator.allows(
- trust("{\"AWS\":\"arn:aws:iam::111111111111:user/alice\"}"), CALLER_ARN, CALLER_ACCOUNT));
+ trust("{\"AWS\":\"arn:aws:iam::111111111111:user/alice\"}"),
+ CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void allowsWildcardPrincipal() {
- assertTrue(evaluator.allows(trust("\"*\""), CALLER_ARN, CALLER_ACCOUNT));
- assertTrue(evaluator.allows(trust("{\"AWS\":\"*\"}"), CALLER_ARN, CALLER_ACCOUNT));
+ assertTrue(evaluator.allows(trust("\"*\""), CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
+ assertTrue(evaluator.allows(trust("{\"AWS\":\"*\"}"), CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void allowsWhenPrincipalListContainsCaller() {
assertTrue(evaluator.allows(
trust("{\"AWS\":[\"arn:aws:iam::999999999999:root\",\"arn:aws:iam::111111111111:root\"]}"),
- CALLER_ARN, CALLER_ACCOUNT));
+ CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void deniesWhenAccountDoesNotMatch() {
assertFalse(evaluator.allows(
- trust("{\"AWS\":\"arn:aws:iam::999999999999:root\"}"), CALLER_ARN, CALLER_ACCOUNT));
+ trust("{\"AWS\":\"arn:aws:iam::999999999999:root\"}"),
+ CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void deniesWhenPrincipalArnDiffers() {
assertFalse(evaluator.allows(
- trust("{\"AWS\":\"arn:aws:iam::111111111111:user/bob\"}"), CALLER_ARN, CALLER_ACCOUNT));
+ trust("{\"AWS\":\"arn:aws:iam::111111111111:user/bob\"}"),
+ CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -101,7 +111,7 @@ class AssumeRolePolicyEvaluatorTest {
{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":{"AWS":"arn:aws:iam::111111111111:root"},"Action":"sts:AssumeRole"}]}
""";
- assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT));
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -110,7 +120,7 @@ class AssumeRolePolicyEvaluatorTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:TagSession"}]}
""";
- assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT));
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -119,7 +129,7 @@ class AssumeRolePolicyEvaluatorTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:*"}]}
""";
- assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT));
+ assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -130,7 +140,7 @@ class AssumeRolePolicyEvaluatorTest {
{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":{"AWS":"*"},"NotAction":"sts:TagSession"}]}
""";
- assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT));
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -141,7 +151,7 @@ class AssumeRolePolicyEvaluatorTest {
{"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"},
{"Effect":"Deny","Principal":{"AWS":"*"},"NotAction":"sts:AssumeRole"}]}
""";
- assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT));
+ assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -151,18 +161,30 @@ class AssumeRolePolicyEvaluatorTest {
{"Version":"2012-10-17","Statement":[
{"Effect":"Allow","Principal":{"AWS":"111111111111"},"NotAction":"sts:GetSessionToken"}]}
""";
- assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT));
+ assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
void allowsAssumedRoleCallerAgainstRolePrincipalArn() {
// The caller used assumed-role temp creds (callerArn is the STS assumed-role ARN), but the
- // trust policy names the underlying IAM role ARN — the canonical trust-policy form. It must
- // match, since AWS resolves the session back to its role for trust evaluation.
+ // trust policy names the role itself, the canonical trust-policy form, so it matches through
+ // the role's ARN.
String assumedRoleArn = "arn:aws:sts::111111111111:assumed-role/AppRole/session-abc";
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws:iam::111111111111:role/AppRole\"}"),
- assumedRoleArn, CALLER_ACCOUNT));
+ assumedRoleArn, "arn:aws:iam::111111111111:role/AppRole", CALLER_ACCOUNT, Map.of()));
+ }
+
+ @Test
+ void assumedRoleCallerMatchesItsRoleByTheFullArnWithItsPath() {
+ // IAM stores a Principal naming a role as the role's unique ID, so the session matches the
+ // role's own ARN, path included, and not an ARN rebuilt from the session, which has no path.
+ String assumedRoleArn = "arn:aws:sts::111111111111:assumed-role/AppRole/session-abc";
+ String roleArn = "arn:aws:iam::111111111111:role/team/AppRole";
+ assertTrue(evaluator.allows(trust("{\"AWS\":\"arn:aws:iam::111111111111:role/team/AppRole\"}"),
+ assumedRoleArn, roleArn, CALLER_ACCOUNT, Map.of()));
+ assertFalse(evaluator.allows(trust("{\"AWS\":\"arn:aws:iam::111111111111:role/AppRole\"}"),
+ assumedRoleArn, roleArn, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -171,7 +193,7 @@ class AssumeRolePolicyEvaluatorTest {
String assumedRoleArn = "arn:aws:sts::111111111111:assumed-role/AppRole/session-abc";
assertFalse(evaluator.allows(
trust("{\"AWS\":\"arn:aws:iam::111111111111:role/OtherRole\"}"),
- assumedRoleArn, CALLER_ACCOUNT));
+ assumedRoleArn, "arn:aws:iam::111111111111:role/AppRole", CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -180,19 +202,15 @@ class AssumeRolePolicyEvaluatorTest {
String assumedRoleArn = "arn:aws:sts::111111111111:assumed-role/AppRole/session-abc";
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws:sts::111111111111:assumed-role/AppRole/session-abc\"}"),
- assumedRoleArn, CALLER_ACCOUNT));
+ assumedRoleArn, "arn:aws:iam::111111111111:role/AppRole", CALLER_ACCOUNT, Map.of()));
}
@Test
void allowsAssumedRoleCallerAgainstRolePrincipalArnInGovCloud() {
- // The silent-denial case. Resolving the session back to its role used to rebuild the role
- // ARN with a hardcoded "aws" partition, so a GovCloud caller was compared against
- // arn:aws:iam::... and never matched the arn:aws-us-gov:iam::... principal its own trust
- // policy names. AssumeRole was refused with nothing in the response explaining why.
String assumedRoleArn = "arn:aws-us-gov:sts::111111111111:assumed-role/AppRole/session-abc";
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws-us-gov:iam::111111111111:role/AppRole\"}"),
- assumedRoleArn, CALLER_ACCOUNT));
+ assumedRoleArn, "arn:aws-us-gov:iam::111111111111:role/AppRole", CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -200,7 +218,7 @@ class AssumeRolePolicyEvaluatorTest {
String assumedRoleArn = "arn:aws-cn:sts::111111111111:assumed-role/AppRole/session-abc";
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws-cn:iam::111111111111:role/AppRole\"}"),
- assumedRoleArn, CALLER_ACCOUNT));
+ assumedRoleArn, "arn:aws-cn:iam::111111111111:role/AppRole", CALLER_ACCOUNT, Map.of()));
}
/**
@@ -212,20 +230,21 @@ class AssumeRolePolicyEvaluatorTest {
String assumedRoleArn = "arn:aws-us-gov:sts::111111111111:assumed-role/AppRole/session-abc";
assertFalse(evaluator.allows(
trust("{\"AWS\":\"arn:aws:iam::111111111111:role/AppRole\"}"),
- assumedRoleArn, CALLER_ACCOUNT));
+ assumedRoleArn, "arn:aws-us-gov:iam::111111111111:role/AppRole", CALLER_ACCOUNT, Map.of()));
}
@Test
void allowsAccountRootPrincipalInGovCloud() {
+ String userArn = "arn:aws-us-gov:iam::111111111111:user/alice";
assertTrue(evaluator.allows(
trust("{\"AWS\":\"arn:aws-us-gov:iam::111111111111:root\"}"),
- "arn:aws-us-gov:iam::111111111111:user/alice", CALLER_ACCOUNT));
+ userArn, userArn, CALLER_ACCOUNT, Map.of()));
}
@Test
void deniesServiceOnlyPrincipal() {
assertFalse(evaluator.allows(
- trust("{\"Service\":\"lambda.amazonaws.com\"}"), CALLER_ARN, CALLER_ACCOUNT));
+ trust("{\"Service\":\"lambda.amazonaws.com\"}"), CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
@Test
@@ -286,11 +305,94 @@ class AssumeRolePolicyEvaluatorTest {
"arn:aws:lambda:us-east-1:111122223333:function:worker", "111122223333"));
}
+ @Test
+ void externalIdConditionNeedsTheMatchingExternalId() {
+ String doc = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole",
+ "Condition":{"StringEquals":{"sts:ExternalId":"Unique-ID-1"}}}]}
+ """;
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
+ Map.of("sts:ExternalId", List.of("unique-id-1"))));
+ assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
+ Map.of("sts:ExternalId", List.of("Unique-ID-1"))));
+ }
+
+ @Test
+ void denyUnlessExternalIdRefusesACallWithoutOne() {
+ // A negated operator on an absent key holds, so this Deny applies when ExternalId is missing.
+ String doc = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole"},
+ {"Effect":"Deny","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole",
+ "Condition":{"StringNotEquals":{"sts:ExternalId":"Unique-ID-1"}}}]}
+ """;
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
+ Map.of("sts:ExternalId", List.of("other-id"))));
+ assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
+ Map.of("sts:ExternalId", List.of("Unique-ID-1"))));
+ }
+
+ @Test
+ void conditionalDenyAppliesOnlyWhenItsConditionMatches() {
+ String doc = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole"},
+ {"Effect":"Deny","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole",
+ "Condition":{"StringLike":{"sts:RoleSessionName":"blocked-*"}}}]}
+ """;
+ assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
+ Map.of("sts:RoleSessionName", List.of("alice"))));
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT,
+ Map.of("sts:RoleSessionName", List.of("blocked-alice"))));
+ }
+
+ @Test
+ void principalArnConditionSeesTheRoleArnWithItsPath() {
+ String doc = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole",
+ "Condition":{"ArnLike":{"aws:PrincipalArn":"arn:aws:iam::111111111111:role/team/*"}}}]}
+ """;
+ String sessionArn = "arn:aws:sts::111111111111:assumed-role/AppRole/session-abc";
+ assertTrue(evaluator.allows(doc, sessionArn, "arn:aws:iam::111111111111:role/team/AppRole",
+ CALLER_ACCOUNT, Map.of()));
+ assertFalse(evaluator.allows(doc, sessionArn, "arn:aws:iam::111111111111:role/AppRole",
+ CALLER_ACCOUNT, Map.of()));
+ }
+
+ @Test
+ void malformedConditionInvalidatesTheWholeTrustDocument() {
+ String doc = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole"},
+ {"Effect":"Deny","Principal":{"AWS":"111111111111"},"Action":"sts:AssumeRole",
+ "Condition":{"StringEquals":"sts:ExternalId"}}]}
+ """;
+ assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
+ }
+
+ @Test
+ void serviceTrustEvaluatesNegatedSourceConditions() {
+ String doc = """
+ {"Statement":[
+ {"Effect":"Allow","Principal":{"Service":"appsync.amazonaws.com"},"Action":"sts:AssumeRole"},
+ {"Effect":"Deny","Principal":{"Service":"appsync.amazonaws.com"},"Action":"sts:AssumeRole",
+ "Condition":{"StringNotEquals":{"aws:SourceAccount":"000000000000"}}}]}
+ """;
+ assertTrue(evaluator.allowsService(doc, "appsync.amazonaws.com",
+ "arn:aws:appsync:us-east-1:000000000000:apis/example", "000000000000"));
+ assertFalse(evaluator.allowsService(doc, "appsync.amazonaws.com",
+ "arn:aws:appsync:us-east-1:111111111111:apis/example", "111111111111"));
+ }
+
@Test
void deniesBlankOrMalformedDocument() {
- assertFalse(evaluator.allows(null, CALLER_ARN, CALLER_ACCOUNT));
- assertFalse(evaluator.allows("", CALLER_ARN, CALLER_ACCOUNT));
- assertFalse(evaluator.allows("{}", CALLER_ARN, CALLER_ACCOUNT));
- assertFalse(evaluator.allows("not json", CALLER_ARN, CALLER_ACCOUNT));
+ assertFalse(evaluator.allows(null, CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
+ assertFalse(evaluator.allows("", CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
+ assertFalse(evaluator.allows("{}", CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
+ assertFalse(evaluator.allows("not json", CALLER_ARN, CALLER_ARN, CALLER_ACCOUNT, Map.of()));
}
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustConditionsIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustConditionsIntegrationTest.java
new file mode 100644
index 0000000000..ff54867dc6
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustConditionsIntegrationTest.java
@@ -0,0 +1,241 @@
+package io.github.hectorvent.floci.services.iam;
+
+import io.github.hectorvent.floci.testing.IamEnforcementProfile;
+import io.quarkus.test.junit.QuarkusTest;
+import io.quarkus.test.junit.TestProfile;
+import io.restassured.response.Response;
+import io.restassured.specification.RequestSpecification;
+import org.junit.jupiter.api.Test;
+
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.UUID;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+
+/**
+ * With {@code iam.enforcement-enabled=true}, STS AssumeRole evaluates the {@code Condition} block of
+ * the role's trust policy against the request, and matches the principal of the account that owns
+ * the caller's credentials, as AWS does.
+ */
+@QuarkusTest
+@TestProfile(IamEnforcementProfile.class)
+class AssumeRoleTrustConditionsIntegrationTest {
+
+ private static final String ROLE_ACCOUNT = "222222222222";
+ private static final String TRUSTED_ACCOUNT = "111111111111";
+ private static final String OTHER_ACCOUNT = "333333333333";
+ private static final String DEFAULT_ACCOUNT = "000000000000";
+ private static final DateTimeFormatter AMZ_DATE_FMT =
+ DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC);
+
+ @Test
+ void externalIdConditionNeedsTheMatchingExternalId() {
+ String role = createRole("""
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole",
+ "Condition":{"StringEquals":{"sts:ExternalId":"expected-id"}}}]}""".formatted(TRUSTED_ACCOUNT));
+
+ assertTrustDenied(assumeRole(TRUSTED_ACCOUNT, role, "s", null), role);
+ assertTrustDenied(assumeRole(TRUSTED_ACCOUNT, role, "s", "other-id"), role);
+ assumeRole(TRUSTED_ACCOUNT, role, "s", "expected-id").then().statusCode(200);
+ }
+
+ @Test
+ void denyUnlessExternalIdRefusesACallWithoutOne() {
+ String role = createRole("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%1$s:root"},"Action":"sts:AssumeRole"},
+ {"Effect":"Deny","Principal":{"AWS":"arn:aws:iam::%1$s:root"},"Action":"sts:AssumeRole",
+ "Condition":{"StringNotEquals":{"sts:ExternalId":"expected-id"}}}]}""".formatted(TRUSTED_ACCOUNT));
+
+ assertTrustDenied(assumeRole(TRUSTED_ACCOUNT, role, "s", null), role);
+ assertTrustDenied(assumeRole(TRUSTED_ACCOUNT, role, "s", "other-id"), role);
+ assumeRole(TRUSTED_ACCOUNT, role, "s", "expected-id").then().statusCode(200);
+ }
+
+ @Test
+ void conditionalDenyAppliesOnlyWhenItsConditionMatches() {
+ String role = createRole("""
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Principal":{"AWS":"arn:aws:iam::%1$s:root"},"Action":"sts:AssumeRole"},
+ {"Effect":"Deny","Principal":{"AWS":"arn:aws:iam::%1$s:root"},"Action":"sts:AssumeRole",
+ "Condition":{"StringEquals":{"sts:RoleSessionName":"blocked"}}}]}""".formatted(TRUSTED_ACCOUNT));
+
+ assumeRole(TRUSTED_ACCOUNT, role, "allowed-session", null).then().statusCode(200);
+ assertTrustDenied(assumeRole(TRUSTED_ACCOUNT, role, "blocked", null), role);
+ }
+
+ @Test
+ void presignedCallerIsTheCredentialsOwnerNotTheDefaultAccount() {
+ String trustsDefault = createRole(trustAccountRoot(DEFAULT_ACCOUNT));
+ String trustsOwnAccount = createRole(trustAccountRoot(OTHER_ACCOUNT));
+
+ assertTrustDenied(presignedAssumeRole(OTHER_ACCOUNT, trustsDefault), trustsDefault);
+ presignedAssumeRole(OTHER_ACCOUNT, trustsOwnAccount).then().statusCode(200);
+ }
+
+ @Test
+ void userKeyCallerIsTheUsersAccountNotTheDefaultAccount() {
+ String user = "trust-user-" + UUID.randomUUID().toString().substring(0, 8);
+ given().formParam("Action", "CreateUser").formParam("UserName", user)
+ .header("Authorization", auth(OTHER_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ given().formParam("Action", "PutUserPolicy").formParam("UserName", user).formParam("PolicyName", "p")
+ .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":\"sts:AssumeRole\",\"Resource\":\"*\"}]}")
+ .header("Authorization", auth(OTHER_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ String accessKeyId = given().formParam("Action", "CreateAccessKey").formParam("UserName", user)
+ .header("Authorization", auth(OTHER_ACCOUNT, "iam")).when().post("/").then().statusCode(200)
+ .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey.AccessKeyId");
+ String trustsDefault = createRole(trustAccountRoot(DEFAULT_ACCOUNT));
+ String trustsOwnAccount = createRole(trustAccountRoot(OTHER_ACCOUNT));
+
+ assertTrustDenied(assumeRole(accessKeyId, trustsDefault, "s", null), trustsDefault);
+ assumeRole(accessKeyId, trustsOwnAccount, "s", null).then().statusCode(200);
+ }
+
+ @Test
+ void roleSessionIsMatchedAsItsRoleWithItsPath() {
+ String callerRole = "trust-path-" + UUID.randomUUID().toString().substring(0, 8);
+ createCallerRole(callerRole, "/team/");
+ Session session = assumeCallerRole(callerRole, "/team/");
+ String roleArn = "arn:aws:iam::" + TRUSTED_ACCOUNT + ":role/team/" + callerRole;
+ String pathlessArn = "arn:aws:iam::" + TRUSTED_ACCOUNT + ":role/" + callerRole;
+ String condition = """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole",
+ "Condition":{"ArnEquals":{"aws:PrincipalArn":"%s"}}}]}""";
+ String namesRole = createRole(trustPrincipal(roleArn));
+ String namesPathlessRole = createRole(trustPrincipal(pathlessArn));
+ String conditionOnRole = createRole(condition.formatted(TRUSTED_ACCOUNT, roleArn));
+ String conditionOnPathlessRole = createRole(condition.formatted(TRUSTED_ACCOUNT, pathlessArn));
+
+ assumeRoleWithSession(session, namesRole).then().statusCode(200);
+ assertTrustDenied(assumeRoleWithSession(session, namesPathlessRole), namesPathlessRole);
+ assumeRoleWithSession(session, conditionOnRole).then().statusCode(200);
+ assertTrustDenied(assumeRoleWithSession(session, conditionOnPathlessRole), conditionOnPathlessRole);
+ }
+
+ @Test
+ void sessionStillNamesItsRoleAfterASameNamedRoleReplacesIt() {
+ String callerRole = "trust-swap-" + UUID.randomUUID().toString().substring(0, 8);
+ createCallerRole(callerRole, "/team/");
+ Session oldSession = assumeCallerRole(callerRole, "/team/");
+ given().formParam("Action", "DeleteRolePolicy").formParam("RoleName", callerRole).formParam("PolicyName", "p")
+ .header("Authorization", auth(TRUSTED_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ given().formParam("Action", "DeleteRole").formParam("RoleName", callerRole)
+ .header("Authorization", auth(TRUSTED_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ createCallerRole(callerRole, "/other/");
+ String namesReplacement = createRole(
+ trustPrincipal("arn:aws:iam::" + TRUSTED_ACCOUNT + ":role/other/" + callerRole));
+
+ assertTrustDenied(assumeRoleWithSession(oldSession, namesReplacement), namesReplacement);
+ assumeRoleWithSession(assumeCallerRole(callerRole, "/other/"), namesReplacement).then().statusCode(200);
+ }
+
+ private static void assertTrustDenied(Response response, String role) {
+ response.then().statusCode(403)
+ .body(containsString("is not authorized to perform: sts:AssumeRole on resource: arn:aws:iam::"
+ + ROLE_ACCOUNT + ":role/" + role));
+ }
+
+ private static Response assumeRole(String accessKeyId, String role, String sessionName,
+ String externalId) {
+ RequestSpecification spec = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "AssumeRole")
+ .formParam("Version", "2011-06-15")
+ .formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT + ":role/" + role)
+ .formParam("RoleSessionName", sessionName)
+ .header("Authorization", auth(accessKeyId, "sts"));
+ if (externalId != null) {
+ spec.formParam("ExternalId", externalId);
+ }
+ return spec.when().post("/");
+ }
+
+ private record Session(String accessKeyId, String sessionToken) {
+ }
+
+ /** A role in the trusted account that its own account may assume, allowed to call AssumeRole. */
+ private static void createCallerRole(String name, String path) {
+ given().formParam("Action", "CreateRole").formParam("RoleName", name).formParam("Path", path)
+ .formParam("AssumeRolePolicyDocument", trustAccountRoot(TRUSTED_ACCOUNT))
+ .header("Authorization", auth(TRUSTED_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ given().formParam("Action", "PutRolePolicy").formParam("RoleName", name).formParam("PolicyName", "p")
+ .formParam("PolicyDocument", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
+ + "\"Action\":\"sts:AssumeRole\",\"Resource\":\"*\"}]}")
+ .header("Authorization", auth(TRUSTED_ACCOUNT, "iam")).when().post("/").then().statusCode(200);
+ }
+
+ private static Session assumeCallerRole(String name, String path) {
+ Response response = given().formParam("Action", "AssumeRole")
+ .formParam("RoleArn", "arn:aws:iam::" + TRUSTED_ACCOUNT + ":role" + path + name)
+ .formParam("RoleSessionName", "s")
+ .header("Authorization", auth(TRUSTED_ACCOUNT, "sts")).when().post("/");
+ response.then().statusCode(200);
+ return new Session(response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId"),
+ response.path("AssumeRoleResponse.AssumeRoleResult.Credentials.SessionToken"));
+ }
+
+ private static Response assumeRoleWithSession(Session session, String role) {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "AssumeRole")
+ .formParam("Version", "2011-06-15")
+ .formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT + ":role/" + role)
+ .formParam("RoleSessionName", "s")
+ .header("Authorization", auth(session.accessKeyId(), "sts"))
+ .header("X-Amz-Security-Token", session.sessionToken())
+ .when().post("/");
+ }
+
+ private static Response presignedAssumeRole(String accessKeyId, String role) {
+ String amzDate = AMZ_DATE_FMT.format(Instant.now());
+ return given()
+ .queryParam("X-Amz-Algorithm", "AWS4-HMAC-SHA256")
+ .queryParam("X-Amz-Credential", accessKeyId + "/" + amzDate.substring(0, 8) + "/us-east-1/sts/aws4_request")
+ .queryParam("X-Amz-Date", amzDate)
+ .queryParam("X-Amz-Expires", "3600")
+ .queryParam("X-Amz-SignedHeaders", "host")
+ .queryParam("X-Amz-Signature", "abc")
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "AssumeRole")
+ .formParam("Version", "2011-06-15")
+ .formParam("RoleArn", "arn:aws:iam::" + ROLE_ACCOUNT + ":role/" + role)
+ .formParam("RoleSessionName", "s")
+ .when().post("/");
+ }
+
+ private static String trustPrincipal(String principalArn) {
+ return """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":{"AWS":"%s"},"Action":"sts:AssumeRole"}]}""".formatted(principalArn);
+ }
+
+ private static String trustAccountRoot(String account) {
+ return """
+ {"Version":"2012-10-17","Statement":[{"Effect":"Allow",
+ "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":"sts:AssumeRole"}]}""".formatted(account);
+ }
+
+ private static String createRole(String trustPolicy) {
+ String role = "trust-cond-" + UUID.randomUUID().toString().substring(0, 8);
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateRole")
+ .formParam("RoleName", role)
+ .formParam("AssumeRolePolicyDocument", trustPolicy)
+ .header("Authorization", auth(ROLE_ACCOUNT, "iam"))
+ .when().post("/")
+ .then().statusCode(200);
+ return role;
+ }
+
+ private static String auth(String accessKeyId, String service) {
+ return "AWS4-HMAC-SHA256 Credential=" + accessKeyId + "/20260929/us-east-1/" + service
+ + "/aws4_request, SignedHeaders=host, Signature=abc";
+ }
+}
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 e97c8d29b9..52d1ba87c8 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
@@ -417,6 +417,43 @@ class IamPolicyEvaluatorTest {
Map.of("dynamodb:LeadingKeys", List.of("USER_alice"))));
}
+ @Test
+ void negatedOperatorOnAnAbsentKeyHolds() {
+ // IAM User Guide, condition operators: when the condition requires that the key is not
+ // matched and the key is not present, the condition is true. A Deny written that way
+ // applies to a request that does not carry the key.
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"sqs:SendMessage","Resource":"*"},
+ {"Effect":"Deny","Action":"sqs:SendMessage","Resource":"*",
+ "Condition":{"ArnNotLike":{"aws:SourceArn":"arn:aws:sns:us-east-1:111122223333:*"}}}
+ ]}""";
+
+ assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
+ List.of(policy), "sqs:SendMessage", "*", Map.of()));
+ assertEquals(Decision.DENY, evaluator.simulateCustomPolicy(
+ List.of(policy), "sqs:SendMessage", "*",
+ Map.of("aws:SourceArn", List.of("arn:aws:sns:us-east-1:999999999999:topic"))));
+ assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
+ List.of(policy), "sqs:SendMessage", "*",
+ Map.of("aws:SourceArn", List.of("arn:aws:sns:us-east-1:111122223333:topic"))));
+ }
+
+ @Test
+ void negatedSetOperatorOnAnAbsentKeyKeepsTheSetOperatorRule() {
+ // The set operators have their own rule for an absent key: ForAnyValue with a Deny effect
+ // evaluates as no match when the key is not present (IAM User Guide, set operators).
+ String policy = """
+ {"Version":"2012-10-17","Statement":[
+ {"Effect":"Allow","Action":"dynamodb:GetItem","Resource":"*"},
+ {"Effect":"Deny","Action":"dynamodb:GetItem","Resource":"*",
+ "Condition":{"ForAnyValue:StringNotEquals":{"dynamodb:Attributes":["name"]}}}
+ ]}""";
+
+ assertEquals(Decision.ALLOW, evaluator.simulateCustomPolicy(
+ List.of(policy), "dynamodb:GetItem", "*", Map.of()));
+ }
+
@Test
void forAllValuesWithANegatedOperatorAndsAcrossThePolicyValues() {
// The deny-list idiom for dynamodb:Attributes: allow only while none of the