mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(iam): enforce AssumeRole trust policies when enforcement is enabled (#1552)
* 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.
This commit is contained in:
1 parent
c496091ac3
commit
d54a307ca9
6 files changed
+534
-1
No files matched your search
@@ -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}.
|
||||
*
|
||||
* <p>Trust policies are principal-centric and carry no {@code Resource} element, so they cannot be
|
||||
* evaluated by {@link IamPolicyEvaluator} (which is identity/resource oriented). This focused
|
||||
* evaluator matches each statement's {@code Action} and {@code Principal} against the caller and
|
||||
* applies AWS precedence: an explicit {@code Deny} wins, otherwise a matching {@code Allow} grants.
|
||||
*
|
||||
* <p>Only AWS principals are modeled (account-root, bare account id, exact principal ARN, and
|
||||
* {@code "*"}); {@code Service} and {@code Federated} principals never match a SigV4 caller and are
|
||||
* ignored. A caller using assumed-role temporary credentials (whose ARN is an STS
|
||||
* {@code assumed-role} ARN) also matches a trust policy that names the underlying IAM role ARN, as
|
||||
* AWS resolves the session back to its role for trust-policy evaluation.
|
||||
*/
|
||||
@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}.
|
||||
*
|
||||
* <p>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;
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
* <p>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<IamRole> findRole(String accountId, String roleName) {
|
||||
if (roles instanceof AccountAwareStorageBackend<IamRole> 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()) {
|
||||
|
||||
@@ -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<String, String> 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<IamRole> 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<String, String> params) {
|
||||
String accountId = regionResolver.getAccountId();
|
||||
String authorization = headers == null ? null : headers.getHeaderString("Authorization");
|
||||
|
||||
Reference in new issue
Block a user