mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(sts): let a same-account trust policy that names a user grant AssumeRole (#8918)
A role's trust policy now reaches IAM enforcement through a ResourcePolicyProvider, the path every other resource-based policy takes, instead of a branch on sts:AssumeRole in the enforcement filter. RoleTrustPolicyProvider answers an STS action on a role ARN with the role's stored trust policy, each statement that names no Resource given the role's ARN, and with the account in the role's ARN as its owner. IAM actions on the role, such as iam:GetRole and iam:PassRole, get nothing from it. evaluateResourcePolicyFor already returns ALLOW_DIRECT_IAM_USER for an Allow naming the caller's user ARN, so a same-account grant to a user is unchanged, and AssumeRolePolicyEvaluator.grantsToIamUser and its request-key helper are removed. Within the role's account, an Allow naming a role session's role, or "*", now grants the call too, as any same-account resource-based policy does. Across accounts the filter needs the trust policy's Allow beside the caller's identity policy, so it refuses an IAM user or a role session the trust policy does not allow before STS does, with its own AccessDenied message; AssumeRoleTrustConditionsIntegrationTest checks that message for those callers. The STS guide's sentence that the caller's identity policy must allow sts:AssumeRole now names the same-account exception.
This commit is contained in:
1 parent
3aba098ee8
commit
b8632351e8
7 files changed
+505
-18
No files matched your search
@@ -3036,6 +3036,7 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED` is active, Floci also queries regi
|
||||
- Aurora DSQL cluster policies take part the same way for a control plane call on the cluster, and when a client connects to the cluster's endpoint. See [DSQL](dsql.md#authentication).
|
||||
- SQS queue policies take part the same way for a call on the queue; see [SQS](sqs.md#queue-policies-under-iam-enforcement).
|
||||
- EventBridge event bus policies, the statements `PutPermission` adds, take part the same way for a call on the bus; see [EventBridge](eventbridge.md#event-bus-policies-under-iam-enforcement).
|
||||
- A role's trust policy takes part the same way for `sts:AssumeRole` on the role, with the role as its resource: a trust policy names no `Resource`. It is not consulted for IAM actions on the role, such as `iam:GetRole` or `iam:PassRole`. See [STS trust policy enforcement](sts.md#trust-policy-enforcement).
|
||||
- API Gateway REST API policies are stored but not evaluated.
|
||||
- A call an AWS service makes to another service's resource on its own behalf, such as SES publishing an event or a notification to an SNS topic, has no IAM principal, so the target's resource policy decides it alone and has to allow the calling service, through `{"Service": "<service>.amazonaws.com"}` or `{"AWS": "*"}`. A target with no policy refuses it. Its request context holds `aws:PrincipalIsAWSService` (`true`), `aws:PrincipalServiceName` and `aws:PrincipalServiceNamesList`, `aws:SourceArn` and `aws:SourceAccount` for the resource whose configuration triggered the call, `aws:ResourceAccount` and `aws:RequestedRegion`, and none of the keys that describe an IAM principal. A publish to an SNS topic from SES also carries `aws:SourceOwner`, the key the SNS Developer Guide lists SES among the services setting, which is what the default topic policy checks, so that policy admits SES acting for the topic owner's account and no other. SES and Lambda, when it reads the code of a Web Function revision from S3, are the services checked this way so far; see [SES IAM enforcement](ses.md#iam-enforcement) and [Lambda Web Functions](lambda-web-functions.md#emulation-behavior).
|
||||
|
||||
|
||||
+22
-1
@@ -392,7 +392,8 @@ When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, `AssumeRole` also evaluates
|
||||
(`AssumeRolePolicyDocument`) against the caller and returns `AccessDenied` if it is not permitted. AWS principal
|
||||
forms are matched: `"*"`, an account id, an account-root ARN (`arn:aws:iam::<acct>:root`), and exact principal ARNs;
|
||||
and an explicit `Deny` always wins. Both `Action` and `NotAction` elements are honored when matching `sts:AssumeRole`.
|
||||
The caller's own identity policy must allow `sts:AssumeRole` too, evaluated against the role's ARN, so a policy can
|
||||
Unless the trust policy grants the call on its own within the role's account (below), the caller's own identity
|
||||
policy must allow `sts:AssumeRole` too, evaluated against the role's ARN, so a policy can
|
||||
allow assuming one role and not another. Other STS actions are evaluated against `*`, whatever `RoleArn` they carry.
|
||||
That evaluation sees the request's `sts:RoleSessionName`, and `sts:ExternalId` when the caller passes `ExternalId`,
|
||||
as the trust policy does: the [Service Authorization Reference](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssecuritytokenservice.html)
|
||||
@@ -400,6 +401,26 @@ lists both among the condition keys of `AssumeRole`, so an identity policy can r
|
||||
`"sts:RoleSessionName": "${aws:username}"`, or an external ID, and a `Deny` conditioned on either applies only when
|
||||
it matches.
|
||||
|
||||
The trust policy is the role's resource-based policy, and IAM enforcement evaluates it as it does a bucket or a
|
||||
queue policy, with the role as its resource, since a trust policy names no `Resource`. Within the role's account, an
|
||||
`Allow` that names the caller grants the call without an identity policy of the caller's: the
|
||||
[AssumeRole API reference](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRole.html) lets a user
|
||||
assume a role in the same account either through "a policy to the user that allows the user to call `AssumeRole`
|
||||
(as long as the role's trust policy trusts the account)" or by adding "the user as a principal directly in the
|
||||
role's trust policy", because "the role's trust policy acts as an IAM resource-based policy. When a resource-based
|
||||
policy grants access to a principal in the same account, no additional identity-based policy is required". The same
|
||||
holds for a role session whose role, or session, the trust policy names, and for `"*"`. A grant to an IAM user's
|
||||
exact ARN is not limited by the user's permissions boundary either
|
||||
([policy evaluation logic](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic_policy-eval-denyallow.html):
|
||||
"not limited by an implicit deny in an identity-based policy or permissions boundary"), while a grant to a role's
|
||||
ARN is ("limited by an implicit deny in a permissions boundary or session policy"). A trust policy that names the
|
||||
account (its id or its root ARN) still needs the caller's identity policy. For a role in another account, both the
|
||||
caller's identity policy and the trust policy have to allow the call
|
||||
([cross-account policy evaluation](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic-cross-account.html):
|
||||
"The request is allowed only if both evaluations return a decision of `Allow`"), so IAM enforcement refuses an IAM
|
||||
user or a role session the trust policy does not allow before STS does. An explicit `Deny` in the trust policy, in
|
||||
any of the caller's policies or in the account's SCPs refuses the call.
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ArrayNode;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import io.floci.aws.core.common.AccountResolver;
|
||||
import io.floci.aws.core.common.AwsArnUtils;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Supplies a role's trust policy to IAM policy evaluation as the role's resource-based policy, for
|
||||
* the STS actions that name the role, together with the account that owns the role: the one in its
|
||||
* ARN, also when the role does not exist or its trust policy cannot be read, so assuming another
|
||||
* account's role is judged as cross-account.
|
||||
*
|
||||
* <p>The STS API Reference (AssumeRole) says "the role's trust policy acts as an IAM resource-based
|
||||
* policy". A trust policy names no {@code Resource}, the role it is attached to being its resource,
|
||||
* so each statement that names none is given the role's ARN. IAM actions on the role, such as
|
||||
* {@code iam:GetRole} or {@code iam:PassRole}, are not governed by its trust policy and get nothing
|
||||
* here.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class RoleTrustPolicyProvider implements ResourcePolicyProvider {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(RoleTrustPolicyProvider.class);
|
||||
private static final String ROLE_PREFIX = "role/";
|
||||
private static final String STS_ACTION_PREFIX = "sts:";
|
||||
|
||||
private final IamService iamService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Inject
|
||||
public RoleTrustPolicyProvider(IamService iamService, ObjectMapper objectMapper) {
|
||||
this.iamService = iamService;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String resourceArn) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ResourcePolicy> getResourcePolicies(String credentialScope, String action, String resourceArn) {
|
||||
if (action == null || !action.startsWith(STS_ACTION_PREFIX) || !AwsArnUtils.isArnFor(resourceArn, "iam")) {
|
||||
return List.of();
|
||||
}
|
||||
AwsArnUtils.Arn arn = AwsArnUtils.parse(resourceArn);
|
||||
String target = arn.resource();
|
||||
if (!AccountResolver.isAccountId(arn.accountId()) || !target.startsWith(ROLE_PREFIX)
|
||||
|| target.length() == ROLE_PREFIX.length() || target.contains("*")) {
|
||||
return List.of();
|
||||
}
|
||||
String roleName = target.substring(target.lastIndexOf('/') + 1);
|
||||
String trustPolicy = iamService.findRole(arn.accountId(), roleName)
|
||||
.filter(role -> IamService.roleArnMatches(resourceArn, role))
|
||||
.map(IamRole::getAssumeRolePolicyDocument)
|
||||
.flatMap(document -> attachedTo(document, resourceArn))
|
||||
.orElse(null);
|
||||
return List.of(new ResourcePolicy(trustPolicy, arn.accountId()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The trust policy with the role's ARN as the {@code Resource} of every statement naming none, or
|
||||
* empty when it cannot be read, which STS refuses whatever it says.
|
||||
*/
|
||||
private Optional<String> attachedTo(String trustPolicy, String roleArn) {
|
||||
if (trustPolicy == null || trustPolicy.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
JsonNode root;
|
||||
try {
|
||||
root = objectMapper.readTree(trustPolicy);
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Unreadable trust policy on {0}: {1}", roleArn, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
if (!(root instanceof ObjectNode document) || !TrustPolicyStatements.wellFormed(root.path("Statement"))) {
|
||||
return Optional.empty();
|
||||
}
|
||||
JsonNode statements = document.path("Statement");
|
||||
List<JsonNode> statementList = new ArrayList<>();
|
||||
if (statements.isArray()) {
|
||||
statements.forEach(statementList::add);
|
||||
} else {
|
||||
statementList.add(statements);
|
||||
}
|
||||
ArrayNode attached = objectMapper.createArrayNode();
|
||||
for (JsonNode statement : statementList) {
|
||||
ObjectNode copy = ((ObjectNode) statement).deepCopy();
|
||||
if (!copy.has("Resource") && !copy.has("NotResource")) {
|
||||
copy.put("Resource", roleArn);
|
||||
}
|
||||
attached.add(copy);
|
||||
}
|
||||
ObjectNode result = document.deepCopy();
|
||||
result.set("Statement", attached);
|
||||
try {
|
||||
return Optional.of(objectMapper.writeValueAsString(result));
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.debugv("Unwritable trust policy on {0}: {1}", roleArn, e.getMessage());
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-10
@@ -98,7 +98,7 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
String trustsDefault = createRole(trustAccountRoot(DEFAULT_ACCOUNT));
|
||||
String trustsOwnAccount = createRole(trustAccountRoot(OTHER_ACCOUNT));
|
||||
|
||||
assertTrustDenied(assumeRole(accessKeyId, trustsDefault, "sx", null), trustsDefault);
|
||||
assertTrustDeniedToAnIamCaller(assumeRole(accessKeyId, trustsDefault, "sx", null));
|
||||
assumeRole(accessKeyId, trustsOwnAccount, "sx", null).then().statusCode(200);
|
||||
}
|
||||
|
||||
@@ -113,7 +113,7 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
"{\"StringEquals\":{\"aws:username\":\"someone-else\"}}"));
|
||||
|
||||
assumeRole(accessKeyId, namesTheCaller, "sx", null).then().statusCode(200);
|
||||
assertTrustDenied(assumeRole(accessKeyId, namesSomeoneElse, "sx", null), namesSomeoneElse);
|
||||
assertTrustDeniedToAnIamCaller(assumeRole(accessKeyId, namesSomeoneElse, "sx", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -128,9 +128,9 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
"{\"StringEquals\":{\"aws:PrincipalType\":\"AssumedRole\"}}"));
|
||||
|
||||
assumeRole(accessKeyId, onlyUsers, "sx", null).then().statusCode(200);
|
||||
assertTrustDenied(assumeRoleWithSession(session, onlyUsers), onlyUsers);
|
||||
assertTrustDeniedToAnIamCaller(assumeRoleWithSession(session, onlyUsers));
|
||||
assumeRoleWithSession(session, onlySessions).then().statusCode(200);
|
||||
assertTrustDenied(assumeRole(accessKeyId, onlySessions, "sx", null), onlySessions);
|
||||
assertTrustDeniedToAnIamCaller(assumeRole(accessKeyId, onlySessions, "sx", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -140,7 +140,7 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
"{\"StringEquals\":{\"aws:PrincipalType\":\"Account\",\"aws:userid\":\"" + TRUSTED_ACCOUNT + "\"}}"));
|
||||
|
||||
assumeRole(TRUSTED_ACCOUNT, onlyTheRoot, "sx", null).then().statusCode(200);
|
||||
assertTrustDenied(assumeRole(accessKeyId, onlyTheRoot, "sx", null), onlyTheRoot);
|
||||
assertTrustDeniedToAnIamCaller(assumeRole(accessKeyId, onlyTheRoot, "sx", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -155,9 +155,9 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
String sessionIds = createRole(trustWithCondition("*", "{\"StringLike\":{\"aws:userid\":\"AROA*:sx\"}}"));
|
||||
|
||||
assumeRole(accessKeyId, userIds, "sx", null).then().statusCode(200);
|
||||
assertTrustDenied(assumeRoleWithSession(session, userIds), userIds);
|
||||
assertTrustDeniedToAnIamCaller(assumeRoleWithSession(session, userIds));
|
||||
assumeRoleWithSession(session, sessionIds).then().statusCode(200);
|
||||
assertTrustDenied(assumeRole(accessKeyId, sessionIds, "sx", null), sessionIds);
|
||||
assertTrustDeniedToAnIamCaller(assumeRole(accessKeyId, sessionIds, "sx", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -177,9 +177,9 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
String conditionOnPathlessRole = createRole(condition.formatted(TRUSTED_ACCOUNT, pathlessArn));
|
||||
|
||||
assumeRoleWithSession(session, namesRole).then().statusCode(200);
|
||||
assertTrustDenied(assumeRoleWithSession(session, namesPathlessRole), namesPathlessRole);
|
||||
assertTrustDeniedToAnIamCaller(assumeRoleWithSession(session, namesPathlessRole));
|
||||
assumeRoleWithSession(session, conditionOnRole).then().statusCode(200);
|
||||
assertTrustDenied(assumeRoleWithSession(session, conditionOnPathlessRole), conditionOnPathlessRole);
|
||||
assertTrustDeniedToAnIamCaller(assumeRoleWithSession(session, conditionOnPathlessRole));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -195,10 +195,21 @@ class AssumeRoleTrustConditionsIntegrationTest {
|
||||
String namesReplacement = createRole(
|
||||
trustPrincipal("arn:aws:iam::" + TRUSTED_ACCOUNT + ":role/other/" + callerRole));
|
||||
|
||||
assertTrustDenied(assumeRoleWithSession(oldSession, namesReplacement), namesReplacement);
|
||||
assertTrustDeniedToAnIamCaller(assumeRoleWithSession(oldSession, namesReplacement));
|
||||
assumeRoleWithSession(assumeCallerRole(callerRole, "/other/"), namesReplacement).then().statusCode(200);
|
||||
}
|
||||
|
||||
/**
|
||||
* A role in another account needs its trust policy to allow an IAM user or a role session
|
||||
* beside the caller's identity policy, so IAM enforcement refuses such a caller the trust
|
||||
* policy does not allow before STS does, with its own AccessDenied message.
|
||||
*/
|
||||
private static void assertTrustDeniedToAnIamCaller(Response response) {
|
||||
response.then().statusCode(403)
|
||||
.body(containsString("<Code>AccessDenied</Code>"))
|
||||
.body(containsString("is not authorized to perform: sts:AssumeRole"));
|
||||
}
|
||||
|
||||
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::"
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.floci.aws.services.iam.ResourcePolicyProvider.ResourcePolicy;
|
||||
import io.floci.aws.services.iam.model.IamRole;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
class RoleTrustPolicyProviderTest {
|
||||
|
||||
private static final String OWNER = "111122223333";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::" + OWNER + ":role/team/deployer";
|
||||
private static final String USER_ARN = "arn:aws:iam::" + OWNER + ":user/alice";
|
||||
private static final String TRUST = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"AWS":"%s"},"Action":"sts:AssumeRole"}]}""".formatted(USER_ARN);
|
||||
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final IamPolicyEvaluator evaluator = new IamPolicyEvaluator(mapper);
|
||||
private IamService iamService;
|
||||
private RoleTrustPolicyProvider provider;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
iamService = mock(IamService.class);
|
||||
when(iamService.findRole(anyString(), anyString())).thenReturn(Optional.empty());
|
||||
provider = new RoleTrustPolicyProvider(iamService, mapper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void assumingARoleComesWithItsTrustPolicyAndTheAccountInItsArn() throws Exception {
|
||||
storeRole(TRUST);
|
||||
|
||||
List<ResourcePolicy> policies = provider.getResourcePolicies("sts", "sts:AssumeRole", ROLE_ARN);
|
||||
|
||||
assertEquals(1, policies.size());
|
||||
assertEquals(OWNER, policies.getFirst().ownerAccountId());
|
||||
JsonNode statement = mapper.readTree(policies.getFirst().policyDocument()).path("Statement").get(0);
|
||||
assertEquals(USER_ARN, statement.path("Principal").path("AWS").asText());
|
||||
assertEquals("sts:AssumeRole", statement.path("Action").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTrustPolicyAppliesToTheRoleItIsAttachedTo() {
|
||||
// A trust policy carries no Resource element: the role it is attached to is its resource.
|
||||
storeRole(TRUST);
|
||||
|
||||
List<String> documents = documents(provider.getResourcePolicies("sts", "sts:AssumeRole", ROLE_ARN));
|
||||
|
||||
assertEquals(IamPolicyEvaluator.ResourcePolicyDecision.ALLOW_DIRECT_IAM_USER,
|
||||
evaluator.evaluateResourcePolicyFor(documents, RequestPrincipal.iam(USER_ARN),
|
||||
"sts:AssumeRole", ROLE_ARN, null));
|
||||
assertEquals(IamPolicyEvaluator.ResourcePolicyDecision.NEUTRAL,
|
||||
evaluator.evaluateResourcePolicyFor(documents, RequestPrincipal.iam(USER_ARN),
|
||||
"sts:AssumeRole", "arn:aws:iam::" + OWNER + ":role/team/other", null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoleThatDoesNotExistStillHasItsOwner() {
|
||||
assertEquals(List.of(new ResourcePolicy(null, OWNER)),
|
||||
provider.getResourcePolicies("sts", "sts:AssumeRole", ROLE_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRoleOfTheSameNameOnAnotherPathIsNotTheRoleNamed() {
|
||||
storeRole(TRUST);
|
||||
|
||||
assertEquals(List.of(new ResourcePolicy(null, OWNER)), provider.getResourcePolicies("sts",
|
||||
"sts:AssumeRole", "arn:aws:iam::" + OWNER + ":role/deployer"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrustPolicyThatCannotBeReadGrantsNothing() {
|
||||
storeRole("{\"Statement\":[{\"Effect\":\"Maybe\",\"Principal\":\"*\",\"Action\":\"sts:AssumeRole\"}]}");
|
||||
|
||||
assertEquals(List.of(new ResourcePolicy(null, OWNER)),
|
||||
provider.getResourcePolicies("sts", "sts:AssumeRole", ROLE_ARN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theTrustPolicyIsNotConsultedForIamActionsOnTheRole() {
|
||||
storeRole("""
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Principal":"*","NotAction":"sts:AssumeRole"}]}""");
|
||||
|
||||
assertTrue(provider.getResourcePolicies("iam", "iam:GetRole", ROLE_ARN).isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("iam", "iam:PassRole", ROLE_ARN).isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("iam", ROLE_ARN).isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anythingThatIsNotOneRoleIsLeftToOtherProviders() {
|
||||
assertTrue(provider.getResourcePolicies("sts", "sts:AssumeRole", "*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sts", "sts:AssumeRole", USER_ARN).isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sts", "sts:AssumeRole",
|
||||
"arn:aws:iam::" + OWNER + ":role/*").isEmpty());
|
||||
assertTrue(provider.getResourcePolicies("sqs", "sqs:SendMessage",
|
||||
"arn:aws:sqs:us-east-1:" + OWNER + ":orders").isEmpty());
|
||||
}
|
||||
|
||||
private void storeRole(String trustPolicy) {
|
||||
IamRole role = new IamRole("AROAEXAMPLE", "deployer", "/team/", ROLE_ARN, trustPolicy);
|
||||
when(iamService.findRole(OWNER, "deployer")).thenReturn(Optional.of(role));
|
||||
}
|
||||
|
||||
private static List<String> documents(List<ResourcePolicy> policies) {
|
||||
return policies.stream().map(ResourcePolicy::policyDocument).toList();
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
package io.floci.aws.services.iam;
|
||||
|
||||
import io.floci.aws.testing.EnforcementFixtures;
|
||||
import io.floci.aws.testing.EnforcementFixtures.Session;
|
||||
import io.floci.aws.testing.EnforcementFixtures.UserCredentials;
|
||||
import io.floci.aws.testing.IamEnforcementProfile;
|
||||
import io.floci.aws.testing.PartitionCleanup;
|
||||
import io.quarkus.test.common.http.TestHTTPResource;
|
||||
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 org.junit.jupiter.api.extension.RegisterExtension;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
|
||||
/**
|
||||
* With {@code iam.enforcement-enabled=true}, a role's trust policy acts as its resource-based policy.
|
||||
* The STS API Reference (AssumeRole) lets a user assume a role in its own account when the user is
|
||||
* added "as a principal directly in the role's trust policy": "When a resource-based policy grants
|
||||
* access to a principal in the same account, no additional identity-based policy is required." A
|
||||
* trust policy naming the account instead needs the user's identity-based policy too, and across
|
||||
* accounts "a principal needs an Allow in the identity policy and the resource-based policy".
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class StsAssumeRoleTrustPolicyUserIntegrationTest {
|
||||
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String OTHER_ACCOUNT = "222222222222";
|
||||
|
||||
private static final String ROLE_POLICY = """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*"}]}""";
|
||||
|
||||
@TestHTTPResource
|
||||
URI baseUri;
|
||||
|
||||
@RegisterExtension
|
||||
final PartitionCleanup cleanup = new PartitionCleanup();
|
||||
|
||||
@Test
|
||||
void aTrustPolicyNamingTheUserLetsItAssumeTheRoleWithoutAnIdentityPolicy() {
|
||||
String suffix = suffix();
|
||||
String user = "trusted-user-" + suffix;
|
||||
UserCredentials caller = createUser(ACCOUNT, user);
|
||||
String roleArn = createRole(ACCOUNT, "trusts-user-" + suffix, trustNaming(userArn(ACCOUNT, user)));
|
||||
|
||||
assumeRole(caller, roleArn).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrustPolicyNamingTheAccountStillNeedsTheUsersIdentityPolicy() {
|
||||
String suffix = suffix();
|
||||
String user = "account-trusted-" + suffix;
|
||||
UserCredentials caller = createUser(ACCOUNT, user);
|
||||
String roleArn = createRole(ACCOUNT, "trusts-root-" + suffix,
|
||||
trustNaming("arn:aws:iam::" + ACCOUNT + ":root"));
|
||||
String bareAccountRoleArn = createRole(ACCOUNT, "trusts-account-" + suffix, trustNaming(ACCOUNT));
|
||||
|
||||
assumeRole(caller, roleArn).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
assumeRole(caller, bareAccountRoleArn).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
allowAssumeRole(user, "*");
|
||||
assumeRole(caller, roleArn).then().statusCode(200);
|
||||
assumeRole(caller, bareAccountRoleArn).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExplicitDenyInTheUsersIdentityPolicyRefusesARoleThatTrustsTheUser() {
|
||||
String suffix = suffix();
|
||||
String user = "denied-user-" + suffix;
|
||||
UserCredentials caller = createUser(ACCOUNT, user);
|
||||
String roleArn = createRole(ACCOUNT, "trusts-denied-" + suffix, trustNaming(userArn(ACCOUNT, user)));
|
||||
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "deny", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Deny","Action":"sts:AssumeRole","Resource":"%s"}]}""".formatted(roleArn));
|
||||
|
||||
assumeRole(caller, roleArn).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPermissionsBoundaryDoesNotCapATrustPolicyNamingTheUser() {
|
||||
// The IAM User Guide: within the same account, resource-based policies that grant
|
||||
// permissions to an IAM user ARN "are not limited by an implicit deny in an identity-based
|
||||
// policy or permissions boundary".
|
||||
String suffix = suffix();
|
||||
String user = "bounded-user-" + suffix;
|
||||
// Created first so that the user, which holds it as its boundary, is removed before it.
|
||||
String boundaryArn = createPolicy("list-only-" + suffix, """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*"}]}""");
|
||||
UserCredentials caller = createUser(ACCOUNT, user);
|
||||
iam("PutUserPermissionsBoundary", "UserName", user, "PermissionsBoundary", boundaryArn);
|
||||
String roleArn = createRole(ACCOUNT, "trusts-bounded-" + suffix, trustNaming(userArn(ACCOUNT, user)));
|
||||
|
||||
assumeRole(caller, roleArn).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrustPolicyNamingAUserOfAnotherAccountStillNeedsThatUsersIdentityPolicy() {
|
||||
String suffix = suffix();
|
||||
String user = "cross-account-user-" + suffix;
|
||||
UserCredentials caller = createUser(OTHER_ACCOUNT, user);
|
||||
String roleArn = createRole(ACCOUNT, "trusts-other-account-user-" + suffix,
|
||||
trustNaming(userArn(OTHER_ACCOUNT, user)));
|
||||
|
||||
assumeRole(caller, roleArn).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
|
||||
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(OTHER_ACCOUNT, "iam"), user, "assume", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"%s"}]}""".formatted(roleArn));
|
||||
assumeRole(caller, roleArn).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrustPolicyNamingAnotherUserDoesNotLetTheCallerIn() {
|
||||
String suffix = suffix();
|
||||
UserCredentials caller = createUser(ACCOUNT, "untrusted-user-" + suffix);
|
||||
createUser(ACCOUNT, "other-user-" + suffix);
|
||||
String roleArn = createRole(ACCOUNT, "trusts-other-user-" + suffix,
|
||||
trustNaming(userArn(ACCOUNT, "other-user-" + suffix)));
|
||||
|
||||
assumeRole(caller, roleArn).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrustPolicyNamingARoleLetsItsSessionsAssumeTheRoleWithoutAnIdentityPolicy() {
|
||||
// The IAM User Guide: "If an action is allowed by an identity-based policy, a
|
||||
// resource-based policy, or both, then AWS allows the action", and a role ARN is a
|
||||
// principal a resource-based policy grants to. The calling role's own policy allows
|
||||
// nothing on STS.
|
||||
String suffix = suffix();
|
||||
String callerRoleArn = EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/team/",
|
||||
"caller-" + suffix, ROLE_POLICY);
|
||||
Session session = EnforcementFixtures.assumeRole(baseUri.getPort(), ACCOUNT, callerRoleArn);
|
||||
String trustsRole = createRole(ACCOUNT, "trusts-role-" + suffix, trustNaming(callerRoleArn));
|
||||
String trustsAccount = createRole(ACCOUNT, "trusts-root-of-role-" + suffix,
|
||||
trustNaming("arn:aws:iam::" + ACCOUNT + ":root"));
|
||||
|
||||
assumeRole(session, trustsRole).then().statusCode(200);
|
||||
assumeRole(session, trustsAccount).then().statusCode(403).body(containsString("AccessDenied"));
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private static String userArn(String account, String user) {
|
||||
return "arn:aws:iam::" + account + ":user/" + user;
|
||||
}
|
||||
|
||||
private static String trustNaming(String principal) {
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"%s"},"Action":"sts:AssumeRole"}]}""".formatted(principal);
|
||||
}
|
||||
|
||||
private UserCredentials createUser(String account, String user) {
|
||||
return EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(account, "iam"), user);
|
||||
}
|
||||
|
||||
private String createRole(String account, String role, String trustPolicy) {
|
||||
return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), account, "/", role, trustPolicy,
|
||||
ROLE_POLICY);
|
||||
}
|
||||
|
||||
private void allowAssumeRole(String user, String resource) {
|
||||
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), user, "assume", """
|
||||
{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"%s"}]}""".formatted(resource));
|
||||
}
|
||||
|
||||
private String createPolicy(String name, String document) {
|
||||
String arn = iam("CreatePolicy", "PolicyName", name, "PolicyDocument", document)
|
||||
.then().extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn");
|
||||
cleanup.register(() -> EnforcementFixtures.removePolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), arn));
|
||||
return arn;
|
||||
}
|
||||
|
||||
private Response iam(String action, String... params) {
|
||||
RequestSpecification request = given().port(baseUri.getPort())
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", auth(ACCOUNT, "iam"))
|
||||
.formParam("Action", action);
|
||||
for (int i = 0; i < params.length; i += 2) {
|
||||
request = request.formParam(params[i], params[i + 1]);
|
||||
}
|
||||
Response response = request.when().post("/");
|
||||
response.then().statusCode(200);
|
||||
return response;
|
||||
}
|
||||
|
||||
private Response assumeRole(Session session, String roleArn) {
|
||||
return given().port(baseUri.getPort())
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", auth(session.accessKeyId(), "sts"))
|
||||
.header("X-Amz-Security-Token", session.sessionToken())
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", EnforcementFixtures.SESSION_NAME)
|
||||
.when().post("/");
|
||||
}
|
||||
|
||||
private Response assumeRole(UserCredentials caller, String roleArn) {
|
||||
return given().port(baseUri.getPort())
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.header("Authorization", auth(caller.accessKeyId(), "sts"))
|
||||
.formParam("Action", "AssumeRole")
|
||||
.formParam("RoleArn", roleArn)
|
||||
.formParam("RoleSessionName", EnforcementFixtures.SESSION_NAME)
|
||||
.when().post("/");
|
||||
}
|
||||
}
|
||||
@@ -192,12 +192,13 @@ class StsMfaEnforcementIntegrationTest {
|
||||
S3RequestSigner user = userWithPolicy(userName, ASSUME_WITH_MFA);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String roleName = unique("mfa-identity-role");
|
||||
createRoleTrustingUser(roleName, userName);
|
||||
createRoleTrusting(roleName, "arn:aws:iam::" + ACCOUNT + ":root");
|
||||
|
||||
// Nothing in the trust policy asks for MFA here: what does is the caller's own permission
|
||||
// to call the operation, which is evaluated before the operation runs. AWS denies such a
|
||||
// request when "users have not been MFA authenticated", and allows it on the device the
|
||||
// call carries.
|
||||
// call carries. The trust policy names the account rather than the user: one naming the
|
||||
// user would grant the call on its own, needing "no additional identity-based policy".
|
||||
assumeRole(user, roleName, device.serialNumber(), device.codeNow()).statusCode(200);
|
||||
assumeRole(user, roleName, null, null).statusCode(403);
|
||||
}
|
||||
@@ -240,7 +241,7 @@ class StsMfaEnforcementIntegrationTest {
|
||||
S3RequestSigner user = userWithPolicy(userName, LIST_AND_MINT);
|
||||
MfaDevice device = enabledDeviceFor(userName);
|
||||
String roleName = unique("mfa-sts-reach-role");
|
||||
createRoleTrustingUser(roleName, userName);
|
||||
createRoleTrusting(roleName, "arn:aws:iam::" + ACCOUNT + ":user/" + userName);
|
||||
S3RequestSigner session = sessionWith(user, null);
|
||||
|
||||
// "You cannot call any AWS STS API except AssumeRole or GetCallerIdentity."
|
||||
@@ -329,12 +330,12 @@ class StsMfaEnforcementIntegrationTest {
|
||||
"PolicyDocument", LIST_WITH_MFA);
|
||||
}
|
||||
|
||||
/** A role {@code userName} may assume, with nothing in the trust policy about MFA. */
|
||||
private static void createRoleTrustingUser(String roleName, String userName) {
|
||||
/** A role {@code principal} may assume, with nothing in the trust policy about MFA. */
|
||||
private static void createRoleTrusting(String roleName, String principal) {
|
||||
iam("CreateRole", "RoleName", roleName, "AssumeRolePolicyDocument", """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:user/%s"},"Action":"sts:AssumeRole"}]}"""
|
||||
.formatted(ACCOUNT, userName));
|
||||
"Principal":{"AWS":"%s"},"Action":"sts:AssumeRole"}]}"""
|
||||
.formatted(principal));
|
||||
}
|
||||
|
||||
/** A virtual device created and enabled for a fresh user, the way a client sets one up. */
|
||||
|
||||
Reference in new issue
Block a user