From d54a307ca91146f019ec1e0c623df49d8571369f Mon Sep 17 00:00:00 2001 From: Alex Banna Date: Tue, 30 Jun 2026 21:44:04 -0500 Subject: [PATCH] feat(iam): enforce AssumeRole trust policies when enforcement is enabled (#1552) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(iam): enforce AssumeRole trust policies when enforcement is enabled When floci.iam.enforcement-enabled is true, STS AssumeRole now evaluates the target role's trust policy (AssumeRolePolicyDocument) against the caller and returns AccessDenied if it is not permitted. Enforcement is off by default, so existing behavior is unchanged. Trust policies are principal-centric and carry no Resource element, so the identity/resource-oriented IamPolicyEvaluator cannot evaluate them. A focused AssumeRolePolicyEvaluator matches each statement's Action (sts:AssumeRole) and AWS Principal (account id, account-root ARN, exact principal ARN, or "*") against the caller, with explicit Deny taking precedence. The role is resolved in its own account (from the role ARN) via a new IamService.findRole overload, since roles are account-namespaced. Roles unknown to Floci stay permissive to preserve backward compatibility. Tests: unit coverage for the evaluator across principal/action/deny/malformed cases, plus an enforcement-enabled integration test asserting a permitted caller succeeds, an unauthorized caller is denied, and an unknown role stays permissive. * docs(sts): restore Configuration section and note NotAction limitation Greptile review on #1552: - Restore the FLOCI_SERVICES_STS_ENABLED Configuration section that was dropped when the Trust Policy Enforcement section was added. - Document that NotAction is not evaluated (a Deny with NotAction won't block). * fix(iam): honor NotAction in AssumeRole trust statements evaluateStatement only inspected the Action key, so a trust statement using NotAction returned NO_MATCH and was skipped entirely. A Deny that should block sts:AssumeRole (NotAction excluding some other action) was therefore ignored, over-permitting AssumeRole when IAM enforcement is enabled. Add actionApplies() mirroring IamPolicyEvaluator's Action/NotAction semantics: Action applies when any pattern matches, NotAction applies when none match. Covered by three new AssumeRolePolicyEvaluatorTest cases. * fix(iam): match an assumed-role caller against a role-ARN trust principal When a caller uses assumed-role temporary credentials, resolveCallerArn (rightly, for GetCallerIdentity) yields the STS assumed-role ARN (arn:aws:sts::ACCT:assumed-role/Role/session). enforceTrustPolicy passes that to the trust-policy evaluator, but role trust policies name the role's IAM principal ARN (arn:aws:iam::ACCT:role/Role) — the canonical form AWS resolves the session back to. So a legitimate role-to-role AssumeRole was denied. matchesAwsPrincipal now also normalizes an assumed-role caller ARN to its underlying IAM role ARN and matches the principal against that, while still matching an exact session-ARN principal. resolveCallerArn is unchanged, so GetCallerIdentity keeps returning the assumed-role ARN. Adds AssumeRolePolicyEvaluatorTest cases for role-ARN match, differing-role denial, and exact session-ARN match. --- docs/services/sts.md | 18 ++ .../iam/AssumeRolePolicyEvaluator.java | 190 ++++++++++++++++++ .../floci/services/iam/IamService.java | 13 ++ .../floci/services/iam/StsQueryHandler.java | 42 +++- .../iam/AssumeRolePolicyEvaluatorTest.java | 167 +++++++++++++++ .../AssumeRoleTrustPolicyIntegrationTest.java | 105 ++++++++++ 6 files changed, 534 insertions(+), 1 deletion(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java diff --git a/docs/services/sts.md b/docs/services/sts.md index 1477e09cd4..b71b42649f 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -20,6 +20,24 @@ |---|---|---| | `FLOCI_SERVICES_STS_ENABLED` | `true` | Enable or disable the service | +## Trust Policy Enforcement + +By default `AssumeRole` succeeds for any caller. When `FLOCI_SERVICES_IAM_ENFORCEMENT_ENABLED=true`, +`AssumeRole` evaluates the target role's trust policy (`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:::root`), and exact principal ARNs — and an +explicit `Deny` always wins. Both `Action` and `NotAction` elements are honored when matching +`sts:AssumeRole`. Roles that Floci has no record of stay permissive, so this only affects roles +created through IAM with a real trust policy. + +### Known limitations + +- **`Condition` blocks are not evaluated.** 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. +- **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. + ## Examples ```bash 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 new file mode 100644 index 0000000000..5bf2e0c9b1 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluator.java @@ -0,0 +1,190 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import jakarta.enterprise.context.ApplicationScoped; +import jakarta.inject.Inject; +import org.jboss.logging.Logger; + +import java.util.regex.Pattern; + +/** + * Evaluates a role's trust policy (AssumeRolePolicyDocument) to decide whether a caller may assume + * the role via {@code sts:AssumeRole}. + * + *

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. + * + *

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. + */ +@ApplicationScoped +public class AssumeRolePolicyEvaluator { + + private static final Logger LOG = Logger.getLogger(AssumeRolePolicyEvaluator.class); + private static final String ASSUME_ROLE_ACTION = "sts:AssumeRole"; + private static final Pattern ACCOUNT_ROOT_ARN = Pattern.compile("^arn:aws:iam::(\\d{12}):root$"); + private static final Pattern ASSUMED_ROLE_ARN = + Pattern.compile("^arn:aws:sts::(\\d{12}):assumed-role/([^/]+)/.*$"); + + private final ObjectMapper objectMapper; + + @Inject + public AssumeRolePolicyEvaluator(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + /** + * Returns true if {@code trustPolicyDocument} allows the caller (identified by + * {@code callerArn}, in {@code callerAccount}) to perform {@code sts:AssumeRole}. + * + *

A null/blank/unparseable document or one with no matching {@code Allow} denies. + */ + public boolean allows(String trustPolicyDocument, String callerArn, String callerAccount) { + if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) { + return false; + } + JsonNode statements; + try { + statements = objectMapper.readTree(trustPolicyDocument).path("Statement"); + } catch (Exception e) { + LOG.warnv("Failed to parse trust policy: {0}", e.getMessage()); + return false; + } + + boolean allow = false; + if (statements.isArray()) { + for (JsonNode stmt : statements) { + switch (evaluateStatement(stmt, callerArn, callerAccount)) { + case DENY -> { return false; } + case ALLOW -> allow = true; + case NO_MATCH -> { } + } + } + } else if (statements.isObject()) { + return evaluateStatement(statements, callerArn, callerAccount) == Match.ALLOW; + } + return allow; + } + + private enum Match { ALLOW, DENY, NO_MATCH } + + private Match evaluateStatement(JsonNode stmt, String callerArn, String callerAccount) { + if (!actionApplies(stmt)) { + return Match.NO_MATCH; + } + if (!matchesPrincipal(stmt.get("Principal"), callerArn, callerAccount)) { + return Match.NO_MATCH; + } + return "Deny".equalsIgnoreCase(stmt.path("Effect").asText("Allow")) ? Match.DENY : Match.ALLOW; + } + + /** + * True if the statement's action element applies to {@code sts:AssumeRole}. An {@code Action} + * element applies when any of its patterns match; a {@code NotAction} element applies when none + * of its patterns match (AWS semantics, mirroring {@link IamPolicyEvaluator}'s action handling). + * A statement with neither key expresses no action constraint and does not apply. + */ + private boolean actionApplies(JsonNode stmt) { + JsonNode action = stmt.get("Action"); + if (action != null) { + return matchesAssumeRoleAction(action); + } + JsonNode notAction = stmt.get("NotAction"); + if (notAction != null) { + return !matchesAssumeRoleAction(notAction); + } + return false; + } + + private boolean matchesAssumeRoleAction(JsonNode actionNode) { + if (actionNode == null) { + return false; + } + if (actionNode.isTextual()) { + return IamPolicyEvaluator.globMatches(actionNode.asText(), ASSUME_ROLE_ACTION); + } + if (actionNode.isArray()) { + for (JsonNode a : actionNode) { + if (a.isTextual() && IamPolicyEvaluator.globMatches(a.asText(), ASSUME_ROLE_ACTION)) { + return true; + } + } + } + return false; + } + + private boolean matchesPrincipal(JsonNode principalNode, String callerArn, String callerAccount) { + if (principalNode == null) { + return false; + } + // Principal: "*" + if (principalNode.isTextual()) { + return "*".equals(principalNode.asText()); + } + if (!principalNode.isObject()) { + return false; + } + // Only the AWS principal type can match a SigV4 caller. + JsonNode aws = principalNode.get("AWS"); + if (aws == null) { + return false; + } + if (aws.isTextual()) { + return matchesAwsPrincipal(aws.asText(), callerArn, callerAccount); + } + if (aws.isArray()) { + for (JsonNode entry : aws) { + if (entry.isTextual() && matchesAwsPrincipal(entry.asText(), callerArn, callerAccount)) { + return true; + } + } + } + return false; + } + + private boolean matchesAwsPrincipal(String principal, String callerArn, String callerAccount) { + if (principal == null) { + return false; + } + if ("*".equals(principal)) { + return true; + } + // Bare 12-digit account id, or an account-root ARN → matches any principal in that account. + if (principal.matches("\\d{12}")) { + return principal.equals(callerAccount); + } + var rootMatcher = ACCOUNT_ROOT_ARN.matcher(principal); + 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)) { + 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. + */ + private static String assumedRoleToRoleArn(String arn) { + var m = ASSUMED_ROLE_ARN.matcher(arn); + return m.matches() ? "arn:aws:iam::" + m.group(1) + ":role/" + m.group(2) : null; + } +} 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 4ee2335df1..1d41af31ba 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 @@ -357,6 +357,19 @@ public class IamService implements SessionAccountLookup { "The role with name " + roleName + " cannot be found.", 404)); } + /** + * Looks up a role by name in a specific account's namespace, without throwing when absent. + * + *

Roles are account-namespaced, so a cross-account caller (e.g. STS AssumeRole) must resolve + * the role in its owning account — taken from the role ARN — rather than the request's account. + */ + public Optional findRole(String accountId, String roleName) { + if (roles instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, roleName); + } + return roles.get(roleName); + } + public void deleteRole(String roleName) { IamRole role = getRole(roleName); if (!role.getAttachedPolicyArns().isEmpty() || !role.getInlinePolicies().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 c6997647a7..e39dcb9846 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,5 +1,6 @@ package io.github.hectorvent.floci.services.iam; +import io.github.hectorvent.floci.config.EmulatorConfig; import io.github.hectorvent.floci.core.common.AwsArnUtils; import io.github.hectorvent.floci.core.common.AwsNamespaces; import io.github.hectorvent.floci.core.common.AwsQueryController; @@ -7,6 +8,7 @@ import io.github.hectorvent.floci.core.common.AwsQueryResponse; import io.github.hectorvent.floci.core.common.AccountResolver; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.common.XmlBuilder; +import io.github.hectorvent.floci.services.iam.model.IamRole; import jakarta.enterprise.context.ApplicationScoped; import jakarta.inject.Inject; import jakarta.ws.rs.core.Context; @@ -17,6 +19,7 @@ import org.jboss.logging.Logger; import java.time.Instant; import java.time.format.DateTimeFormatter; +import java.util.Optional; import java.util.concurrent.ThreadLocalRandom; /** @@ -33,15 +36,20 @@ public class StsQueryHandler { private final IamService iamService; private final AccountResolver accountResolver; private final RegionResolver regionResolver; + private final EmulatorConfig config; + private final AssumeRolePolicyEvaluator trustPolicyEvaluator; @Context HttpHeaders headers; @Inject - public StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver) { + public StsQueryHandler(IamService iamService, AccountResolver accountResolver, RegionResolver regionResolver, + EmulatorConfig config, AssumeRolePolicyEvaluator trustPolicyEvaluator) { this.iamService = iamService; this.accountResolver = accountResolver; this.regionResolver = regionResolver; + this.config = config; + this.trustPolicyEvaluator = trustPolicyEvaluator; } public Response handle(String action, MultivaluedMap params) { @@ -79,6 +87,12 @@ public class StsQueryHandler { : "UnknownRole"; String callerAccountId = regionResolver.getAccountId(); String accountId = AwsArnUtils.accountOrDefault(roleArn, callerAccountId); + + Response trustDenied = enforceTrustPolicy(roleArn, roleName, accountId); + if (trustDenied != null) { + return trustDenied; + } + String assumedRoleArn = AwsArnUtils.Arn.of("sts", "", accountId, "assumed-role/" + roleName + "/" + sessionName).toString(); String assumedRoleId = "AROA" + randomId(16) + ":" + sessionName; @@ -99,6 +113,32 @@ public class StsQueryHandler { return Response.ok(AwsQueryResponse.envelope("AssumeRole", AwsNamespaces.STS, result)).build(); } + /** + * 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. + */ + private Response enforceTrustPolicy(String roleArn, String roleName, String roleAccountId) { + if (!config.services().iam().enforcementEnabled()) { + return null; + } + Optional role = iamService.findRole(roleAccountId, roleName); + if (role.isEmpty()) { + 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)) + .orElse(AwsArnUtils.Arn.of("iam", "", callerAccount, "root").toString()); + if (trustPolicyEvaluator.allows(role.get().getAssumeRolePolicyDocument(), callerArn, callerAccount)) { + return null; + } + return AwsQueryResponse.error("AccessDenied", + "User: " + callerArn + " is not authorized to perform: sts:AssumeRole on resource: " + roleArn, + AwsNamespaces.STS, 403); + } + private Response handleGetCallerIdentity(MultivaluedMap params) { String accountId = regionResolver.getAccountId(); String authorization = headers == null ? null : headers.getHeaderString("Authorization"); 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 new file mode 100644 index 0000000000..6797faf19c --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRolePolicyEvaluatorTest.java @@ -0,0 +1,167 @@ +package io.github.hectorvent.floci.services.iam; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +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 static final String CALLER_ARN = "arn:aws:iam::111111111111:user/alice"; + private static final String CALLER_ACCOUNT = "111111111111"; + + private static String trust(String principal) { + return """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":%s,"Action":"sts:AssumeRole"}]} + """.formatted(principal); + } + + @Test + void allowsAccountRootPrincipal() { + assertTrue(evaluator.allows( + trust("{\"AWS\":\"arn:aws:iam::111111111111:root\"}"), CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void allowsBareAccountPrincipal() { + assertTrue(evaluator.allows(trust("{\"AWS\":\"111111111111\"}"), CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void allowsExactPrincipalArn() { + assertTrue(evaluator.allows( + trust("{\"AWS\":\"arn:aws:iam::111111111111:user/alice\"}"), CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void allowsWildcardPrincipal() { + assertTrue(evaluator.allows(trust("\"*\""), CALLER_ARN, CALLER_ACCOUNT)); + assertTrue(evaluator.allows(trust("{\"AWS\":\"*\"}"), CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void allowsWhenPrincipalListContainsCaller() { + assertTrue(evaluator.allows( + trust("{\"AWS\":[\"arn:aws:iam::999999999999:root\",\"arn:aws:iam::111111111111:root\"]}"), + CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void deniesWhenAccountDoesNotMatch() { + assertFalse(evaluator.allows( + trust("{\"AWS\":\"arn:aws:iam::999999999999:root\"}"), CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void deniesWhenPrincipalArnDiffers() { + assertFalse(evaluator.allows( + trust("{\"AWS\":\"arn:aws:iam::111111111111:user/bob\"}"), CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void explicitDenyOverridesAllow() { + String doc = """ + {"Version":"2012-10-17","Statement":[ + {"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)); + } + + @Test + void deniesWhenActionIsNotAssumeRole() { + String doc = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:TagSession"}]} + """; + assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void allowsWildcardAction() { + String doc = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"111111111111"},"Action":"sts:*"}]} + """; + assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void deniesWhenDenyNotActionExcludesAssumeRole() { + // Deny applies to every action except sts:TagSession — which includes sts:AssumeRole — so it blocks. + String doc = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"}, + {"Effect":"Deny","Principal":{"AWS":"*"},"NotAction":"sts:TagSession"}]} + """; + assertFalse(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void allowsWhenDenyNotActionIncludesAssumeRole() { + // Deny applies to every action except sts:AssumeRole, so it does NOT block the assume. + String doc = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"*"},"Action":"sts:AssumeRole"}, + {"Effect":"Deny","Principal":{"AWS":"*"},"NotAction":"sts:AssumeRole"}]} + """; + assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT)); + } + + @Test + void allowsWhenAllowNotActionDoesNotCoverAssumeRole() { + // Allow applies to every action except sts:GetSessionToken, so it grants sts:AssumeRole. + String doc = """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Principal":{"AWS":"111111111111"},"NotAction":"sts:GetSessionToken"}]} + """; + assertTrue(evaluator.allows(doc, CALLER_ARN, CALLER_ACCOUNT)); + } + + @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. + 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)); + } + + @Test + void deniesAssumedRoleCallerWhenRolePrincipalDiffers() { + // A trust policy naming a different role must not be satisfied by this session. + 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)); + } + + @Test + void allowsAssumedRoleCallerAgainstExactSessionArn() { + // A trust policy that names the exact assumed-role session ARN still matches directly. + 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)); + } + + @Test + void deniesServiceOnlyPrincipal() { + assertFalse(evaluator.allows( + trust("{\"Service\":\"lambda.amazonaws.com\"}"), CALLER_ARN, CALLER_ACCOUNT)); + } + + @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)); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java new file mode 100644 index 0000000000..d06ed27cc3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/AssumeRoleTrustPolicyIntegrationTest.java @@ -0,0 +1,105 @@ +package io.github.hectorvent.floci.services.iam; + +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.QuarkusTestProfile; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.startsWith; + +/** + * Verifies that, with {@code iam.enforcement-enabled=true}, STS AssumeRole honors the target role's + * trust policy: a caller the trust policy permits succeeds; one it does not is denied; and a role + * Floci does not know about stays permissive (backward-compatible). + */ +@QuarkusTest +@TestProfile(AssumeRoleTrustPolicyIntegrationTest.EnforcementProfile.class) +class AssumeRoleTrustPolicyIntegrationTest { + + public static class EnforcementProfile implements QuarkusTestProfile { + @Override + public Map getConfigOverrides() { + return Map.of("floci.services.iam.enforcement-enabled", "true"); + } + } + + private static final String ACCOUNT_A = "111111111111"; + private static final String ACCOUNT_B = "222222222222"; + private static final String ACCOUNT_C = "333333333333"; + + private static final String TRUST_ALLOW_A = "{\"Version\":\"2012-10-17\",\"Statement\":[{" + + "\"Effect\":\"Allow\",\"Principal\":{\"AWS\":\"arn:aws:iam::" + ACCOUNT_A + ":root\"}," + + "\"Action\":\"sts:AssumeRole\"}]}"; + + private static String auth(String account, String service) { + return "AWS4-HMAC-SHA256 Credential=" + account + "/20260215/us-east-1/" + service + + "/aws4_request, SignedHeaders=host, Signature=abc"; + } + + private static void createRoleInB(String roleName) { + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "CreateRole") + .formParam("RoleName", roleName) + .formParam("AssumeRolePolicyDocument", TRUST_ALLOW_A) + .header("Authorization", auth(ACCOUNT_B, "iam")) + .when().post("/") + .then().statusCode(200); + } + + @Test + void permittedCallerCanAssumeRole() { + String role = "trust-ok-" + UUID.randomUUID().toString().substring(0, 8); + createRoleInB(role); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRole") + .formParam("RoleArn", "arn:aws:iam::" + ACCOUNT_B + ":role/" + role) + .formParam("RoleSessionName", "s") + .header("Authorization", auth(ACCOUNT_A, "sts")) + .when().post("/") + .then().statusCode(200) + .body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA")); + } + + @Test + void unauthorizedCallerIsDenied() { + String role = "trust-deny-" + UUID.randomUUID().toString().substring(0, 8); + createRoleInB(role); + + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRole") + .formParam("RoleArn", "arn:aws:iam::" + ACCOUNT_B + ":role/" + role) + .formParam("RoleSessionName", "s") + .header("Authorization", auth(ACCOUNT_C, "sts")) + .when().post("/") + .then().statusCode(403) + .body(containsString("AccessDenied")) + // AWS prefixes the denial with the caller and names the action and resource. + .body(containsString("User: ")) + .body(containsString("is not authorized to perform: sts:AssumeRole on resource: " + + "arn:aws:iam::" + ACCOUNT_B + ":role/" + role)); + } + + @Test + void unknownRoleStaysPermissive() { + // No role created — enforcement must not block roles Floci has never seen. + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRole") + .formParam("RoleArn", "arn:aws:iam::" + ACCOUNT_B + ":role/never-created-" + + UUID.randomUUID().toString().substring(0, 8)) + .formParam("RoleSessionName", "s") + .header("Authorization", auth(ACCOUNT_C, "sts")) + .when().post("/") + .then().statusCode(200) + .body("AssumeRoleResponse.AssumeRoleResult.Credentials.AccessKeyId", startsWith("ASIA")); + } +}