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

With IAM enforcement on, AssumeRole matched a trust policy on its Action and
Principal only. The Condition block was never read and the ExternalId request
parameter was ignored, so a role guarded by sts:ExternalId, the documented
confused-deputy guard, could be assumed without it, and a conditional Deny
applied whether or not its condition held.

Trust-policy conditions now go through IamPolicyEvaluator's condition engine,
through a new package-private conditionMatches, so they get the same operators
as identity and resource policies. The request context holds sts:RoleSessionName,
sts:ExternalId when the caller sends one, the global keys the enforcement filter
already provides, and aws:PrincipalArn.

A role session is now matched as the role that issued it, through that role's
own ARN, path included. AssumeRole records it on the session when it issues
one, and a new IamService.resolvePrincipalArn reads it back as is, so an old
session keeps naming its role even after a same-named role replaces it. The
evaluator used to rebuild the role ARN from
the assumed-role session ARN, which names the role without its path, so a
session of role/team/App was compared as role/App: a Principal naming the role
refused it, and a condition on aws:PrincipalArn saw the wrong value. IAM stores
a Principal naming a role as the role's unique ID, and aws:PrincipalArn is the
ARN of the role that was assumed, so both are the full role ARN.

A negated operator on an absent key now holds, as the IAM User Guide says for
every condition operator but the IfExists forms and Null: "If the policy
condition requires that the key is not matched, such as StringNotLike or
ArnNotLike, and the right key is not present, the condition is true."
evaluateConditionBlock failed every operator on an absent key, so once trust
conditions were evaluated a Deny with StringNotEquals on sts:ExternalId stopped
refusing a call that omits ExternalId. The change is in the shared engine, so
identity, resource and SCP conditions get the same rule; the set operators keep
their own rule for an absent key.

The AppSync service-trust path from #4555 had its own small condition evaluator
for aws:SourceArn and aws:SourceAccount. It now uses the same engine with those
two keys as its context, which also makes negated operators such as
StringNotEquals work there instead of refusing the document. A Condition that
is not an object of non-empty operator objects still invalidates the whole
trust document, now on every path.

The trust check also resolved the caller's account from the Authorization
header alone, where only a 12-digit key names an account. An IAM user's or a
role session's key, and any presigned request, therefore counted as the default
account and could assume a role that trusts only that account. The check now
uses the account the request was resolved to, and reads a presigned caller's
key from X-Amz-Credential.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-09-30 17:39:45 -05:00
1 parent 55d37cfc41
commit 4e2c1d11ff
12 files changed
+603 -183

No files matched your search

@@ -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
@@ -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);
@@ -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()));
}
}
@@ -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";
}
}
@@ -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