mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(iam): read federated trust policies with the shared condition engine (#9728)
The trust policies of AssumeRoleWithSAML and AssumeRoleWithWebIdentity were read by two condition evaluators of their own, each taking only StringEquals, StringNotEquals, StringLike and StringNotLike: a statement using a set operator (ForAllValues on aws:TagKeys, ForAnyValue on an audience), an IfExists operator or Null never allowed the assume, a negated operator never matched a key the request does not carry, and SAML read a claim under any prefix, so other:sub read the assertion's sub. Both now read each statement's Condition with IamPolicyEvaluator.conditionMatches, as AssumeRolePolicyEvaluator does, against a context holding the claims under their full keys (the Service Authorization Reference's saml: keys for an assertion, the issuer's prefix for a token), sts:RoleSessionName, the role's tags, the request tags and the source identity. Each keeps its own Federated principal and action matching; the hand condition code is gone. A token's <issuer>:aud holds the one audience the token was accepted for, the one the response returns as Audience, wherever the token's list names it: the Service Authorization Reference types the key String, a single value. A multivalued key such as aws:TagKeys takes a set operator, as in every other policy, and a negated operator over an empty list of values holds, the NOR of no values.
This commit is contained in:
1 parent
fd6fff87be
commit
6f22b84977
8 files changed
+199
-193
No files matched your search
+17
-5
@@ -491,17 +491,29 @@ Authorization Reference lists no authorized actions for, is the companion the ge
|
||||
companions name where the tags arrive, the assertion's
|
||||
`https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}` attributes and the token's
|
||||
`https://aws.amazon.com/tags` claim, which is what the assertion and the token are read under.
|
||||
`AssumeRole` reads its trust policy under the enforcement this section describes, so the permission
|
||||
is read there too; the assertion and the token are read against their trust policy on every call, as
|
||||
they always have been.
|
||||
|
||||
The tags an assertion or a token passes are request tags of its trust policy as well, as
|
||||
`aws:RequestTag/<key>` and `aws:TagKeys`, the keys the Service Authorization Reference gives both
|
||||
actions, written as an `AssumeRole`'s are. The IAM user guide's SAML ABAC tutorial has a trust
|
||||
policy reading them on the assume and the tagging alike, "aws:RequestTag/access-team" required to be
|
||||
`eng` or `qas`, so a statement requiring a tag allows an assertion passing one of its values and not
|
||||
one passing another or none. The federated trust policies read the `String` operators; a set
|
||||
operator such as `ForAllValues` is not read by them, so a statement using one does not allow the
|
||||
assume. `AssumeRole` reads its trust policy under the enforcement this section
|
||||
describes, so the permission is read there too; the assertion and the token are read against their
|
||||
trust policy on every call, as they always have been.
|
||||
one passing another or none.
|
||||
|
||||
A federated trust policy's `Condition` is read by the condition engine every other policy is, as an
|
||||
`AssumeRole`'s is, so it takes every operator AWS gives, the set operators (`ForAllValues`,
|
||||
`ForAnyValue`), `...IfExists` and `Null` among them, with their usual reading of a key the request
|
||||
does not carry. Its context holds the assertion's claims under the Service Authorization Reference's
|
||||
`saml:` keys (`saml:aud`, `saml:sub`, `saml:iss`, `saml:namequalifier`), or the token's under its
|
||||
issuer's prefix (`<issuer>:sub`, `<issuer>:aud`), each read under that prefix alone,
|
||||
`sts:RoleSessionName`, the role's tags, the request tags and the source identity. `<issuer>:aud` is
|
||||
the one audience the token was accepted for, the one the response returns as `Audience`, wherever
|
||||
the token's list names it: the Service Authorization Reference types the key `String`, a single
|
||||
value. A key that is multivalued, as `aws:TagKeys` is, takes a set operator, as AWS says
|
||||
"multivalued context keys require a condition set operator", and a negated operator over an empty
|
||||
list of values holds, the NOR of no values.
|
||||
|
||||
The caller's own policy is read for it as well, and that half was already here: the generated
|
||||
tagging table has `sts:AssumeRole` and `sts:GetFederationToken` requiring `sts:TagSession` of a
|
||||
|
||||
@@ -5,23 +5,34 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
/** Evaluates the federated principal and SAML action in a role trust policy. */
|
||||
/**
|
||||
* Evaluates the federated principal and SAML action in a role trust policy, and hands each statement's
|
||||
* {@code Condition} to {@link IamPolicyEvaluator#conditionMatches}, the condition engine every other policy is read
|
||||
* with, so a trust policy reads every operator AWS gives (the set operators, {@code ...IfExists}, {@code Null}) as an
|
||||
* identity policy does.
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class SAMLTrustPolicyEvaluator {
|
||||
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
|
||||
private static final String SAML_ACTION = "sts:AssumeRoleWithSAML";
|
||||
/** The prefix of the keys the Service Authorization Reference gives a SAML assertion's claims, {@code saml:aud}. */
|
||||
private static final String SAML_KEY_PREFIX = "saml:";
|
||||
private final ObjectMapper mapper;
|
||||
private final IamPolicyEvaluator policyEvaluator;
|
||||
|
||||
@Inject
|
||||
public SAMLTrustPolicyEvaluator(ObjectMapper mapper) {
|
||||
public SAMLTrustPolicyEvaluator(ObjectMapper mapper, IamPolicyEvaluator policyEvaluator) {
|
||||
this.mapper = mapper;
|
||||
this.policyEvaluator = policyEvaluator;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code claims} are the assertion's claims by name, which a policy reads under the
|
||||
* Service Authorization Reference's {@code saml:} keys ({@code saml:aud}, {@code saml:sub}).
|
||||
* {@code roleSessionName} is the assertion's {@code RoleSessionName} attribute, which a policy
|
||||
* reads as {@code sts:RoleSessionName}, or null when the assertion carries none. {@code roleTags}
|
||||
* holds the tags of the role being assumed under the keys the generated table gives its type
|
||||
@@ -50,14 +61,17 @@ public class SAMLTrustPolicyEvaluator {
|
||||
Map<String, List<String>> claims, String roleSessionName,
|
||||
Map<String, List<String>> roleTags) {
|
||||
try {
|
||||
JsonNode statements = mapper.readTree(document).path("Statement");
|
||||
JsonNode root = mapper.readTree(document);
|
||||
JsonNode statements = root.path("Statement");
|
||||
if (!TrustPolicyStatements.wellFormed(statements)) {
|
||||
return false;
|
||||
}
|
||||
Map<String, List<String>> context = context(claims, roleSessionName, roleTags);
|
||||
String version = root.path("Version").asText(null);
|
||||
if (statements.isArray()) {
|
||||
boolean allowed = false;
|
||||
for (JsonNode statement : statements) {
|
||||
int result = evaluate(action, statement, providerArn, claims, roleSessionName, roleTags);
|
||||
int result = evaluate(action, statement, providerArn, context, version);
|
||||
if (result < 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -67,83 +81,34 @@ public class SAMLTrustPolicyEvaluator {
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
return statements.isObject()
|
||||
&& evaluate(action, statements, providerArn, claims, roleSessionName, roleTags) > 0;
|
||||
return statements.isObject() && evaluate(action, statements, providerArn, context, version) > 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int evaluate(String action, JsonNode statement, String providerArn,
|
||||
Map<String, List<String>> claims, String roleSessionName,
|
||||
Map<String, List<String>> roleTags) {
|
||||
private int evaluate(String action, JsonNode statement, String providerArn, Map<String, List<String>> context,
|
||||
String version) {
|
||||
if (!actionApplies(statement, action) || !principal(statement.path("Principal"), providerArn)
|
||||
|| !conditionsSatisfied(statement.get("Condition"), claims, roleSessionName, roleTags)) {
|
||||
|| !policyEvaluator.conditionMatches(statement.get("Condition"), context, version)) {
|
||||
return 0;
|
||||
}
|
||||
return TrustPolicyStatements.denies(statement) ? -1 : 1;
|
||||
}
|
||||
|
||||
private boolean conditionsSatisfied(JsonNode condition, Map<String, List<String>> claims,
|
||||
String roleSessionName, Map<String, List<String>> roleTags) {
|
||||
if (condition == null || condition.isNull()) {
|
||||
return true;
|
||||
/**
|
||||
* The request context the trust policy is read with: the keys given in full ({@code roleTags}: the role's tags,
|
||||
* the assertion's request tags and source identity), each claim under its {@code saml:} key, and the session
|
||||
* name as {@code sts:RoleSessionName} where the assertion names one.
|
||||
*/
|
||||
private static Map<String, List<String>> context(Map<String, List<String>> claims, String roleSessionName,
|
||||
Map<String, List<String>> roleTags) {
|
||||
Map<String, List<String>> context = new HashMap<>(roleTags);
|
||||
claims.forEach((name, values) -> context.put(SAML_KEY_PREFIX + name, values));
|
||||
if (roleSessionName != null) {
|
||||
context.put(ROLE_SESSION_NAME_KEY, List.of(roleSessionName));
|
||||
}
|
||||
if (!condition.isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> operators = condition.fields();
|
||||
while (operators.hasNext()) {
|
||||
Map.Entry<String, JsonNode> operator = operators.next();
|
||||
if (!operator.getValue().isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> entries = operator.getValue().fields();
|
||||
while (entries.hasNext()) {
|
||||
Map.Entry<String, JsonNode> entry = entries.next();
|
||||
List<String> actual = TrustPolicyStatements.roleValues(entry.getKey(), roleTags)
|
||||
.orElseGet(() -> conditionValues(entry.getKey(), claims, roleSessionName));
|
||||
List<String> expected = entry.getValue().isArray()
|
||||
? StreamSupport.stream(entry.getValue().spliterator(), false)
|
||||
.filter(JsonNode::isTextual).map(JsonNode::asText).toList()
|
||||
: entry.getValue().isTextual() ? List.of(entry.getValue().asText()) : List.of();
|
||||
if (expected.isEmpty() || actual.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
if (!operatorMatches(operator.getKey(), actual, expected)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static List<String> conditionValues(String key, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
if (ROLE_SESSION_NAME_KEY.equalsIgnoreCase(key)) {
|
||||
return roleSessionName == null ? List.of() : List.of(roleSessionName);
|
||||
}
|
||||
int colon = key.indexOf(':');
|
||||
String claimName = colon < 0 ? key : key.substring(colon + 1);
|
||||
return claims.getOrDefault(claimName, List.of());
|
||||
}
|
||||
|
||||
private boolean operatorMatches(String operator, List<String> actual, List<String> expected) {
|
||||
if ("StringEquals".equals(operator)) {
|
||||
return actual.stream().anyMatch(value -> expected.contains(value));
|
||||
}
|
||||
if ("StringLike".equals(operator)) {
|
||||
return actual.stream().anyMatch(value -> expected.stream().anyMatch(pattern ->
|
||||
IamPolicyEvaluator.caseSensitiveGlobMatches(pattern, value)));
|
||||
}
|
||||
if ("StringNotEquals".equals(operator)) {
|
||||
return actual.stream().allMatch(value -> expected.stream().noneMatch(value::equals));
|
||||
}
|
||||
if ("StringNotLike".equals(operator)) {
|
||||
return actual.stream().allMatch(value -> expected.stream().noneMatch(pattern ->
|
||||
IamPolicyEvaluator.caseSensitiveGlobMatches(pattern, value)));
|
||||
}
|
||||
return false;
|
||||
return context;
|
||||
}
|
||||
|
||||
private boolean actionApplies(JsonNode statement, String action) {
|
||||
|
||||
@@ -1056,9 +1056,15 @@ public class StsQueryHandler {
|
||||
return WebIdentityOutcome.deny(accessDenied(roleArn));
|
||||
}
|
||||
|
||||
// The audience the token was accepted for, which is the one value of the trust policy's aud key as it is of
|
||||
// the response's Audience: the Service Authorization Reference types the key String, where "multivalued
|
||||
// context keys ... use an ArrayOf prefix", and "AWS STS will use the value in the azp claim as the aud
|
||||
// claim". verify() already required the audience list to hold one of the accepted audiences.
|
||||
String audience = claims.audiences().stream().filter(acceptedAudiences::contains).findFirst()
|
||||
.orElse(STS_AUDIENCE);
|
||||
Map<String, List<String>> conditionClaims = Map.of(
|
||||
"sub", List.of(claims.subject()),
|
||||
"aud", claims.audiences());
|
||||
"aud", List.of(audience));
|
||||
|
||||
// The source identity the token sets, which the generated table says it carries in a claim of its own:
|
||||
// "include source identity in the https://aws.amazon.com/source_identity namespace in the token". The trust
|
||||
@@ -1098,9 +1104,6 @@ public class StsQueryHandler {
|
||||
return WebIdentityOutcome.deny(accessDenied(taggingKey.action(), roleArn));
|
||||
}
|
||||
|
||||
// verify() already required the audience list to hold one of the accepted audiences.
|
||||
String audience = claims.audiences().stream().filter(acceptedAudiences::contains).findFirst()
|
||||
.orElse(STS_AUDIENCE);
|
||||
return WebIdentityOutcome.allow(
|
||||
new VerifiedWebIdentity(claims.issuer(), claims.subject(), audience,
|
||||
claims.principalTags(), claims.transitiveTagKeys(), sourceIdentity), role.get());
|
||||
|
||||
@@ -7,10 +7,9 @@ import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
/**
|
||||
* Evaluates a role's trust policy for {@code sts:AssumeRoleWithWebIdentity}, matching the
|
||||
@@ -35,10 +34,12 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final IamPolicyEvaluator policyEvaluator;
|
||||
|
||||
@Inject
|
||||
public WebIdentityTrustPolicyEvaluator(ObjectMapper objectMapper) {
|
||||
public WebIdentityTrustPolicyEvaluator(ObjectMapper objectMapper, IamPolicyEvaluator policyEvaluator) {
|
||||
this.objectMapper = objectMapper;
|
||||
this.policyEvaluator = policyEvaluator;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,21 +83,24 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
JsonNode statements;
|
||||
JsonNode root;
|
||||
try {
|
||||
statements = objectMapper.readTree(trustPolicyDocument).path("Statement");
|
||||
root = objectMapper.readTree(trustPolicyDocument);
|
||||
} catch (JsonProcessingException e) {
|
||||
LOG.warnv("Failed to parse web-identity trust policy: {0}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
JsonNode statements = root.path("Statement");
|
||||
if (!TrustPolicyStatements.wellFormed(statements)) {
|
||||
return false;
|
||||
}
|
||||
Map<String, List<String>> context = context(issuerKeyPrefix, claims, roleSessionName, roleTags);
|
||||
String version = root.path("Version").asText(null);
|
||||
|
||||
boolean allow = false;
|
||||
if (statements.isArray()) {
|
||||
for (JsonNode stmt : statements) {
|
||||
switch (evaluate(action, stmt, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName, roleTags)) {
|
||||
switch (evaluate(action, stmt, oidcProviderArn, context, version)) {
|
||||
case DENY -> { return false; }
|
||||
case ALLOW -> allow = true;
|
||||
case NO_MATCH -> { }
|
||||
@@ -105,24 +109,22 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
return allow;
|
||||
}
|
||||
if (statements.isObject()) {
|
||||
return evaluate(action, statements, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName,
|
||||
roleTags) == Match.ALLOW;
|
||||
return evaluate(action, statements, oidcProviderArn, context, version) == Match.ALLOW;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private enum Match { ALLOW, DENY, NO_MATCH }
|
||||
|
||||
private Match evaluate(String action, JsonNode stmt, String oidcProviderArn, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims, String roleSessionName,
|
||||
Map<String, List<String>> roleTags) {
|
||||
private Match evaluate(String action, JsonNode stmt, String oidcProviderArn, Map<String, List<String>> context,
|
||||
String version) {
|
||||
if (!actionApplies(stmt, action)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
if (!matchesFederatedPrincipal(stmt.get("Principal"), oidcProviderArn)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
if (!conditionsSatisfied(stmt.get("Condition"), issuerKeyPrefix, claims, roleSessionName, roleTags)) {
|
||||
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context, version)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
return TrustPolicyStatements.denies(stmt) ? Match.DENY : Match.ALLOW;
|
||||
@@ -195,104 +197,17 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates the condition block. Every operator block and every key within it must be satisfied
|
||||
* (AWS ANDs them). Only the string operators meaningful for OIDC claims are handled; a condition
|
||||
* using anything else does not match, which fails closed.
|
||||
* The request context the trust policy is read with: the keys given in full ({@code roleTags}: the role's tags,
|
||||
* the token's request tags and source identity), each claim under the issuer's key prefix
|
||||
* ({@code <provider-host-and-path>:sub}), and the session name as {@code sts:RoleSessionName}.
|
||||
*/
|
||||
private boolean conditionsSatisfied(JsonNode conditionNode, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims, String roleSessionName,
|
||||
Map<String, List<String>> roleTags) {
|
||||
if (conditionNode == null || conditionNode.isNull()) {
|
||||
// No condition constraints — the federated principal alone is enough.
|
||||
return true;
|
||||
private static Map<String, List<String>> context(String issuerKeyPrefix, Map<String, List<String>> claims,
|
||||
String roleSessionName, Map<String, List<String>> roleTags) {
|
||||
Map<String, List<String>> context = new HashMap<>(roleTags);
|
||||
claims.forEach((name, values) -> context.put(issuerKeyPrefix + ":" + name, values));
|
||||
if (roleSessionName != null) {
|
||||
context.put(ROLE_SESSION_NAME_KEY, List.of(roleSessionName));
|
||||
}
|
||||
if (!conditionNode.isObject()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Iterator<Map.Entry<String, JsonNode>> operators = conditionNode.fields();
|
||||
while (operators.hasNext()) {
|
||||
Map.Entry<String, JsonNode> operatorEntry = operators.next();
|
||||
String operator = operatorEntry.getKey();
|
||||
JsonNode keys = operatorEntry.getValue();
|
||||
if (!keys.isObject()) {
|
||||
return false;
|
||||
}
|
||||
Iterator<Map.Entry<String, JsonNode>> keyIterator = keys.fields();
|
||||
while (keyIterator.hasNext()) {
|
||||
Map.Entry<String, JsonNode> keyEntry = keyIterator.next();
|
||||
if (!keySatisfied(operator, keyEntry.getKey(), keyEntry.getValue(),
|
||||
issuerKeyPrefix, claims, roleSessionName, roleTags)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean keySatisfied(String operator, String conditionKey, JsonNode expected,
|
||||
String issuerKeyPrefix, Map<String, List<String>> claims,
|
||||
String roleSessionName, Map<String, List<String>> roleTags) {
|
||||
List<String> actual = ROLE_SESSION_NAME_KEY.equalsIgnoreCase(conditionKey)
|
||||
? (roleSessionName == null ? List.of() : List.of(roleSessionName))
|
||||
: TrustPolicyStatements.roleValues(conditionKey, roleTags)
|
||||
.orElseGet(() -> resolveClaim(conditionKey, issuerKeyPrefix, claims));
|
||||
List<String> expectedValues = textValues(expected);
|
||||
if (expectedValues.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return switch (operator) {
|
||||
case "StringEquals" -> actual.stream().anyMatch(expectedValues::contains);
|
||||
case "StringNotEquals" -> actual.stream().noneMatch(expectedValues::contains);
|
||||
case "StringLike" -> actual.stream().anyMatch(
|
||||
a -> expectedValues.stream().anyMatch(e -> IamPolicyEvaluator.caseSensitiveGlobMatches(e, a)));
|
||||
case "StringNotLike" -> actual.stream().noneMatch(
|
||||
a -> expectedValues.stream().anyMatch(e -> IamPolicyEvaluator.caseSensitiveGlobMatches(e, a)));
|
||||
default -> {
|
||||
LOG.debugv("Unsupported web-identity trust policy condition operator: {0}", operator);
|
||||
yield false;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a policy condition key such as
|
||||
* {@code oidc.eks.us-east-1.amazonaws.com/id/ABC123:sub} to the token's claim values. The key
|
||||
* prefix is the issuer with its scheme stripped, which is how the AWS console, eksctl, and
|
||||
* Terraform all render it.
|
||||
*/
|
||||
private List<String> resolveClaim(String conditionKey, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims) {
|
||||
if (conditionKey == null) {
|
||||
return List.of();
|
||||
}
|
||||
int separator = conditionKey.lastIndexOf(':');
|
||||
if (separator < 0) {
|
||||
return List.of();
|
||||
}
|
||||
String prefix = conditionKey.substring(0, separator);
|
||||
String claimName = conditionKey.substring(separator + 1);
|
||||
|
||||
// The provider prefix must be this token's issuer; a condition pinned to a different
|
||||
// provider must not be satisfied by our claims.
|
||||
if (!prefix.equalsIgnoreCase(issuerKeyPrefix)) {
|
||||
return List.of();
|
||||
}
|
||||
return claims.getOrDefault(claimName.toLowerCase(), List.of());
|
||||
}
|
||||
|
||||
private List<String> textValues(JsonNode node) {
|
||||
if (node.isTextual()) {
|
||||
return List.of(node.asText());
|
||||
}
|
||||
if (node.isArray()) {
|
||||
return StreamSupport
|
||||
.stream(node.spliterator(), false)
|
||||
.filter(JsonNode::isTextual)
|
||||
.map(JsonNode::asText)
|
||||
.toList();
|
||||
}
|
||||
return List.of();
|
||||
return context;
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,9 @@ class SAMLTrustPolicyEvaluatorTest {
|
||||
"iss", List.of("https://idp.example.test/saml"),
|
||||
"sub", List.of("saml-subject"));
|
||||
|
||||
private final SAMLTrustPolicyEvaluator evaluator = new SAMLTrustPolicyEvaluator(new ObjectMapper());
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private final SAMLTrustPolicyEvaluator evaluator =
|
||||
new SAMLTrustPolicyEvaluator(MAPPER, new IamPolicyEvaluator(MAPPER));
|
||||
|
||||
private static String policy(String condition) {
|
||||
return """
|
||||
@@ -53,6 +55,39 @@ class SAMLTrustPolicyEvaluatorTest {
|
||||
"alice", Map.of()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The trust policy is read by the condition engine every other policy is, so the set operators, {@code IfExists}
|
||||
* and {@code Null} read as they do anywhere: {@code ForAllValues} on {@code aws:TagKeys} holds while every tag the
|
||||
* assertion passes is one it names, and a negated operator matches a key the request does not carry.
|
||||
*/
|
||||
@Test
|
||||
void readsEveryOperatorTheConditionEngineDoes() {
|
||||
Map<String, List<String>> oneTag = Map.of("aws:RequestTag/access-team", List.of("eng"),
|
||||
"aws:TagKeys", List.of("access-team"));
|
||||
Map<String, List<String>> twoTags = Map.of("aws:RequestTag/access-team", List.of("eng"),
|
||||
"aws:RequestTag/cost-center", List.of("1"), "aws:TagKeys", List.of("access-team", "cost-center"));
|
||||
String onlyTeam = policy("{\"ForAllValues:StringEquals\":{\"aws:TagKeys\":[\"access-team\"]}}");
|
||||
assertTrue(evaluator.allows(onlyTeam, PROVIDER, CLAIMS, null, oneTag));
|
||||
assertFalse(evaluator.allows(onlyTeam, PROVIDER, CLAIMS, null, twoTags));
|
||||
assertTrue(allows(policy("{\"StringNotEquals\":{\"aws:RequestTag/access-team\":\"ops\"}}"), null));
|
||||
assertTrue(allows(policy("{\"Null\":{\"aws:RequestTag/access-team\":\"true\"}}"), null));
|
||||
assertFalse(evaluator.allows(policy("{\"Null\":{\"aws:RequestTag/access-team\":\"true\"}}"), PROVIDER,
|
||||
CLAIMS, null, oneTag));
|
||||
assertTrue(allows(policy("{\"StringEqualsIfExists\":{\"sts:RoleSessionName\":\"alice\"}}"), null));
|
||||
}
|
||||
|
||||
/**
|
||||
* An assertion's claims are read under the {@code saml:} keys the Service Authorization Reference gives them,
|
||||
* whatever case the policy spells them in, and under no other prefix.
|
||||
*/
|
||||
@Test
|
||||
void readsTheAssertionsClaimsUnderTheirSamlKeys() {
|
||||
assertTrue(allows(policy("{\"StringEquals\":{\"SAML:aud\":\"https://signin.aws.amazon.com/saml\"}}"),
|
||||
null));
|
||||
assertTrue(allows(policy("{\"StringEquals\":{\"saml:sub\":\"saml-subject\"}}"), null));
|
||||
assertFalse(allows(policy("{\"StringEquals\":{\"other:sub\":\"saml-subject\"}}"), null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void allowsTheRoleSessionNameThePolicyRequires() {
|
||||
assertTrue(allows(policy("{\"StringEquals\":{\"sts:RoleSessionName\":\"alice\"}}"), "alice"));
|
||||
|
||||
@@ -319,6 +319,38 @@ class StsRegisteredOidcProviderIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The trust policy's {@code aud} key holds the one audience the token was accepted for, whatever its place in the
|
||||
* token's list: the Service Authorization Reference types the key {@code String}, a single value, and it is the
|
||||
* audience the response returns. A statement requiring that audience allows a token naming another one first, and a
|
||||
* statement excluding it refuses that token.
|
||||
*/
|
||||
@Test
|
||||
void theAudienceKeyIsTheAudienceTheTokenWasAcceptedFor() throws Exception {
|
||||
String host = issuer.substring("https://".length());
|
||||
ObjectNode audiences = objectMapper.createObjectNode();
|
||||
audiences.putArray("aud").add("another-client").add("sts.amazonaws.com");
|
||||
String token = token(issuer, "sts.amazonaws.com", privateKey, KEY_ID, audiences);
|
||||
Role requiring = audienceRole(host, "StringEquals");
|
||||
Role excluding = audienceRole(host, "StringNotEquals");
|
||||
try {
|
||||
assertEquals("sts.amazonaws.com", assume(requiring, token).audience());
|
||||
StsException refused = assertThrows(StsException.class, () -> assume(excluding, token));
|
||||
assertEquals(403, refused.statusCode());
|
||||
} finally {
|
||||
iam.deleteRole(b -> b.roleName(requiring.roleName()));
|
||||
iam.deleteRole(b -> b.roleName(excluding.roleName()));
|
||||
}
|
||||
}
|
||||
|
||||
private Role audienceRole(String host, String operator) {
|
||||
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{"
|
||||
+ "\"Federated\":\"" + providerArn + "\"},\"Action\":\"sts:AssumeRoleWithWebIdentity\","
|
||||
+ "\"Condition\":{\"" + operator + "\":{\"" + host + ":aud\":\"sts.amazonaws.com\"}}}]}";
|
||||
return iam.createRole(b -> b.roleName("web-aud-" + UUID.randomUUID().toString().substring(0, 8))
|
||||
.assumeRolePolicyDocument(trust)).role();
|
||||
}
|
||||
|
||||
/** The nested claim the IAM user guide gives a token's session tags in, passing Project as {@code value}. */
|
||||
private ObjectNode principalTag(String value) {
|
||||
ObjectNode claims = objectMapper.createObjectNode();
|
||||
|
||||
@@ -27,8 +27,9 @@ class TrustPolicyStatementsTest {
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final AssumeRolePolicyEvaluator assumeRole =
|
||||
new AssumeRolePolicyEvaluator(mapper, new IamPolicyEvaluator(mapper));
|
||||
private final WebIdentityTrustPolicyEvaluator webIdentity = new WebIdentityTrustPolicyEvaluator(mapper);
|
||||
private final SAMLTrustPolicyEvaluator saml = new SAMLTrustPolicyEvaluator(mapper);
|
||||
private final WebIdentityTrustPolicyEvaluator webIdentity =
|
||||
new WebIdentityTrustPolicyEvaluator(mapper, new IamPolicyEvaluator(mapper));
|
||||
private final SAMLTrustPolicyEvaluator saml = new SAMLTrustPolicyEvaluator(mapper, new IamPolicyEvaluator(mapper));
|
||||
|
||||
/** A path that assumes a role, with the principal and action a statement names to reach it. */
|
||||
enum Path {
|
||||
|
||||
@@ -20,7 +20,7 @@ class WebIdentityTrustPolicyEvaluatorTest {
|
||||
private static final String SESSION_NAME = "build-42";
|
||||
|
||||
private final WebIdentityTrustPolicyEvaluator evaluator =
|
||||
new WebIdentityTrustPolicyEvaluator(new ObjectMapper());
|
||||
new WebIdentityTrustPolicyEvaluator(new ObjectMapper(), new IamPolicyEvaluator(new ObjectMapper()));
|
||||
|
||||
/** The canonical IRSA trust policy shape. */
|
||||
private String irsaTrustPolicy(String subject) {
|
||||
@@ -49,6 +49,49 @@ class WebIdentityTrustPolicyEvaluatorTest {
|
||||
return evaluator.allows(policy, PROVIDER_ARN, PREFIX, claims, SESSION_NAME, Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* The trust policy is read by the condition engine every other policy is: an EKS IRSA policy matching its subject
|
||||
* with {@code StringLike} and its audience with {@code ForAnyValue:StringEquals}, a {@code ForAllValues} on
|
||||
* {@code aws:TagKeys}, and a negated operator on a claim the token does not carry, which matches.
|
||||
*/
|
||||
@Test
|
||||
void readsEveryOperatorTheConditionEngineDoes() {
|
||||
String forAnyAudience = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{
|
||||
"StringLike":{"%s:sub":"system:serviceaccount:%s:*"},
|
||||
"ForAnyValue:StringEquals":{"%s:aud":["sts.amazonaws.com","other"]}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX, NAMESPACE, PREFIX);
|
||||
assertTrue(allows(forAnyAudience, claims(SUBJECT)));
|
||||
assertFalse(allows(forAnyAudience, claims("system:serviceaccount:other:app")));
|
||||
|
||||
String onlyProject = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{
|
||||
"ForAllValues:StringEquals":{"aws:TagKeys":["Project"]},
|
||||
"StringNotEquals":{"%s:amr":"unauthenticated"}}}]}""".formatted(PROVIDER_ARN, PREFIX);
|
||||
assertTrue(evaluator.allows(onlyProject, PROVIDER_ARN, PREFIX, claims(SUBJECT), SESSION_NAME,
|
||||
Map.of("aws:TagKeys", List.of("Project"))));
|
||||
assertFalse(evaluator.allows(onlyProject, PROVIDER_ARN, PREFIX, claims(SUBJECT), SESSION_NAME,
|
||||
Map.of("aws:TagKeys", List.of("Project", "Team"))));
|
||||
}
|
||||
|
||||
/**
|
||||
* A negated operator over an empty list of values holds, as it does in every other policy: "if a single negated
|
||||
* matching condition operator includes multiple values for a context key, those values are evaluated using a
|
||||
* logical NOR", the NOR of no values being true, and Access Analyzer's empty-array check says "when the condition
|
||||
* value is empty, the condition returns true". A positive operator over one matches nothing.
|
||||
*/
|
||||
@Test
|
||||
void aNegatedOperatorOverNoValuesHolds() {
|
||||
String negated = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Federated":"%s"},
|
||||
"Action":"sts:AssumeRoleWithWebIdentity","Condition":{"StringNotEquals":{"%s:aud":[]}}}]}"""
|
||||
.formatted(PROVIDER_ARN, PREFIX);
|
||||
assertTrue(allows(negated, claims(SUBJECT)));
|
||||
assertFalse(allows(negated.replace("StringNotEquals", "StringEquals"), claims(SUBJECT)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags of the role being assumed, which a trust policy reads under the keys its type carries beside the
|
||||
* token's claims: a tag key matched whatever its case, its value exactly, and a role without the tag not matching.
|
||||
|
||||
Reference in new issue
Block a user