mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(sts): read the session tags a request, an assertion and a token pass (#9289)
A session's tags are principal tags of its requests, "when you request a session, you can specify principal tags as the session tags. The tags apply to requests that you make using the session's credentials", and this package read none of them. AssumeRole and GetFederationToken counted the Tags member toward the token size and then dropped it, and the two operations that take session tags inside a SAML assertion or a web identity token, where the model declares no Tags member at all, had nowhere to take them from, so aws:PrincipalTag held only what was stored on the user or the role. A session records the tags it was minted with now, from wherever its own operation takes them: the Tags member on AssumeRole and GetFederationToken, the assertion's https://aws.amazon.com/SAML/Attributes/PrincipalTag:<key> attributes on AssumeRoleWithSAML, and the token's https://aws.amazon.com/tags claims on AssumeRoleWithWebIdentity, in both formats AWS reads those in, the nested object under principal_tags and the flattened claims prefixed https://aws.amazon.com/tags/principal_tags/. GetSessionToken and AssumeRoot declare no way to pass one and record none. What a request publishes is the identity's tags with the session's own over them: the role's tags for a role session, and for a federated user the tags of the user whose key minted it, where it carried none at all, "the session principal tags include the user tags and the passed session tags". A session tag "overrides the role" tag of the same key, matched without case as IAM matches a tag key on a user or a role, "not case sensitive, but case is preserved", so the session's own spelling is the one published. One value per tag: "you must pass a single value for each session tag" and STS "does not support multi-valued session tags". The published nested example writes each value as an array holding one string and the flattened format as a plain claim, so both are read, while a tag carrying more than one value is left unread rather than cut down to its first. A role's trust policy has to permit the tagging as well as the assume: "trust policies for all roles connected to the identity provider passing tags must have the sts:TagSession permission. For roles without this permission in the trust policy, the AssumeRole operation fails." All three assume operations read their own trust policy for that action when the request, the assertion or the token carries a tag, with the same principals and conditions as the assume, and answer AccessDenied naming it. Without that reading a caller the policy lets assume a role could choose the principal tags downstream permissions are conditioned on, which is the whole point of the permission. The caller's own half was already here, the generated tagging table requiring sts:TagSession of a request that carries Tags, so a tagged AssumeRole is held to both policies and a tagged GetFederationToken to the caller's alone, having no trust policy to read. A tag that is not one key with one value is refused rather than read as the first value or dropped: an attribute with several AttributeValue elements or none, an attribute whose name ends at the colon, and a token claim that is neither a string nor a one-element array. Nothing published says what AWS answers a malformed session tag, so those sentences are this package's own, and a tag a policy would have been evaluated with cannot go missing quietly. An assertion's value is stored as it was signed, spaces included, where trimming it would hand a policy a value the provider never asserted. Two tags of one request whose keys differ only in case are one tag, the later winning, as a tag key on an identity is: kept as two they would reach a policy as one key with the other's value dropped, and a Deny on that value would stop matching. Session tags are state the token carries, "session policies and session tags add to the session token size", so they count against the limit and into what the session reports. The two operations that take them from a message measure that once the assertion or the token has been verified, which is the first point the tags exist, rather than before the operation runs where the declared members are read. Two published pieces are left, named on the page rather than guessed at here. The transitive tag keys beside the tags are not read, so no tag passes into a chained session, which is AWS's own default and leaves only the opt-in missing; a key stored unread would have said otherwise. And the plaintext limits a session tag is held to are read where the model declares the members that carry them, which leaves the number and the length of a tag inside an assertion or a token unchecked, nothing published saying what AWS answers there; what does hold them is the token size. Covered end to end under enforcement by a session tag that decides a call and overrides the role's tag of that key, by one that brings a Deny on, by a caller whose trust policy permits the assume but not the tagging, and by a federated session whose tag is the whole of what decides it; over the API by a signed assertion whose attributes reach the session, by a spaced value kept as signed, by an attribute carrying no single value and one naming no key, and by a tag set too large for the token it would be carried in; at the service level by the merge, the case-insensitive replacement within a request and across the identity's tags, and the federated user's two halves; on the handler by the Tags member reaching the session it mints, by the token's tags counting toward what the session reports, and by the long-term session recording nothing; and on the token verifier by both claim formats, a multi-valued tag, a tag with no key and a token that passes none.
This commit is contained in:
1 parent
8a0903f42b
commit
d2a3e2624e
16 files changed
+1048
-114
No files matched your search
@@ -3840,12 +3840,16 @@ floci populates:
|
||||
`o-.../r-.../ou-.../`, which is the value the key's own published condition compares with
|
||||
`StringEquals`, and is `o-.../r-.../` for an account the organization holds at its root.
|
||||
- `aws:PrincipalTag/<key>`: the stored tags of the IAM user making the request, including a
|
||||
`GetSessionToken` session, or of the role an assumed-role session represents. Tags are read
|
||||
`GetSessionToken` session, or of the role an assumed-role session represents, with the session
|
||||
tags the credentials were minted with over them. Tags are read
|
||||
from that identity's account and copied for the request; later requests see tag updates and
|
||||
removals. Identity policies, resource policies and `AssumeRole` trust policies see the same
|
||||
caller tags. A role session uses its role's tags, not those of the user that assumed it.
|
||||
Untagged identities, account-root principals and federated users have no stored principal tags.
|
||||
STS session tags, their overrides and transitive inheritance are not implemented.
|
||||
removals, while the session tags are the session's own and do not change after it is minted.
|
||||
Identity policies, resource policies and `AssumeRole` trust policies see the same
|
||||
caller tags. A role session uses its role's tags, not those of the user that assumed it, and a
|
||||
federated user carries the tags of the user whose key minted it. An account-root principal has
|
||||
no stored tags and no way to pass one. A session tag replaces the identity's tag of that key
|
||||
whatever its case; [STS](sts.md#session-tags) has where each operation takes its session tags
|
||||
from, and the transitive inheritance that is not implemented.
|
||||
- `aws:PrincipalType` and `aws:userid`: resolved from the same lookup as `aws:PrincipalArn`, so
|
||||
they always describe the same credential. The values follow the user guide's principal key
|
||||
values list: `Account` with the account id for the account-root principal and for a session
|
||||
|
||||
+83
-6
@@ -448,20 +448,97 @@ request context holds `sts:RoleSessionName`, `sts:ExternalId` when the caller pa
|
||||
guard, refuses a call that omits it or passes another value, and a conditional `Deny` applies only
|
||||
when its condition matches.
|
||||
|
||||
`aws:PrincipalTag/<key>` contains the stored tags of the calling IAM user or assumed role.
|
||||
The target role's tags do not supply the caller's principal tags. A chained request reads the
|
||||
current caller role's tags; tags on the user that originally assumed it are not inherited.
|
||||
`aws:PrincipalTag/<key>` contains the stored tags of the calling IAM user or assumed role, with
|
||||
the session tags its credentials were minted with over them, as [Session Tags](#session-tags)
|
||||
below describes. The target role's tags do not supply the caller's principal tags. A chained
|
||||
request reads the current caller role's tags and its own session tags; tags on the user that
|
||||
originally assumed it are not inherited, and neither are the transitive session tags AWS carries
|
||||
into a chained session.
|
||||
|
||||
A trust policy with a statement whose `Effect` is not exactly `Allow` or `Deny`, or whose
|
||||
`Condition` is not an object of non-empty operator objects, lets no one assume the role, the same
|
||||
on `AssumeRole`, `AssumeRoleWithWebIdentity` and `AssumeRoleWithSAML`. IAM refuses such a document
|
||||
when it is written; Floci stores it as given, so the whole document is refused when it is read.
|
||||
|
||||
### Session Tags
|
||||
|
||||
A session carries tags of its own, and its requests publish them as `aws:PrincipalTag/<key>`:
|
||||
"when you request a session, you can specify principal tags as the session tags. The tags apply to
|
||||
requests that you make using the session's credentials." Each operation takes them where AWS
|
||||
publishes them for it, which the model says the same way, three of the six declaring no `Tags`
|
||||
member at all:
|
||||
|
||||
| Operation | Where a session tag comes from |
|
||||
|-----------|-------------------------------|
|
||||
| `AssumeRole` | the request's `Tags` member |
|
||||
| `AssumeRoleWithSAML` | the assertion's `https://aws.amazon.com/SAML/Attributes/PrincipalTag:<key>` attributes |
|
||||
| `AssumeRoleWithWebIdentity` | the token's `https://aws.amazon.com/tags` claims, in either published format |
|
||||
| `GetFederationToken` | the request's `Tags` member |
|
||||
| `GetSessionToken`, `AssumeRoot` | nothing: neither declares a way to pass one |
|
||||
|
||||
A role's trust policy has to permit the tagging as well as the assume: "when using session tags,
|
||||
trust policies for all roles connected to the identity provider passing tags must have the
|
||||
sts:TagSession permission. For roles without this permission in the trust policy, the AssumeRole
|
||||
operation fails." All three assume operations read their trust policy for `sts:TagSession` when the
|
||||
request, the assertion or the token carries a tag, with the same principals and conditions as the
|
||||
assume itself, and answer `AccessDenied` naming that action when it is not allowed. An untagged
|
||||
request is not held to it. `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 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
|
||||
request that carries `Tags`, which [enforcement](iam.md#iam-enforcement-mode) reads before the
|
||||
operation runs, answering `User is not authorized to perform: sts:TagSession`. So a tagged
|
||||
`AssumeRole` is held to both permissions, the caller's and the role's, and a tagged
|
||||
`GetFederationToken` to the caller's alone, having no trust policy to read. The two operations that
|
||||
take their tags from an assertion or a token carry no `Tags` member, so nothing asks their caller's
|
||||
policy for the action and the trust policy is the whole of it.
|
||||
|
||||
The session's tags sit over the tags of the identity it acts as. For a role session that is the
|
||||
role's own tags, for a federated user the tags of the user whose key minted it, "the session
|
||||
principal tags include the user tags and the passed session tags", and a session tag "overrides the
|
||||
role" tag of the same key. The key is matched without case, as IAM matches a tag key on a user or a
|
||||
role, so a session passing `Department` replaces a `department` the role carries and the session's
|
||||
own spelling is the one published. Two tags in one request whose keys differ only in case are one
|
||||
tag, the later winning, for the same reason: "you cannot have separate Department and department
|
||||
tag keys", and a second such tag "replaces the first tag".
|
||||
|
||||
A tag carries exactly one value, since "you must pass a single value for each session tag" and AWS
|
||||
STS "does not support multi-valued session tags". The token's nested format writes that value as an
|
||||
array holding one string and its flattened format as a plain claim, and both are read. Anything
|
||||
else is refused rather than read as the first value or dropped: a `PrincipalTag:` attribute with
|
||||
several `AttributeValue` elements or none answers `InvalidIdentityToken` with
|
||||
`Session tag <key> must carry exactly one AttributeValue: a session tag takes a single value.`, one
|
||||
whose name ends at the colon answers
|
||||
`A PrincipalTag attribute must name the tag key after the colon.`, and a token whose tag claim is
|
||||
neither a string nor a one-element array is refused the same way. Those three sentences are Floci's
|
||||
own: nothing published says what AWS answers a malformed session tag, and a tag a policy would have
|
||||
been evaluated with cannot go missing quietly. An assertion's value is stored as it was signed,
|
||||
spaces included, tag values being allowed them.
|
||||
|
||||
Session tags are state the token carries, so they count against the
|
||||
[4,096-byte limit](iam.md#what-a-sessions-token-costs-and-when-it-is-refused) and are reported in
|
||||
`SessionTokenSize` and `SessionTokenUtilization`. For the two operations that take them from a
|
||||
message rather than from a request member, that is measured once the assertion or the token has
|
||||
been verified, which is the first point the tags exist, rather than before the operation runs where
|
||||
the declared members are read.
|
||||
|
||||
Two published pieces of this are not here yet. The transitive tag keys an assertion or a token
|
||||
carries beside the tags are not read, so a tag never passes into a chained session: that is AWS's
|
||||
default, "by default, AWS STS does not pass tags to subsequent role sessions", and the opt-in is
|
||||
missing. And the plaintext limits a session tag is held to, 50 tags with keys of 128 characters and
|
||||
values of 256, are read where the model declares the members that carry them, which leaves the
|
||||
number and the length of the tags inside an assertion or a token unchecked, nothing published
|
||||
saying what AWS answers when those break; what does hold them is the token size above.
|
||||
|
||||
### Known limitations
|
||||
|
||||
- **Session tags and source identity are not modelled.** `aws:RequestTag/*`, `aws:TagKeys`,
|
||||
`sts:TransitiveTagKeys` and `sts:SourceIdentity` are not in the request context, so a condition
|
||||
on them does not match, and `sts:TagSession` and `sts:SetSourceIdentity` are not checked.
|
||||
- **The tag and source-identity condition keys are not in the request context.**
|
||||
`aws:RequestTag/*`, `aws:TagKeys`, `sts:TransitiveTagKeys` and `sts:SourceIdentity` are not
|
||||
populated, so a condition on them does not match. A trust policy keyed on one of them therefore
|
||||
reads as unsatisfied, including on the `sts:TagSession` permission a tagged assume needs, and
|
||||
`sts:SetSourceIdentity` is not checked at all.
|
||||
|
||||
## Web Identity Validation (IRSA)
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.floci.aws.core.common;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* The verified claims of a web-identity JWT.
|
||||
@@ -8,6 +9,13 @@ import java.util.List;
|
||||
* @param issuer the {@code iss} claim
|
||||
* @param subject the {@code sub} claim. For IRSA, {@code system:serviceaccount:<ns>:<sa>}
|
||||
* @param audiences the {@code aud} claim, normalized to a list (JWT allows string or array)
|
||||
* @param principalTags the session tags the token passes, from either of the two claim formats
|
||||
* AWS publishes for them, and empty when it passes none
|
||||
*/
|
||||
public record WebIdentityToken(String issuer, String subject, List<String> audiences) {
|
||||
public record WebIdentityToken(String issuer, String subject, List<String> audiences,
|
||||
Map<String, String> principalTags) {
|
||||
|
||||
public WebIdentityToken(String issuer, String subject, List<String> audiences) {
|
||||
this(issuer, subject, audiences, Map.of());
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,9 @@ import java.security.interfaces.RSAPublicKey;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
@@ -36,6 +38,9 @@ public class WebIdentityTokenVerifier {
|
||||
|
||||
/** Tolerance for clock drift between Floci and a token minted elsewhere. */
|
||||
private static final long CLOCK_SKEW_SECONDS = 60;
|
||||
/** The namespace AWS publishes a token's session tags under, whichever format they take. */
|
||||
private static final String TAGS_CLAIM = "https://aws.amazon.com/tags";
|
||||
private static final String FLATTENED_TAG_CLAIM = TAGS_CLAIM + "/principal_tags/";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@@ -121,7 +126,7 @@ public class WebIdentityTokenVerifier {
|
||||
throw new InvalidTokenException("The web identity token has no subject claim");
|
||||
}
|
||||
|
||||
return new WebIdentityToken(issuer, subject, audiences);
|
||||
return new WebIdentityToken(issuer, subject, audiences, readPrincipalTags(claims));
|
||||
}
|
||||
|
||||
private void verifyValidityWindow(JsonNode claims) throws InvalidTokenException {
|
||||
@@ -155,6 +160,52 @@ public class WebIdentityTokenVerifier {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The session tags the token passes, in either format AWS reads them in. The nested format
|
||||
* puts them "under the principal_tags key" inside the {@code https://aws.amazon.com/tags}
|
||||
* namespace; the flattened one, "compatible with identity providers that don't support nested
|
||||
* objects in JWT claims", carries each as its own claim "with the prefix
|
||||
* https://aws.amazon.com/tags/principal_tags/". Both "achieve the same result", so both are
|
||||
* read, the flattened claims last for a token that somehow carries both.
|
||||
*
|
||||
* <p>A tag's value is one string: "each principal tag is a single string value", while the
|
||||
* published nested example writes each as an array holding that one value, so a single-element
|
||||
* array is read as the value it holds. Anything else is a multi-valued session tag, which "AWS
|
||||
* STS does not support", and the token is refused rather than verified with that tag dropped:
|
||||
* a tag a policy would have been evaluated with cannot go missing quietly. The transitive tag
|
||||
* keys the same namespace carries are not read: nothing here passes a tag into a later session
|
||||
* yet, and a key stored unread would say otherwise.
|
||||
*/
|
||||
private Map<String, String> readPrincipalTags(JsonNode claims) throws InvalidTokenException {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (Map.Entry<String, JsonNode> tag : claims.path(TAGS_CLAIM).path("principal_tags").properties()) {
|
||||
tags.put(tag.getKey(), singleValue(tag.getKey(), tag.getValue()));
|
||||
}
|
||||
for (Map.Entry<String, JsonNode> claim : claims.properties()) {
|
||||
if (!claim.getKey().startsWith(FLATTENED_TAG_CLAIM)) {
|
||||
continue;
|
||||
}
|
||||
String key = claim.getKey().substring(FLATTENED_TAG_CLAIM.length());
|
||||
if (key.isEmpty()) {
|
||||
throw new InvalidTokenException("The web identity token carries a session tag with no key");
|
||||
}
|
||||
tags.put(key, singleValue(key, claim.getValue()));
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/** The one value a tag claim carries, written as a string or as an array holding it alone. */
|
||||
private static String singleValue(String key, JsonNode value) throws InvalidTokenException {
|
||||
if (value.isTextual()) {
|
||||
return value.asText();
|
||||
}
|
||||
if (value.isArray() && value.size() == 1 && value.get(0).isTextual()) {
|
||||
return value.get(0).asText();
|
||||
}
|
||||
throw new InvalidTokenException("The web identity token's session tag " + key
|
||||
+ " does not carry a single value");
|
||||
}
|
||||
|
||||
private List<String> readAudiences(JsonNode claims) {
|
||||
List<String> audiences = new ArrayList<>();
|
||||
JsonNode aud = claims.get("aud");
|
||||
|
||||
@@ -47,6 +47,13 @@ public class AssumeRolePolicyEvaluator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(AssumeRolePolicyEvaluator.class);
|
||||
private static final String ASSUME_ROLE_ACTION = "sts:AssumeRole";
|
||||
/**
|
||||
* What a trust policy has to allow beside the assume for the request's session tags to be
|
||||
* taken: "when using session tags, trust policies for all roles connected to the identity
|
||||
* provider passing tags must have the sts:TagSession permission. For roles without this
|
||||
* permission in the trust policy, the AssumeRole operation fails."
|
||||
*/
|
||||
public static final String TAG_SESSION_ACTION = "sts:TagSession";
|
||||
private static final Pattern ACCOUNT_ROOT_ARN =
|
||||
Pattern.compile("^arn:" + AwsArnUtils.PARTITION_REGEX + ":iam::(\\d{12}):root$");
|
||||
|
||||
@@ -95,6 +102,18 @@ public class AssumeRolePolicyEvaluator {
|
||||
return decision == TrustDecision.ALLOW || decision == TrustDecision.ALLOW_ACCOUNT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the trust policy lets this caller tag the session it is assuming, which is the
|
||||
* {@link #TAG_SESSION_ACTION} permission read on the same document, with the same principals
|
||||
* and the same conditions as the assume itself.
|
||||
*/
|
||||
public boolean allowsTagging(String trustPolicyDocument, IamService.CallerArns caller,
|
||||
String callerAccount, Map<String, List<String>> requestContext) {
|
||||
TrustDecision decision = decide(TAG_SESSION_ACTION, trustPolicyDocument, caller, callerAccount,
|
||||
requestContext);
|
||||
return decision == TrustDecision.ALLOW || decision == TrustDecision.ALLOW_ACCOUNT;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if {@code trustPolicyDocument} lets some principal of {@code account} assume the
|
||||
* role: the account itself, through its root, or a principal of it that an Allow names, each
|
||||
@@ -150,7 +169,7 @@ public class AssumeRolePolicyEvaluator {
|
||||
}
|
||||
Iterable<JsonNode> statementList = statements.isArray() ? statements : List.of(statements);
|
||||
for (JsonNode stmt : statementList) {
|
||||
if (effectOf(stmt) != Match.ALLOW || !actionApplies(stmt)) {
|
||||
if (effectOf(stmt) != Match.ALLOW || !actionApplies(stmt, ASSUME_ROLE_ACTION)) {
|
||||
continue;
|
||||
}
|
||||
JsonNode aws = stmt.path("Principal").path("AWS");
|
||||
@@ -195,6 +214,12 @@ public class AssumeRolePolicyEvaluator {
|
||||
*/
|
||||
public TrustDecision decide(String trustPolicyDocument, IamService.CallerArns caller,
|
||||
String callerAccount, Map<String, List<String>> requestContext) {
|
||||
return decide(ASSUME_ROLE_ACTION, trustPolicyDocument, caller, callerAccount, requestContext);
|
||||
}
|
||||
|
||||
/** The same, for one of the two actions a trust policy is read for. */
|
||||
private TrustDecision decide(String action, String trustPolicyDocument, IamService.CallerArns caller,
|
||||
String callerAccount, Map<String, List<String>> requestContext) {
|
||||
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
@@ -219,8 +244,8 @@ public class AssumeRolePolicyEvaluator {
|
||||
Iterable<JsonNode> statementList = statements.isArray() ? statements : List.of(statements);
|
||||
TrustDecision decision = TrustDecision.NEUTRAL;
|
||||
for (JsonNode stmt : statementList) {
|
||||
TrustDecision match =
|
||||
evaluateStatement(stmt, callerArn, principalArn, callerAccount, context, version);
|
||||
TrustDecision match = evaluateStatement(action, stmt, callerArn, principalArn, callerAccount,
|
||||
context, version);
|
||||
if (match == TrustDecision.EXPLICIT_DENY) {
|
||||
return TrustDecision.EXPLICIT_DENY;
|
||||
}
|
||||
@@ -305,10 +330,10 @@ public class AssumeRolePolicyEvaluator {
|
||||
|
||||
private enum Match { ALLOW, DENY, NO_MATCH }
|
||||
|
||||
private TrustDecision evaluateStatement(JsonNode stmt, String callerArn, String principalArn,
|
||||
String callerAccount, Map<String, List<String>> context,
|
||||
String policyVersion) {
|
||||
if (!actionApplies(stmt)) {
|
||||
private TrustDecision evaluateStatement(String action, JsonNode stmt, String callerArn,
|
||||
String principalArn, String callerAccount,
|
||||
Map<String, List<String>> context, String policyVersion) {
|
||||
if (!actionApplies(stmt, action)) {
|
||||
return TrustDecision.NEUTRAL;
|
||||
}
|
||||
PrincipalMatch principal = matchPrincipal(stmt.get("Principal"), callerArn, principalArn, callerAccount);
|
||||
@@ -326,7 +351,8 @@ public class AssumeRolePolicyEvaluator {
|
||||
}
|
||||
|
||||
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal) {
|
||||
if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
|
||||
if (!actionApplies(stmt, ASSUME_ROLE_ACTION)
|
||||
|| !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
return effectOf(stmt);
|
||||
@@ -334,7 +360,8 @@ public class AssumeRolePolicyEvaluator {
|
||||
|
||||
private Match evaluateServiceStatement(JsonNode stmt, String servicePrincipal,
|
||||
Map<String, List<String>> context, String policyVersion) {
|
||||
if (!actionApplies(stmt) || !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
|
||||
if (!actionApplies(stmt, ASSUME_ROLE_ACTION)
|
||||
|| !matchesServicePrincipal(stmt.get("Principal"), servicePrincipal)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
if (!policyEvaluator.conditionMatches(stmt.get("Condition"), context, policyVersion)) {
|
||||
@@ -389,33 +416,34 @@ public class AssumeRolePolicyEvaluator {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* True if the statement's action element applies to {@code action}, which is the assume itself
|
||||
* or the {@link #TAG_SESSION_ACTION} a tagged assume also needs. 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);
|
||||
private boolean actionApplies(JsonNode stmt, String action) {
|
||||
JsonNode element = stmt.get("Action");
|
||||
if (element != null) {
|
||||
return matchesAction(element, action);
|
||||
}
|
||||
JsonNode notAction = stmt.get("NotAction");
|
||||
if (notAction != null) {
|
||||
return !matchesAssumeRoleAction(notAction);
|
||||
return !matchesAction(notAction, action);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean matchesAssumeRoleAction(JsonNode actionNode) {
|
||||
private boolean matchesAction(JsonNode actionNode, String action) {
|
||||
if (actionNode == null) {
|
||||
return false;
|
||||
}
|
||||
if (actionNode.isTextual()) {
|
||||
return IamPolicyEvaluator.globMatches(actionNode.asText(), ASSUME_ROLE_ACTION);
|
||||
return IamPolicyEvaluator.globMatches(actionNode.asText(), action);
|
||||
}
|
||||
if (actionNode.isArray()) {
|
||||
for (JsonNode a : actionNode) {
|
||||
if (a.isTextual() && IamPolicyEvaluator.globMatches(a.asText(), ASSUME_ROLE_ACTION)) {
|
||||
if (a.isTextual() && IamPolicyEvaluator.globMatches(a.asText(), action)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5155,6 +5155,35 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the session tags {@code sessionAccessKeyId} was minted with, which its requests then
|
||||
* publish as {@code aws:PrincipalTag/<key>}: "when you request a session, you can specify
|
||||
* principal tags as the session tags. The tags apply to requests that you make using the
|
||||
* session's credentials." Where they came from is the operation's business, a request member
|
||||
* on one, a SAML assertion's attributes or a web identity token's claims on another, and what
|
||||
* reaches here is the pairs themselves.
|
||||
*
|
||||
* <p>Two of those pairs whose keys differ only in case are one tag, the later winning, which is
|
||||
* what a tag key is on an identity as well: "you cannot have separate Department and department
|
||||
* tag keys", and a second such tag "replaces the first tag. A second tag is not added." Stored
|
||||
* as two they would reach a policy as one key with the other's value dropped, and a Deny keyed
|
||||
* on that value would stop matching.
|
||||
*/
|
||||
public void recordSessionTags(String sessionAccessKeyId, Map<String, String> tags) {
|
||||
if (sessionAccessKeyId == null || tags == null || tags.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<String, String> oneTagPerKey = new LinkedHashMap<>();
|
||||
tags.forEach((key, value) -> {
|
||||
oneTagPerKey.keySet().removeIf(stored -> stored.equalsIgnoreCase(key));
|
||||
oneTagPerKey.put(key, value);
|
||||
});
|
||||
sessions.get(sessionAccessKeyId).ifPresent(session -> {
|
||||
session.setSessionTags(oneTagPerKey);
|
||||
sessions.put(sessionAccessKeyId, session);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* When the credentials {@code accessKeyId} names last authenticated with an MFA device, empty
|
||||
* for a session minted without one and for every long-term key. A session assumed from such a
|
||||
@@ -6497,8 +6526,9 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
* @param userName the request's {@code aws:username}, which only an IAM user has
|
||||
* @param permissionsBoundary whether a permissions boundary is attached to the user, or to the
|
||||
* role a session assumed, which a Deny's {@code NotPrincipal} never spares
|
||||
* @param principalTags the stored user's or assumed role's tags, snapshotted for this request;
|
||||
* STS session tags are not yet recorded
|
||||
* @param principalTags the tags this request publishes, snapshotted for it: the stored user's
|
||||
* or assumed role's, with the session tags its credentials were minted
|
||||
* with over them
|
||||
* @param sessionMfa what the credentials the request was signed with say about multi-factor
|
||||
* authentication, or null when they publish neither key
|
||||
* @param organization the organization the principal's account belongs to, whose three keys go
|
||||
@@ -6807,11 +6837,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return delegatedApproverArns(session);
|
||||
}
|
||||
if (isFederatedUserSession(session)) {
|
||||
// A federated user has no aws:username at all, only the account:name userid.
|
||||
// A federated user has no aws:username at all, only the account:name userid. Its
|
||||
// principal tags are both halves the guide names: "the session principal tags include
|
||||
// the user tags and the passed session tags".
|
||||
String federatedArn = session.getRoleArn();
|
||||
return Optional.of(new CallerArns(federatedArn, federatedArn,
|
||||
CallerArns.TYPE_FEDERATED_USER,
|
||||
sessionUserId(session).orElse(null), null));
|
||||
sessionUserId(session).orElse(null), null, false,
|
||||
withSessionTags(issuingUser(session).map(IamUser::getTags).orElse(Map.of()),
|
||||
session.getSessionTags())));
|
||||
}
|
||||
String roleArn = session.getRoleArn();
|
||||
if (roleArn == null) {
|
||||
@@ -6839,7 +6873,35 @@ public class IamService implements SessionAccountLookup, ResourceProvider {
|
||||
return Optional.of(new CallerArns(sessionArn, roleArn, CallerArns.TYPE_ASSUMED_ROLE,
|
||||
sessionUserId(session).orElse(null), null,
|
||||
role.map(IamRole::getPermissionsBoundaryArn).isPresent(),
|
||||
role.map(IamRole::getTags).orElse(Map.of())));
|
||||
withSessionTags(role.map(IamRole::getTags).orElse(Map.of()), session.getSessionTags())));
|
||||
}
|
||||
|
||||
/**
|
||||
* The principal tags a session's requests publish: the tags of the identity it acts as, with
|
||||
* its own session tags over them. The guide gives the order and the collision rule both. The
|
||||
* principal tags of a session "come from any new session tags, the inherited transitive
|
||||
* session tags, and the role tags", a session tag "overrides the role" tag of the same key,
|
||||
* and a new session tag replaces an existing one "regardless of character case", which is how
|
||||
* IAM compares a tag key on a user or a role as well: "tag key values for IAM users and roles
|
||||
* are not case sensitive, but case is preserved", so the session's own spelling is the one
|
||||
* published and the identity's tag of that key in any other spelling is the one dropped.
|
||||
*/
|
||||
private static Map<String, String> withSessionTags(Map<String, String> identityTags,
|
||||
Map<String, String> sessionTags) {
|
||||
if (sessionTags.isEmpty()) {
|
||||
return identityTags;
|
||||
}
|
||||
Set<String> replaced = sessionTags.keySet().stream()
|
||||
.map(key -> key.toLowerCase(Locale.ROOT))
|
||||
.collect(Collectors.toSet());
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
identityTags.forEach((key, value) -> {
|
||||
if (!replaced.contains(key.toLowerCase(Locale.ROOT))) {
|
||||
tags.put(key, value);
|
||||
}
|
||||
});
|
||||
tags.putAll(sessionTags);
|
||||
return tags;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,7 +23,9 @@ import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -35,6 +37,11 @@ final class SAMLAssertionVerifier {
|
||||
static final String ASSERTION_INVALID = "The SAML assertion is invalid.";
|
||||
static final String SIGNATURE_INVALID = "Response signature invalid";
|
||||
private static final String ROLE_SESSION_NAME = "https://aws.amazon.com/SAML/Attributes/RoleSessionName";
|
||||
/** What an attribute carrying a session tag is named, the tag's key following the colon. */
|
||||
private static final String PRINCIPAL_TAG = "https://aws.amazon.com/SAML/Attributes/PrincipalTag:";
|
||||
/** What a session tag attribute naming no key is refused with, this package's own wording. */
|
||||
static final String TAG_KEY_MISSING =
|
||||
"A PrincipalTag attribute must name the tag key after the colon.";
|
||||
// The pattern AWS names in its error for a RoleSessionName attribute outside it.
|
||||
static final String ROLE_SESSION_NAME_INVALID = "RoleSessionName in AuthnResponse must match [a-zA-Z_0-9+=,.@-]{2,64}";
|
||||
private static final Pattern ROLE_SESSION_NAME_PATTERN = Pattern.compile("[a-zA-Z_0-9+=,.@-]{2,64}");
|
||||
@@ -44,9 +51,13 @@ final class SAMLAssertionVerifier {
|
||||
|
||||
private SAMLAssertionVerifier() {}
|
||||
|
||||
/** {@code roleSessionName} is null when the assertion carries no RoleSessionName attribute. */
|
||||
/**
|
||||
* {@code roleSessionName} is null when the assertion carries no RoleSessionName attribute, and
|
||||
* {@code principalTags} is empty when it carries no session tags.
|
||||
*/
|
||||
record Verified(String issuer, String subject, String subjectType, String nameQualifier,
|
||||
Instant expiration, List<RolePair> roles, String roleSessionName) {}
|
||||
Instant expiration, List<RolePair> roles, String roleSessionName,
|
||||
Map<String, String> principalTags) {}
|
||||
record RolePair(String roleArn, String principalArn) {}
|
||||
|
||||
static Verified verify(String encoded, SAMLProvider provider, Instant now) throws InvalidAssertionException {
|
||||
@@ -178,7 +189,8 @@ final class SAMLAssertionVerifier {
|
||||
String roleSessionName = roleSessionName(attributes);
|
||||
String nameQualifier = Base64.getEncoder().encodeToString(
|
||||
Digests.sha1((issuer + provider.getArn()).getBytes(StandardCharsets.UTF_8)));
|
||||
return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles, roleSessionName);
|
||||
return new Verified(issuer, name, subjectType, nameQualifier, notOnOrAfter, roles,
|
||||
roleSessionName, principalTags(attributes));
|
||||
} catch (InvalidAssertionException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
@@ -206,6 +218,49 @@ final class SAMLAssertionVerifier {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The session tags the assertion passes: "to pass SAML attributes as session tags, include the
|
||||
* Attribute element with the Name attribute set to
|
||||
* https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}. Use the AttributeValue element
|
||||
* to specify the value of the tag. Include a separate Attribute element for each session tag."
|
||||
*
|
||||
* <p>An attribute carries exactly one value, since "you must pass a single value for each
|
||||
* session tag" and STS "does not support multi-valued session tags", and an attribute carrying
|
||||
* none or several is refused rather than read as the first of them or dropped: a tag a policy
|
||||
* would have been evaluated with cannot go missing quietly. An attribute whose name ends at
|
||||
* the colon names no key and is refused the same way. The value is taken as the assertion
|
||||
* signed it, spaces included, tag values being allowed them, where trimming it would hand a
|
||||
* policy a value the provider never asserted. Two attributes naming one key leave the later,
|
||||
* which is how a tag key already on an identity resolves, a second tag replacing the first
|
||||
* rather than being added beside it.
|
||||
*/
|
||||
private static Map<String, String> principalTags(NodeList attributes) throws InvalidAssertionException {
|
||||
Map<String, String> tags = new LinkedHashMap<>();
|
||||
for (int i = 0; i < attributes.getLength(); i++) {
|
||||
Element attribute = (Element) attributes.item(i);
|
||||
String name = attribute.getAttribute("Name");
|
||||
if (name == null || !name.startsWith(PRINCIPAL_TAG)) {
|
||||
continue;
|
||||
}
|
||||
String key = name.substring(PRINCIPAL_TAG.length());
|
||||
if (key.isEmpty()) {
|
||||
throw new InvalidAssertionException("principal tag key", TAG_KEY_MISSING);
|
||||
}
|
||||
NodeList values = attribute.getElementsByTagNameNS(SAML, "AttributeValue");
|
||||
if (values.getLength() != 1) {
|
||||
throw new InvalidAssertionException("principal tag values", singleValueRequired(key));
|
||||
}
|
||||
tags.put(key, values.item(0).getTextContent());
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
/** What an attribute carrying no single value for its tag is refused with, Floci's wording. */
|
||||
static String singleValueRequired(String key) {
|
||||
return "Session tag " + key + " must carry exactly one AttributeValue:"
|
||||
+ " a session tag takes a single value.";
|
||||
}
|
||||
|
||||
private static X509Certificate certificate(String encoded) throws Exception {
|
||||
byte[] der = Base64.getDecoder().decode(encoded.replaceAll("\\s+", ""));
|
||||
return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(der));
|
||||
|
||||
@@ -14,6 +14,7 @@ import java.util.stream.StreamSupport;
|
||||
@ApplicationScoped
|
||||
public class SAMLTrustPolicyEvaluator {
|
||||
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
|
||||
private static final String SAML_ACTION = "sts:AssumeRoleWithSAML";
|
||||
private final ObjectMapper mapper;
|
||||
@Inject
|
||||
public SAMLTrustPolicyEvaluator(ObjectMapper mapper) {
|
||||
@@ -26,6 +27,21 @@ public class SAMLTrustPolicyEvaluator {
|
||||
*/
|
||||
public boolean allows(String document, String providerArn, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
return allows(SAML_ACTION, document, providerArn, claims, roleSessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the trust policy lets this assertion's holder tag the session it is assuming, read on
|
||||
* the same document with the same principal and the same conditions as the assume itself.
|
||||
*/
|
||||
public boolean allowsTagging(String document, String providerArn, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
return allows(AssumeRolePolicyEvaluator.TAG_SESSION_ACTION, document, providerArn, claims,
|
||||
roleSessionName);
|
||||
}
|
||||
|
||||
private boolean allows(String action, String document, String providerArn,
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
try {
|
||||
JsonNode statements = mapper.readTree(document).path("Statement");
|
||||
if (!TrustPolicyStatements.wellFormed(statements)) {
|
||||
@@ -34,7 +50,7 @@ public class SAMLTrustPolicyEvaluator {
|
||||
if (statements.isArray()) {
|
||||
boolean allowed = false;
|
||||
for (JsonNode statement : statements) {
|
||||
int result = evaluate(statement, providerArn, claims, roleSessionName);
|
||||
int result = evaluate(action, statement, providerArn, claims, roleSessionName);
|
||||
if (result < 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -44,15 +60,16 @@ public class SAMLTrustPolicyEvaluator {
|
||||
}
|
||||
return allowed;
|
||||
}
|
||||
return statements.isObject() && evaluate(statements, providerArn, claims, roleSessionName) > 0;
|
||||
return statements.isObject()
|
||||
&& evaluate(action, statements, providerArn, claims, roleSessionName) > 0;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int evaluate(JsonNode statement, String providerArn, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
if (!actionApplies(statement) || !principal(statement.path("Principal"), providerArn)
|
||||
private int evaluate(String action, JsonNode statement, String providerArn,
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
if (!actionApplies(statement, action) || !principal(statement.path("Principal"), providerArn)
|
||||
|| !conditionsSatisfied(statement.get("Condition"), claims, roleSessionName)) {
|
||||
return 0;
|
||||
}
|
||||
@@ -120,31 +137,31 @@ public class SAMLTrustPolicyEvaluator {
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean actionApplies(JsonNode statement) {
|
||||
JsonNode action = statement.get("Action");
|
||||
if (action != null) {
|
||||
return action(action);
|
||||
private boolean actionApplies(JsonNode statement, String action) {
|
||||
JsonNode element = statement.get("Action");
|
||||
if (element != null) {
|
||||
return action(element, action);
|
||||
}
|
||||
JsonNode notAction = statement.get("NotAction");
|
||||
return notAction != null && !action(notAction);
|
||||
return notAction != null && !action(notAction, action);
|
||||
}
|
||||
|
||||
private boolean action(JsonNode node) {
|
||||
private boolean action(JsonNode node, String action) {
|
||||
if (node.isTextual()) {
|
||||
return matches(node.asText());
|
||||
return matches(node.asText(), action);
|
||||
}
|
||||
if (node.isArray()) {
|
||||
for (JsonNode value : node) {
|
||||
if (value.isTextual() && matches(value.asText())) {
|
||||
if (value.isTextual() && matches(value.asText(), action)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
private boolean matches(String action) {
|
||||
String regex = action.replace(".", "\\.").replace("*", ".*").replace("?", ".");
|
||||
return "sts:AssumeRoleWithSAML".matches("(?i)^" + regex + "$");
|
||||
private boolean matches(String pattern, String action) {
|
||||
String regex = pattern.replace(".", "\\.").replace("*", ".*").replace("?", ".");
|
||||
return action.matches("(?i)^" + regex + "$");
|
||||
}
|
||||
private boolean principal(JsonNode node, String providerArn) {
|
||||
JsonNode federated = node.isObject() ? node.get("Federated") : null;
|
||||
|
||||
@@ -228,6 +228,7 @@ public class StsQueryHandler {
|
||||
iamService.registerSession(
|
||||
accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, sessionPolicy, callerAccountId,
|
||||
sessionName, assumedRoleId);
|
||||
iamService.recordSessionTags(accessKeyId, requestTags(params));
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
@@ -319,8 +320,18 @@ public class StsQueryHandler {
|
||||
* {@code AssumeRoleWithSAML} inside the assertion rather than as a member of the request, and
|
||||
* the two operations that mint a session out of the caller's own credentials declare no state
|
||||
* at all, so a parameter STS would ignore cannot be made to cost a caller anything.
|
||||
*
|
||||
* <p>{@code carriedTags} is for the tags an operation takes from its message instead: they are
|
||||
* state the session carries like any other, "session policies and session tags add to the
|
||||
* session token size", and they are known only once the assertion or the token they arrived in
|
||||
* has been verified, which is where those two operations read this.
|
||||
*/
|
||||
private AssembledSession assembledSession(String action, MultivaluedMap<String, String> params) {
|
||||
return assembledSession(action, params, Map.of());
|
||||
}
|
||||
|
||||
private AssembledSession assembledSession(String action, MultivaluedMap<String, String> params,
|
||||
Map<String, String> carriedTags) {
|
||||
StringBuilder state = new StringBuilder();
|
||||
if (StsRequestShapes.hasMember(action, "Policy")) {
|
||||
String document = params.getFirst("Policy");
|
||||
@@ -337,8 +348,9 @@ public class StsQueryHandler {
|
||||
}
|
||||
}
|
||||
if (StsRequestShapes.hasMember(action, "Tags")) {
|
||||
tagClaims(params).forEach((key, value) -> state.append(key).append(value));
|
||||
requestTags(params).forEach((key, value) -> state.append(key).append(value));
|
||||
}
|
||||
carriedTags.forEach((key, value) -> state.append(key).append(value));
|
||||
return new AssembledSession(sessionTokenLength(params)
|
||||
+ state.toString().getBytes(StandardCharsets.UTF_8).length);
|
||||
}
|
||||
@@ -366,7 +378,11 @@ public class StsQueryHandler {
|
||||
* the refusal read the same request as over the limit.
|
||||
*/
|
||||
private String sessionSizeXml(String action, MultivaluedMap<String, String> params) {
|
||||
AssembledSession session = assembledSession(action, params);
|
||||
return sessionSizeXml(action, assembledSession(action, params));
|
||||
}
|
||||
|
||||
/** The same members, for an operation that measured its session itself. */
|
||||
private String sessionSizeXml(String action, AssembledSession session) {
|
||||
XmlBuilder members = new XmlBuilder();
|
||||
if (PACKED_SESSION_OPERATIONS.contains(action)) {
|
||||
members.elem("PackedPolicySize", session.utilization());
|
||||
@@ -502,13 +518,22 @@ public class StsQueryHandler {
|
||||
if (externalId != null) {
|
||||
trustContext.put("sts:ExternalId", List.of(externalId));
|
||||
}
|
||||
if (trustPolicyEvaluator.allows(role.getAssumeRolePolicyDocument(), caller, callerAccount,
|
||||
if (!trustPolicyEvaluator.allows(role.getAssumeRolePolicyDocument(), caller, callerAccount,
|
||||
trustContext)) {
|
||||
return null;
|
||||
return AwsQueryResponse.error("AccessDenied",
|
||||
"User: " + callerArn + " is not authorized to perform: sts:AssumeRole on resource: " + roleArn,
|
||||
AwsNamespaces.STS, 403);
|
||||
}
|
||||
return AwsQueryResponse.error("AccessDenied",
|
||||
"User: " + callerArn + " is not authorized to perform: sts:AssumeRole on resource: " + roleArn,
|
||||
AwsNamespaces.STS, 403);
|
||||
// A request that carries session tags needs the trust policy's permission to carry them:
|
||||
// "for roles without this permission in the trust policy, the AssumeRole operation fails".
|
||||
if (!requestTags(params).isEmpty()
|
||||
&& !trustPolicyEvaluator.allowsTagging(role.getAssumeRolePolicyDocument(), caller,
|
||||
callerAccount, trustContext)) {
|
||||
return AwsQueryResponse.error("AccessDenied", "User: " + callerArn
|
||||
+ " is not authorized to perform: " + AssumeRolePolicyEvaluator.TAG_SESSION_ACTION
|
||||
+ " on resource: " + roleArn, AwsNamespaces.STS, 403);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String canonicalRoleArn(IamRole role, String accountId, String roleName) {
|
||||
@@ -654,6 +679,15 @@ public class StsQueryHandler {
|
||||
return roleDurationError;
|
||||
}
|
||||
|
||||
// The token's tags are state its session has to carry, measured here because the
|
||||
// pre-dispatch check reads the members a request declares and this operation declares no
|
||||
// Tags member: what the token passed is known once it has been verified.
|
||||
Map<String, String> carriedTags = verified != null ? verified.principalTags() : Map.of();
|
||||
AssembledSession session = assembledSession("AssumeRoleWithWebIdentity", params, carriedTags);
|
||||
if (session.tooLarge()) {
|
||||
return session.refusal();
|
||||
}
|
||||
|
||||
String accessKeyId = "ASIA" + randomId(16);
|
||||
String secretKey = randomSecret(40);
|
||||
String sessionToken = sessionToken(params);
|
||||
@@ -672,6 +706,9 @@ public class StsQueryHandler {
|
||||
iamService.registerSession(
|
||||
accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, sessionPolicy, callerAccountId,
|
||||
sessionName, assumedRoleId);
|
||||
// The token's own claims, this operation declaring no Tags member: a session tag reaches it
|
||||
// "in the JSON Web Token (JWT) when you submit the AssumeRoleWithWebIdentity request".
|
||||
iamService.recordSessionTags(accessKeyId, carriedTags);
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
@@ -679,7 +716,7 @@ public class StsQueryHandler {
|
||||
.elem("Arn", assumedRoleArn)
|
||||
.elem("AssumedRoleId", assumedRoleId)
|
||||
.end("AssumedRoleUser")
|
||||
.raw(sessionSizeXml("AssumeRoleWithWebIdentity", params))
|
||||
.raw(sessionSizeXml("AssumeRoleWithWebIdentity", session))
|
||||
.elem("Provider", provider)
|
||||
.elem("Audience", audience)
|
||||
.elem("SubjectFromWebIdentityToken", subject)
|
||||
@@ -707,7 +744,8 @@ public class StsQueryHandler {
|
||||
}
|
||||
|
||||
/** The claims of a token Floci issued and verified, used to fill the response accurately. */
|
||||
private record VerifiedWebIdentity(String issuer, String subject, String audience) {}
|
||||
private record VerifiedWebIdentity(String issuer, String subject, String audience,
|
||||
Map<String, String> principalTags) {}
|
||||
|
||||
private record WebIdentityOutcome(VerifiedWebIdentity verified, IamRole role, Response denial) {
|
||||
|
||||
@@ -777,12 +815,21 @@ public class StsQueryHandler {
|
||||
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName)) {
|
||||
LOG.debugv("Trust policy on role {0} denies web identity subject {1}",
|
||||
roleArn, claims.subject());
|
||||
return WebIdentityOutcome.deny(accessDenied(roleArn));
|
||||
return WebIdentityOutcome.deny(accessDenied("sts:AssumeRoleWithWebIdentity", roleArn));
|
||||
}
|
||||
if (!claims.principalTags().isEmpty()
|
||||
&& !webIdentityTrustEvaluator.allowsTagging(role.get().getAssumeRolePolicyDocument(),
|
||||
oidcProviderArn, issuerKeyPrefix, conditionClaims, sessionName)) {
|
||||
LOG.debugv("Trust policy on role {0} does not permit tagging the session of subject {1}",
|
||||
roleArn, claims.subject());
|
||||
return WebIdentityOutcome.deny(
|
||||
accessDenied(AssumeRolePolicyEvaluator.TAG_SESSION_ACTION, roleArn));
|
||||
}
|
||||
|
||||
// verify() already required the audience list to contain STS_AUDIENCE.
|
||||
return WebIdentityOutcome.allow(
|
||||
new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE), role.get());
|
||||
new VerifiedWebIdentity(claims.issuer(), claims.subject(), STS_AUDIENCE,
|
||||
claims.principalTags()), role.get());
|
||||
}
|
||||
|
||||
private static String assumedRoleId(IamRole role, String sessionName) {
|
||||
@@ -802,8 +849,13 @@ public class StsQueryHandler {
|
||||
}
|
||||
|
||||
private Response accessDenied(String roleArn) {
|
||||
return accessDenied("sts:AssumeRoleWithWebIdentity", roleArn);
|
||||
}
|
||||
|
||||
/** The refusal this operation answers, for the assume itself or for the tagging it also needs. */
|
||||
private Response accessDenied(String action, String roleArn) {
|
||||
return AwsQueryResponse.error("AccessDenied",
|
||||
"Not authorized to perform sts:AssumeRoleWithWebIdentity on resource: " + roleArn,
|
||||
"Not authorized to perform " + action + " on resource: " + roleArn,
|
||||
AwsNamespaces.STS, 403);
|
||||
}
|
||||
|
||||
@@ -849,13 +901,21 @@ public class StsQueryHandler {
|
||||
String roleName = roleArn.contains("/") ? roleArn.substring(roleArn.lastIndexOf('/') + 1) : "UnknownRole";
|
||||
IamRole role = iamService.findRole(accountId, roleName).orElseThrow(() ->
|
||||
new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403));
|
||||
if (!samlTrustEvaluator.allows(role.getAssumeRolePolicyDocument(), principalArn, Map.of(
|
||||
Map<String, List<String>> assertionClaims = Map.of(
|
||||
"aud", List.of(STS_AUDIENCE),
|
||||
"iss", List.of(verified.issuer()),
|
||||
"sub", List.of(verified.subject()),
|
||||
"namequalifier", List.of(verified.nameQualifier())), verified.roleSessionName())) {
|
||||
"namequalifier", List.of(verified.nameQualifier()));
|
||||
if (!samlTrustEvaluator.allows(role.getAssumeRolePolicyDocument(), principalArn, assertionClaims,
|
||||
verified.roleSessionName())) {
|
||||
throw new AwsException("AccessDenied", "Not authorized to perform sts:AssumeRoleWithSAML on resource: " + roleArn, 403);
|
||||
}
|
||||
if (!verified.principalTags().isEmpty()
|
||||
&& !samlTrustEvaluator.allowsTagging(role.getAssumeRolePolicyDocument(), principalArn,
|
||||
assertionClaims, verified.roleSessionName())) {
|
||||
throw new AwsException("AccessDenied", "Not authorized to perform "
|
||||
+ AssumeRolePolicyEvaluator.TAG_SESSION_ACTION + " on resource: " + roleArn, 403);
|
||||
}
|
||||
|
||||
Response roleDurationError = validateMaxSessionDuration(durationSeconds, role);
|
||||
if (roleDurationError != null) {
|
||||
@@ -871,6 +931,14 @@ public class StsQueryHandler {
|
||||
sessionName = sessionName.substring(0, 64);
|
||||
}
|
||||
}
|
||||
// The assertion's tags are state the token has to carry, and they are known only here:
|
||||
// the pre-dispatch check reads the members a request declares, and this operation declares
|
||||
// no Tags member, so what the assertion passed is measured once it has been verified.
|
||||
AssembledSession session = assembledSession("AssumeRoleWithSAML", params, verified.principalTags());
|
||||
if (session.tooLarge()) {
|
||||
return session.refusal();
|
||||
}
|
||||
|
||||
Instant requestedExpiration = clock.instant().plusSeconds(durationSeconds);
|
||||
Instant expiration = verified.expiration().isBefore(requestedExpiration) ? verified.expiration() : requestedExpiration;
|
||||
String accessKeyId = "ASIA" + randomId(16);
|
||||
@@ -882,10 +950,12 @@ public class StsQueryHandler {
|
||||
|
||||
iamService.registerSession(accessKeyId, secretKey, sessionToken, sessionRoleArn, expiration, null,
|
||||
callerAccountId, sessionName, assumedRoleId);
|
||||
// The assertion's own attributes, this operation declaring no Tags member either.
|
||||
iamService.recordSessionTags(accessKeyId, verified.principalTags());
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
.start("AssumedRoleUser").elem("Arn", assumedRoleArn).elem("AssumedRoleId", assumedRoleId).end("AssumedRoleUser")
|
||||
.raw(sessionSizeXml("AssumeRoleWithSAML", params)).elem("Issuer", verified.issuer())
|
||||
.raw(sessionSizeXml("AssumeRoleWithSAML", session)).elem("Issuer", verified.issuer())
|
||||
.elem("Audience", "urn:amazon:webservices")
|
||||
.elem("NameQualifier", verified.nameQualifier()).elem("SubjectType", verified.subjectType()).elem("Subject", verified.subject()).build();
|
||||
return Response.ok(AwsQueryResponse.envelope("AssumeRoleWithSAML", AwsNamespaces.STS, result)).build();
|
||||
@@ -935,6 +1005,7 @@ public class StsQueryHandler {
|
||||
// minted it, so the caller is recorded with it.
|
||||
iamService.registerIssuedSession(accessKeyId, secretKey, sessionToken, federatedUserArn, expiration,
|
||||
sessionPolicy, accountId, callerAccessKeyId());
|
||||
iamService.recordSessionTags(accessKeyId, requestTags(params));
|
||||
|
||||
String result = new XmlBuilder()
|
||||
.raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration))
|
||||
@@ -1316,7 +1387,7 @@ public class StsQueryHandler {
|
||||
WebIdentityTokenIssuer.Algorithm.valueOf(params.getFirst("SigningAlgorithm")),
|
||||
federation.get().getIssuerIdentifier(), subject, audiences(params),
|
||||
new WebIdentityTokenIssuer.CustomClaims(regionResolver.getAccountId(),
|
||||
regionResolver.getRegion(), tagClaims(params)),
|
||||
regionResolver.getRegion(), requestTags(params)),
|
||||
issuedAt, expiration);
|
||||
LOG.debugv("Issued a web identity token for {0} expiring at {1}", subject, expiration);
|
||||
String result = new XmlBuilder()
|
||||
@@ -1338,11 +1409,13 @@ public class StsQueryHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags the request turns into claims, the last value winning for a key sent twice, which is
|
||||
* how a Query map's duplicate key resolves elsewhere in this package. {@code Tag} declares both
|
||||
* its fields required, so a member reaching here carries them.
|
||||
* The tags the request's own {@code Tags} member carries, the last value winning for a key
|
||||
* sent twice, which is how a Query map's duplicate key resolves elsewhere in this package.
|
||||
* {@code Tag} declares both its fields required, so a member reaching here carries them. They
|
||||
* are a session's tags where the operation mints one, and a minted token's claims where it
|
||||
* mints a token.
|
||||
*/
|
||||
private static Map<String, String> tagClaims(MultivaluedMap<String, String> params) {
|
||||
private static Map<String, String> requestTags(MultivaluedMap<String, String> params) {
|
||||
Map<String, String> claims = new LinkedHashMap<>();
|
||||
for (AwsQueryLists.IndexedMember tag : AwsQueryLists.members(params, "Tags", null)) {
|
||||
String key = params.getFirst(tag.prefix() + ".Key");
|
||||
|
||||
@@ -32,6 +32,8 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
|
||||
private static final Logger LOG = Logger.getLogger(WebIdentityTrustPolicyEvaluator.class);
|
||||
private static final String WEB_IDENTITY_ACTION = "sts:assumerolewithwebidentity";
|
||||
/** What a trust policy also has to allow for the token's session tags to be taken. */
|
||||
private static final String TAG_SESSION_ACTION = AssumeRolePolicyEvaluator.TAG_SESSION_ACTION;
|
||||
private static final String ROLE_SESSION_NAME_KEY = "sts:RoleSessionName";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
@@ -53,6 +55,23 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
*/
|
||||
public boolean allows(String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
return allows(WEB_IDENTITY_ACTION, trustPolicyDocument, oidcProviderArn, issuerKeyPrefix, claims,
|
||||
roleSessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the trust policy lets this token's holder tag the session it is assuming, read on the
|
||||
* same document with the same principal and the same conditions as the assume itself.
|
||||
*/
|
||||
public boolean allowsTagging(String trustPolicyDocument, String oidcProviderArn, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
return allows(TAG_SESSION_ACTION, trustPolicyDocument, oidcProviderArn, issuerKeyPrefix, claims,
|
||||
roleSessionName);
|
||||
}
|
||||
|
||||
private boolean allows(String action, String trustPolicyDocument, String oidcProviderArn,
|
||||
String issuerKeyPrefix, Map<String, List<String>> claims,
|
||||
String roleSessionName) {
|
||||
if (trustPolicyDocument == null || trustPolicyDocument.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
@@ -70,7 +89,7 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
boolean allow = false;
|
||||
if (statements.isArray()) {
|
||||
for (JsonNode stmt : statements) {
|
||||
switch (evaluate(stmt, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName)) {
|
||||
switch (evaluate(action, stmt, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName)) {
|
||||
case DENY -> { return false; }
|
||||
case ALLOW -> allow = true;
|
||||
case NO_MATCH -> { }
|
||||
@@ -79,16 +98,17 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
return allow;
|
||||
}
|
||||
if (statements.isObject()) {
|
||||
return evaluate(statements, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName) == Match.ALLOW;
|
||||
return evaluate(action, statements, oidcProviderArn, issuerKeyPrefix, claims, roleSessionName)
|
||||
== Match.ALLOW;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private enum Match { ALLOW, DENY, NO_MATCH }
|
||||
|
||||
private Match evaluate(JsonNode stmt, String oidcProviderArn, String issuerKeyPrefix,
|
||||
private Match evaluate(String action, JsonNode stmt, String oidcProviderArn, String issuerKeyPrefix,
|
||||
Map<String, List<String>> claims, String roleSessionName) {
|
||||
if (!actionApplies(stmt)) {
|
||||
if (!actionApplies(stmt, action)) {
|
||||
return Match.NO_MATCH;
|
||||
}
|
||||
if (!matchesFederatedPrincipal(stmt.get("Principal"), oidcProviderArn)) {
|
||||
@@ -101,29 +121,29 @@ public class WebIdentityTrustPolicyEvaluator {
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the statement's action element covers {@code sts:AssumeRoleWithWebIdentity}. Action
|
||||
* names are case-insensitive in AWS policy documents, and wildcards are honoured.
|
||||
* True when the statement's action element covers {@code action}, the assume itself or the
|
||||
* {@code sts:TagSession} a tagged assume also needs. Action names are case-insensitive in AWS
|
||||
* policy documents, and wildcards are honoured.
|
||||
*/
|
||||
private boolean actionApplies(JsonNode stmt) {
|
||||
JsonNode action = stmt.get("Action");
|
||||
if (action != null) {
|
||||
return matchesAction(action);
|
||||
private boolean actionApplies(JsonNode stmt, String action) {
|
||||
JsonNode element = stmt.get("Action");
|
||||
if (element != null) {
|
||||
return matchesAction(element, action);
|
||||
}
|
||||
JsonNode notAction = stmt.get("NotAction");
|
||||
if (notAction != null) {
|
||||
return !matchesAction(notAction);
|
||||
return !matchesAction(notAction, action);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean matchesAction(JsonNode actionNode) {
|
||||
private boolean matchesAction(JsonNode actionNode, String action) {
|
||||
if (actionNode.isTextual()) {
|
||||
return IamPolicyEvaluator.globMatches(actionNode.asText(), WEB_IDENTITY_ACTION);
|
||||
return IamPolicyEvaluator.globMatches(actionNode.asText(), action);
|
||||
}
|
||||
if (actionNode.isArray()) {
|
||||
for (JsonNode entry : actionNode) {
|
||||
if (entry.isTextual()
|
||||
&& IamPolicyEvaluator.globMatches(entry.asText(), WEB_IDENTITY_ACTION)) {
|
||||
if (entry.isTextual() && IamPolicyEvaluator.globMatches(entry.asText(), action)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
@@ -78,6 +80,15 @@ public class SessionCredential {
|
||||
* counting from the authentication itself.
|
||||
*/
|
||||
private Instant mfaAuthenticatedAt;
|
||||
/**
|
||||
* The session tags this session was minted with, which its requests publish as
|
||||
* {@code aws:PrincipalTag/<key>} beside the tags of the user or role it acts as. They are the
|
||||
* session's own: "session tags are valid only for the current session", and a session carries
|
||||
* them whether they came as a request member, as a SAML assertion's attributes or as a web
|
||||
* identity token's claims. Empty for a session minted with none and for one stored before
|
||||
* Floci recorded them.
|
||||
*/
|
||||
private Map<String, String> sessionTags = new LinkedHashMap<>();
|
||||
|
||||
public SessionCredential() {}
|
||||
|
||||
@@ -201,4 +212,12 @@ public class SessionCredential {
|
||||
public void setMfaAuthenticatedAt(Instant mfaAuthenticatedAt) {
|
||||
this.mfaAuthenticatedAt = mfaAuthenticatedAt;
|
||||
}
|
||||
|
||||
public Map<String, String> getSessionTags() {
|
||||
return sessionTags;
|
||||
}
|
||||
|
||||
public void setSessionTags(Map<String, String> sessionTags) {
|
||||
this.sessionTags = sessionTags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(sessionTags);
|
||||
}
|
||||
}
|
||||
@@ -190,6 +190,95 @@ class WebIdentityTokenVerifierTest {
|
||||
assertTrue(thrown.getMessage().contains("not yet valid"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The session tags a token passes in the nested format, "a structure within the
|
||||
* https://aws.amazon.com/tags namespace", where the tags sit "under the principal_tags key".
|
||||
* The published example writes each value as an array holding one string while the prose calls
|
||||
* each tag "a single string value", so both forms are read. The transitive keys beside them are
|
||||
* not read.
|
||||
*/
|
||||
@Test
|
||||
void readsTheSessionTagsOfTheNestedClaimFormat() throws Exception {
|
||||
KeyPair keyPair = newKeyPair();
|
||||
String token = signRs256(keyPair.getPrivate(), claims(
|
||||
"\"https://aws.amazon.com/tags\":{"
|
||||
+ "\"principal_tags\":{\"Project\":[\"Automation\"],\"CostCenter\":\"987654\"},"
|
||||
+ "\"transitive_tag_keys\":[\"Project\"]}"));
|
||||
|
||||
WebIdentityToken verified = verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE);
|
||||
|
||||
assertEquals(Map.of("Project", "Automation", "CostCenter", "987654"), verified.principalTags());
|
||||
}
|
||||
|
||||
/**
|
||||
* A tag carrying anything but one string is a multi-valued session tag, which "AWS STS does not
|
||||
* support", and the token is refused rather than verified with that tag quietly dropped: a tag
|
||||
* a policy would have been evaluated with cannot go missing. A tag claim naming no key at all
|
||||
* is refused the same way.
|
||||
*/
|
||||
@Test
|
||||
void refusesATokenWhoseSessionTagCarriesNoSingleValue() throws Exception {
|
||||
KeyPair keyPair = newKeyPair();
|
||||
String multiValued = signRs256(keyPair.getPrivate(), claims(
|
||||
"\"https://aws.amazon.com/tags\":{\"principal_tags\":{\"Teams\":[\"one\",\"two\"]}}"));
|
||||
|
||||
WebIdentityTokenVerifier.InvalidTokenException thrown = assertThrows(
|
||||
WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(multiValued, (RSAPublicKey) keyPair.getPublic(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE));
|
||||
assertTrue(thrown.getMessage().contains("Teams does not carry a single value"),
|
||||
thrown.getMessage());
|
||||
|
||||
String keyless = signRs256(keyPair.getPrivate(),
|
||||
claims("\"https://aws.amazon.com/tags/principal_tags/\":\"Automation\""));
|
||||
|
||||
assertTrue(assertThrows(WebIdentityTokenVerifier.InvalidTokenException.class,
|
||||
() -> verifier.verify(keyless, (RSAPublicKey) keyPair.getPublic(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE))
|
||||
.getMessage().contains("session tag with no key"));
|
||||
}
|
||||
|
||||
/**
|
||||
* And in the flattened format, "compatible with identity providers that don't support nested
|
||||
* objects in JWT claims", where each tag is "a separate claim with the prefix
|
||||
* https://aws.amazon.com/tags/principal_tags/" and the transitive keys are one claim of their
|
||||
* own, which is not a tag.
|
||||
*/
|
||||
@Test
|
||||
void readsTheSessionTagsOfTheFlattenedClaimFormat() throws Exception {
|
||||
KeyPair keyPair = newKeyPair();
|
||||
String token = signRs256(keyPair.getPrivate(), claims(
|
||||
"\"https://aws.amazon.com/tags/principal_tags/Project\":\"Automation\","
|
||||
+ "\"https://aws.amazon.com/tags/principal_tags/Department\":\"Engineering\","
|
||||
+ "\"https://aws.amazon.com/tags/transitive_tag_keys\":[\"Project\"]"));
|
||||
|
||||
WebIdentityToken verified = verifier.verify(token, (RSAPublicKey) keyPair.getPublic(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE);
|
||||
|
||||
assertEquals(Map.of("Project", "Automation", "Department", "Engineering"),
|
||||
verified.principalTags());
|
||||
}
|
||||
|
||||
/** A token passing no tags carries none, which is every token this emulator mints itself. */
|
||||
@Test
|
||||
void aTokenWithoutTagClaimsCarriesNoSessionTags() throws Exception {
|
||||
String token = mint("my-namespace", "my-service-account", null, null);
|
||||
|
||||
WebIdentityToken verified = verifier.verify(token, publicKey(), ISSUER,
|
||||
EksOidcService.STS_AUDIENCE);
|
||||
|
||||
assertTrue(verified.principalTags().isEmpty());
|
||||
}
|
||||
|
||||
/** A valid claim set carrying {@code extra} beside the three claims every token needs. */
|
||||
private static String claims(String extra) {
|
||||
long now = System.currentTimeMillis() / 1000;
|
||||
return "{\"iss\":\"" + ISSUER + "\",\"aud\":[\"" + EksOidcService.STS_AUDIENCE + "\"],"
|
||||
+ "\"sub\":\"system:serviceaccount:my-namespace:my-service-account\","
|
||||
+ "\"exp\":" + (now + 3600) + "," + extra + "}";
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsKeyFromAnotherCluster() {
|
||||
String otherIssuer = "https://oidc.eks.us-east-1.amazonaws.com/id/OTHERCLUSTER0000000000000000";
|
||||
|
||||
+154
-14
@@ -58,7 +58,9 @@ import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
@@ -541,6 +543,104 @@ class AssumeRoleWithSamlValidationIntegrationTest {
|
||||
.body(result + "PackedPolicySize", equalTo("25"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The session tags the assertion passes are the session's principal tags: "to pass SAML
|
||||
* attributes as session tags, include the Attribute element with the Name attribute set to
|
||||
* https://aws.amazon.com/SAML/Attributes/PrincipalTag:{TagKey}", which is the only way this
|
||||
* operation takes them, its request declaring no Tags member at all.
|
||||
*/
|
||||
@Test
|
||||
void theAssertionsSessionTagsBecomeTheSessionsPrincipalTags() {
|
||||
String role = createRoleAllowingTags();
|
||||
Map<String, List<String>> tags = Map.of("Project", List.of("Automation"),
|
||||
"CostCenter", List.of("12345"));
|
||||
|
||||
String accessKeyId = assumeRequest(role, assertionCarryingTags(role, tags), PROVIDER)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().path("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId");
|
||||
|
||||
assertEquals(Map.of("Project", "Automation", "CostCenter", "12345"),
|
||||
iamService.resolveCallerArns(accessKeyId).orElseThrow().principalTags());
|
||||
}
|
||||
|
||||
/**
|
||||
* The value is the one the assertion signed, spaces and all: a tag value may carry them, and
|
||||
* trimming it would hand a policy a value the provider never asserted.
|
||||
*/
|
||||
@Test
|
||||
void aSpacedTagValueIsStoredAsTheAssertionSignedIt() {
|
||||
String role = createRoleAllowingTags();
|
||||
|
||||
String accessKeyId = assumeRequest(role, assertionCarryingTags(role, tag("Team", " admin ")), PROVIDER)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.extract().path("AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.Credentials.AccessKeyId");
|
||||
|
||||
assertEquals(Map.of("Team", " admin "),
|
||||
iamService.resolveCallerArns(accessKeyId).orElseThrow().principalTags());
|
||||
}
|
||||
|
||||
/**
|
||||
* A tag attribute carrying several values is a multi-valued session tag, which AWS STS does not
|
||||
* support, and one carrying none names a tag with no value: both are refused rather than read
|
||||
* as the first value or dropped, so a tag a policy would be evaluated with cannot go missing.
|
||||
*/
|
||||
@Test
|
||||
void aTagAttributeWithoutExactlyOneValueIsRefused() {
|
||||
String role = createRoleAllowingTags();
|
||||
|
||||
assume(role, assertionCarryingTags(role, Map.of("Teams", List.of("one", "two"))), PROVIDER)
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidIdentityToken"))
|
||||
.body("ErrorResponse.Error.Message",
|
||||
equalTo(SAMLAssertionVerifier.singleValueRequired("Teams")));
|
||||
assume(role, assertionCarryingTags(role, Map.of("Teams", List.of())), PROVIDER)
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Message",
|
||||
equalTo(SAMLAssertionVerifier.singleValueRequired("Teams")));
|
||||
}
|
||||
|
||||
/** And an attribute whose name ends at the colon names no tag key at all. */
|
||||
@Test
|
||||
void aTagAttributeNamingNoKeyIsRefused() {
|
||||
String role = createRoleAllowingTags();
|
||||
|
||||
assume(role, assertionCarryingTags(role, tag("", "Automation")), PROVIDER)
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("InvalidIdentityToken"))
|
||||
.body("ErrorResponse.Error.Message", equalTo(SAMLAssertionVerifier.TAG_KEY_MISSING));
|
||||
}
|
||||
|
||||
/**
|
||||
* The assertion's tags are state the session token carries, so they count against the one
|
||||
* limit it is held to and a set that will not fit is refused before anything is minted. The
|
||||
* request declares no Tags member, so this is measured once the assertion has been verified.
|
||||
*/
|
||||
@Test
|
||||
void anAssertionCarryingTooManyTagsIsRefused() {
|
||||
String role = createRoleAllowingTags();
|
||||
Map<String, List<String>> tags = new LinkedHashMap<>();
|
||||
for (int i = 1; i <= 20; i++) {
|
||||
tags.put("key-" + i, List.of("v".repeat(250)));
|
||||
}
|
||||
|
||||
assume(role, assertionCarryingTags(role, tags), PROVIDER)
|
||||
.statusCode(400)
|
||||
.body("ErrorResponse.Error.Code", equalTo("PackedPolicyTooLarge"));
|
||||
}
|
||||
|
||||
/** A set that does fit is reported as what it cost, the tags counted with the token. */
|
||||
@Test
|
||||
void theAssertionsTagsCountTowardWhatTheSessionReports() {
|
||||
String role = createRoleAllowingTags();
|
||||
String value = "v".repeat(250);
|
||||
|
||||
String result = "AssumeRoleWithSAMLResponse.AssumeRoleWithSAMLResult.";
|
||||
assumeRequest(role, assertionCarryingTags(role, tag("Project", value)), PROVIDER)
|
||||
.when().post("/").then().statusCode(200)
|
||||
.body(result + "SessionTokenSize",
|
||||
equalTo(Integer.toString(200 + "Project".length() + value.length())));
|
||||
}
|
||||
|
||||
private static void assertSignatureInvalid(Function<XMLSignatureFactory, List<Transform>> transforms) {
|
||||
String role = createRole(true);
|
||||
assume(role, assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false, transforms),
|
||||
@@ -577,22 +677,31 @@ class AssumeRoleWithSamlValidationIntegrationTest {
|
||||
}
|
||||
|
||||
private static String createRole(boolean allow) {
|
||||
String role = "saml-role-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||
String trust = allow
|
||||
? "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Federated\":\"" + PROVIDER + "\"},\"Action\":\"sts:AssumeRoleWithSAML\"}]}"
|
||||
: "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Principal\":{\"Federated\":\"" + PROVIDER + "\"},\"Action\":\"sts:AssumeRoleWithSAML\"}]}";
|
||||
given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateRole").formParam("RoleName", role)
|
||||
.formParam("AssumeRolePolicyDocument", trust)
|
||||
.header("Authorization", auth("iam")).when().post("/").then().statusCode(200);
|
||||
ensureProviderRegistered();
|
||||
return "arn:aws:iam::" + ACCOUNT + ":role/" + role;
|
||||
return createRole("saml-role-", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\""
|
||||
+ (allow ? "Allow" : "Deny") + "\",\"Principal\":{\"Federated\":\"" + PROVIDER
|
||||
+ "\"},\"Action\":\"sts:AssumeRoleWithSAML\"}]}");
|
||||
}
|
||||
|
||||
/**
|
||||
* A role whose trust policy permits tagging the session as well as assuming it, which a tagged
|
||||
* assertion needs: "trust policies for all roles connected to the identity provider passing
|
||||
* tags must have the sts:TagSession permission."
|
||||
*/
|
||||
private static String createRoleAllowingTags() {
|
||||
return createRole("saml-tagged-", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"Federated\":\"" + PROVIDER + "\"},"
|
||||
+ "\"Action\":[\"sts:AssumeRoleWithSAML\",\"sts:TagSession\"]}]}");
|
||||
}
|
||||
|
||||
private static String createRoleWithCondition(String condition) {
|
||||
String role = "saml-session-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||
String trust = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"Federated\":\""
|
||||
+ PROVIDER + "\"},\"Action\":\"sts:AssumeRoleWithSAML\",\"Condition\":" + condition + "}]}";
|
||||
return createRole("saml-session-", "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","
|
||||
+ "\"Principal\":{\"Federated\":\"" + PROVIDER + "\"},"
|
||||
+ "\"Action\":\"sts:AssumeRoleWithSAML\",\"Condition\":" + condition + "}]}");
|
||||
}
|
||||
|
||||
/** A role of this class's own, named for what its trust policy says, with the provider registered. */
|
||||
private static String createRole(String namePrefix, String trust) {
|
||||
String role = namePrefix + UUID.randomUUID().toString().replace("-", "").substring(0, 12);
|
||||
given().contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "CreateRole").formParam("RoleName", role)
|
||||
.formParam("AssumeRolePolicyDocument", trust)
|
||||
@@ -648,13 +757,44 @@ class AssumeRoleWithSamlValidationIntegrationTest {
|
||||
factory -> List.of(enveloped(factory)), roleSessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* A valid signed assertion for {@code role} passing {@code tags} as its session tags, each key
|
||||
* written as its own attribute and each value in its own AttributeValue element, so a case can
|
||||
* pass a tag with no value or with several.
|
||||
*/
|
||||
private static String assertionCarryingTags(String role, Map<String, List<String>> tags) {
|
||||
return assertion(role, PROVIDER, Instant.now().plusSeconds(300), AUDIENCE, ISSUER, true, false,
|
||||
factory -> List.of(enveloped(factory)), null, tags);
|
||||
}
|
||||
|
||||
/** One session tag, the shape every case that passes a well-formed one uses. */
|
||||
private static Map<String, List<String>> tag(String key, String value) {
|
||||
return Map.of(key, List.of(value));
|
||||
}
|
||||
|
||||
private static String assertion(String role, String provider, Instant expiry, String audience,
|
||||
String issuer, boolean sign, boolean unrelatedConfirmation,
|
||||
Function<XMLSignatureFactory, List<Transform>> transforms,
|
||||
String roleSessionName) {
|
||||
return assertion(role, provider, expiry, audience, issuer, sign, unrelatedConfirmation, transforms,
|
||||
roleSessionName, Map.of());
|
||||
}
|
||||
|
||||
private static String assertion(String role, String provider, Instant expiry, String audience,
|
||||
String issuer, boolean sign, boolean unrelatedConfirmation,
|
||||
Function<XMLSignatureFactory, List<Transform>> transforms,
|
||||
String roleSessionName, Map<String, List<String>> principalTags) {
|
||||
String sessionNameAttribute = roleSessionName == null ? ""
|
||||
: "<saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/RoleSessionName\"><saml:AttributeValue>"
|
||||
+ roleSessionName + "</saml:AttributeValue></saml:Attribute>";
|
||||
StringBuilder tagAttributes = new StringBuilder();
|
||||
principalTags.forEach((key, values) -> {
|
||||
tagAttributes.append("<saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/PrincipalTag:")
|
||||
.append(key).append("\">");
|
||||
values.forEach(value -> tagAttributes.append("<saml:AttributeValue>").append(value)
|
||||
.append("</saml:AttributeValue>"));
|
||||
tagAttributes.append("</saml:Attribute>");
|
||||
});
|
||||
String id = "_" + UUID.randomUUID();
|
||||
String extraConfirmation = unrelatedConfirmation
|
||||
? "<saml:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:sender-vouches\"><saml:SubjectConfirmationData Recipient=\"https://unrelated.example.test\" NotOnOrAfter=\"" + Instant.now().minusSeconds(1) + "\"/></saml:SubjectConfirmation>"
|
||||
@@ -664,7 +804,7 @@ class AssumeRoleWithSamlValidationIntegrationTest {
|
||||
+ extraConfirmation + "<saml:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\"><saml:SubjectConfirmationData Recipient=\"https://signin.aws.amazon.com/saml\" NotOnOrAfter=\"" + expiry + "\"/></saml:SubjectConfirmation></saml:Subject>"
|
||||
+ "<saml:Conditions NotBefore=\"" + Instant.now().minusSeconds(30) + "\" NotOnOrAfter=\"" + expiry + "\"><saml:AudienceRestriction><saml:Audience>" + audience + "</saml:Audience></saml:AudienceRestriction></saml:Conditions>"
|
||||
+ "<saml:AttributeStatement><saml:Attribute Name=\"https://aws.amazon.com/SAML/Attributes/Role\"><saml:AttributeValue>" + role + "," + provider + "</saml:AttributeValue></saml:Attribute>" + sessionNameAttribute
|
||||
+ "</saml:AttributeStatement></saml:Assertion>";
|
||||
+ tagAttributes + "</saml:AttributeStatement></saml:Assertion>";
|
||||
try {
|
||||
Document document = XmlParser.parseDocument(xml);
|
||||
if (!sign) {
|
||||
|
||||
@@ -555,7 +555,7 @@ class IamServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void userSessionTokensCarryUserTagsButFederatedAndRootSessionsDoNot() {
|
||||
void userAndFederatedSessionsCarryTheUsersTagsButRootSessionsDoNot() {
|
||||
IamUser user = iamService.createUser("tagged", "/");
|
||||
user.setTags(Map.of("Team", "platform"));
|
||||
String key = iamService.createAccessKey("tagged").getAccessKeyId();
|
||||
@@ -567,13 +567,97 @@ class IamServiceTest {
|
||||
iamService.registerIssuedSession("ASIAROOT", "secret", "token", null, expiration,
|
||||
null, "000000000000", "test");
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.resolveCallerArns("ASIAUSER").orElseThrow().putPrincipalKeys(context);
|
||||
assertEquals(List.of("platform"), context.get("aws:PrincipalTag/Team"));
|
||||
for (String session : List.of("ASIAFEDERATED", "ASIAROOT")) {
|
||||
// The federated user's own half of what the guide gives it: "the session principal tags
|
||||
// include the user tags and the passed session tags".
|
||||
for (String session : List.of("ASIAUSER", "ASIAFEDERATED")) {
|
||||
context.clear();
|
||||
iamService.resolveCallerArns(session).orElseThrow().putPrincipalKeys(context);
|
||||
assertFalse(context.containsKey("aws:PrincipalTag/Team"));
|
||||
assertEquals(List.of("platform"), context.get("aws:PrincipalTag/Team"));
|
||||
}
|
||||
context.clear();
|
||||
iamService.resolveCallerArns("ASIAROOT").orElseThrow().putPrincipalKeys(context);
|
||||
assertFalse(context.containsKey("aws:PrincipalTag/Team"));
|
||||
}
|
||||
|
||||
/**
|
||||
* A session's own tags are principal tags of its requests, over the tags of the identity it
|
||||
* acts as: "when you request a session, you can specify principal tags as the session tags.
|
||||
* The tags apply to requests that you make using the session's credentials."
|
||||
*/
|
||||
@Test
|
||||
void sessionTagsArePublishedOverTheTagsOfTheIdentityTheSessionActsAs() {
|
||||
IamRole role = iamService.createRole("Tagged", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
|
||||
role.setTags(Map.of("Team", "role-team", "Owner", "platform"));
|
||||
iamService.registerSession("ASIASESSIONTAGS", "secret", "token", role.getArn(),
|
||||
Instant.now().plusSeconds(3600), null, "000000000000", "tagged", "AROATAGGED:tagged");
|
||||
iamService.recordSessionTags("ASIASESSIONTAGS", Map.of("Team", "session-team", "Project", "atlas"));
|
||||
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.resolveCallerArns("ASIASESSIONTAGS").orElseThrow().putPrincipalKeys(context);
|
||||
|
||||
assertEquals(List.of("session-team"), context.get("aws:PrincipalTag/Team"));
|
||||
assertEquals(List.of("atlas"), context.get("aws:PrincipalTag/Project"));
|
||||
assertEquals(List.of("platform"), context.get("aws:PrincipalTag/Owner"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a session tag replaces is matched without case, as IAM matches a tag key on a user or
|
||||
* a role: a new session tag overrides an existing one "regardless of character case", and the
|
||||
* spelling published is the session's own.
|
||||
*/
|
||||
@Test
|
||||
void aSessionTagReplacesTheIdentityTagOfThatKeyWhateverItsCase() {
|
||||
IamRole role = iamService.createRole("CaseTagged", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
|
||||
role.setTags(Map.of("department", "finance"));
|
||||
iamService.registerSession("ASIACASETAGS", "secret", "token", role.getArn(),
|
||||
Instant.now().plusSeconds(3600), null, "000000000000", "cased", "AROACASED:cased");
|
||||
iamService.recordSessionTags("ASIACASETAGS", Map.of("Department", "engineering"));
|
||||
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.resolveCallerArns("ASIACASETAGS").orElseThrow().putPrincipalKeys(context);
|
||||
|
||||
assertEquals(List.of("engineering"), context.get("aws:PrincipalTag/Department"));
|
||||
assertFalse(context.containsKey("aws:PrincipalTag/department"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Two session tags whose keys differ only in case are one tag, the later winning, as a tag key
|
||||
* on an identity is: "you cannot have separate Department and department tag keys". Kept as two
|
||||
* they would reach a policy as one key with the other's value dropped.
|
||||
*/
|
||||
@Test
|
||||
void sessionTagsThatDifferOnlyInCaseAreOneTag() {
|
||||
IamRole role = iamService.createRole("OneTag", "/", EMPTY_POLICY_DOCUMENT, null, 3600, null);
|
||||
iamService.registerSession("ASIAONETAG", "secret", "token", role.getArn(),
|
||||
Instant.now().plusSeconds(3600), null, "000000000000", "one", "AROAONE:one");
|
||||
Map<String, String> sent = new LinkedHashMap<>();
|
||||
sent.put("Team", "first");
|
||||
sent.put("team", "second");
|
||||
iamService.recordSessionTags("ASIAONETAG", sent);
|
||||
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.resolveCallerArns("ASIAONETAG").orElseThrow().putPrincipalKeys(context);
|
||||
|
||||
assertEquals(List.of("second"), context.get("aws:PrincipalTag/team"));
|
||||
assertFalse(context.containsKey("aws:PrincipalTag/Team"));
|
||||
}
|
||||
|
||||
/** A federated user's session tags join the tags of the user whose key minted the session. */
|
||||
@Test
|
||||
void federatedSessionTagsJoinTheIssuingUsersTags() {
|
||||
IamUser user = iamService.createUser("federated-tagged", "/");
|
||||
user.setTags(Map.of("Team", "platform"));
|
||||
String key = iamService.createAccessKey("federated-tagged").getAccessKeyId();
|
||||
iamService.registerIssuedSession("ASIAFEDTAGS", "secret", "token",
|
||||
"arn:aws:sts::000000000000:federated-user/federated-tagged",
|
||||
Instant.now().plusSeconds(3600), null, "000000000000", key);
|
||||
iamService.recordSessionTags("ASIAFEDTAGS", Map.of("Project", "atlas"));
|
||||
|
||||
Map<String, List<String>> context = new LinkedHashMap<>();
|
||||
iamService.resolveCallerArns("ASIAFEDTAGS").orElseThrow().putPrincipalKeys(context);
|
||||
|
||||
assertEquals(List.of("platform"), context.get("aws:PrincipalTag/Team"));
|
||||
assertEquals(List.of("atlas"), context.get("aws:PrincipalTag/Project"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+166
-2
@@ -27,12 +27,26 @@ import java.util.UUID;
|
||||
import static io.floci.aws.testing.EnforcementFixtures.auth;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@QuarkusTest
|
||||
@TestProfile(IamEnforcementProfile.class)
|
||||
class PrincipalTagEnforcementIntegrationTest {
|
||||
private static final String ACCOUNT = "111111111111";
|
||||
private static final String OTHER_ACCOUNT = "222222222222";
|
||||
/**
|
||||
* What a caller needs of its own policy to pass session tags, beside the operation itself:
|
||||
* the generated tagging table has {@code sts:AssumeRole} and {@code sts:GetFederationToken}
|
||||
* requiring {@code sts:TagSession} of a request that carries {@code Tags}, which the
|
||||
* enforcement filter reads before the operation runs. The role's trust policy is a separate
|
||||
* permission, and the cases below tell the two refusals apart by their sentences.
|
||||
*/
|
||||
private static final String ALLOW_TAGGING = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:TagSession","Resource":"*"}]}""";
|
||||
private static final String ALLOW_FEDERATION = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Action":["sts:GetFederationToken","sts:TagSession"],"Resource":"*"}]}""";
|
||||
|
||||
private static final String ALLOW_ASSUME = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}""";
|
||||
private static final String TAG_POLICY = """
|
||||
@@ -135,6 +149,125 @@ class PrincipalTagEnforcementIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A session's own tags are principal tags of its requests, over the tags of the role it
|
||||
* assumed: "when you request a session, you can specify principal tags as the session tags.
|
||||
* The tags apply to requests that you make using the session's credentials", and a session tag
|
||||
* overrides the role's tag of the same key. The role here carries the wrong team, so only the
|
||||
* session that passes the right one is allowed, and a session tag of its own can bring the Deny
|
||||
* on as well.
|
||||
*/
|
||||
@Test
|
||||
void sessionTagsDecideTheCallAndOverrideTheRolesOwnTags() {
|
||||
String name = "principal-session-" + suffix();
|
||||
String source = "principal-passer-" + suffix();
|
||||
UserCredentials keys = user(ACCOUNT, source, ALLOW_ASSUME);
|
||||
policy(source, "tagging", ALLOW_TAGGING);
|
||||
try (IamClient admin = admin(ACCOUNT);
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
|
||||
Region.US_EAST_1)) {
|
||||
String target = role(admin, ACCOUNT, name, trustAllowingTags(), TAG_POLICY);
|
||||
admin.tagRole(r -> r.roleName(name).tags(tag("Team", "other")));
|
||||
|
||||
Credentials passed = sts.assumeRole(r -> r.roleArn(target).roleSessionName("passed")
|
||||
.tags(sessionTag("Team", "platform"))).credentials();
|
||||
try (IamClient caller = sessionClient(passed)) {
|
||||
caller.listUsers();
|
||||
}
|
||||
|
||||
Credentials none = sts.assumeRole(r -> r.roleArn(target).roleSessionName("none")).credentials();
|
||||
try (IamClient caller = sessionClient(none)) {
|
||||
denied(caller::listUsers);
|
||||
}
|
||||
|
||||
Credentials blocked = sts.assumeRole(r -> r.roleArn(target).roleSessionName("blocked")
|
||||
.tags(sessionTag("Team", "platform"), sessionTag("Blocked", "yes"))).credentials();
|
||||
try (IamClient caller = sessionClient(blocked)) {
|
||||
denied(caller::listUsers);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A caller the trust policy lets assume the role but not tag the session cannot choose its own
|
||||
* principal tags: "for roles without this permission in the trust policy, the AssumeRole
|
||||
* operation fails". The same role is assumable without tags, so what is refused is the tagging.
|
||||
*/
|
||||
@Test
|
||||
void aTaggedAssumeNeedsTheTrustPolicysPermissionToTag() {
|
||||
String name = "principal-untagged-" + suffix();
|
||||
String source = "principal-untrusted-" + suffix();
|
||||
UserCredentials keys = user(ACCOUNT, source, ALLOW_ASSUME);
|
||||
policy(source, "tagging", ALLOW_TAGGING);
|
||||
try (IamClient admin = admin(ACCOUNT);
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
|
||||
Region.US_EAST_1)) {
|
||||
String target = role(admin, ACCOUNT, name, trust(null), TAG_POLICY);
|
||||
|
||||
AwsServiceException refused = assertThrows(AwsServiceException.class,
|
||||
() -> sts.assumeRole(r -> r.roleArn(target).roleSessionName("tagged")
|
||||
.tags(sessionTag("Team", "platform"))));
|
||||
assertEquals(403, refused.statusCode());
|
||||
// The role's own refusal, which names the resource it was read for, rather than the
|
||||
// caller's policy being short of the action: that grant is in place here.
|
||||
assertTrue(refused.awsErrorDetails().errorMessage()
|
||||
.endsWith("is not authorized to perform: sts:TagSession on resource: " + target),
|
||||
refused.awsErrorDetails().errorMessage());
|
||||
sts.assumeRole(r -> r.roleArn(target).roleSessionName("untagged"));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A federated user's session tags are principal tags of its requests, beside the tags of the
|
||||
* user whose key minted it: "when you use the temporary credentials returned by the
|
||||
* GetFederationToken operation, the session principal tags include the user tags and the passed
|
||||
* session tags". The user is untagged here, so the session tag is the whole of what decides the
|
||||
* call.
|
||||
*
|
||||
* <p>The probe is an object read rather than an IAM call, which such a session never reaches,
|
||||
* and it carries the session policy AWS requires of it: without one "the temporary security
|
||||
* credentials will not grant any permissions", so the policy is what the tag is read in.
|
||||
*/
|
||||
@Test
|
||||
void federatedSessionTagsJoinTheIssuingUsersTags() {
|
||||
String bucket = "principal-federated-" + suffix();
|
||||
String name = "principal-fed-user-" + suffix();
|
||||
String read = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::%s/*"}]}""".formatted(bucket);
|
||||
String readWhenTagged = """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:GetObject",
|
||||
"Resource":"arn:aws:s3:::%s/*",
|
||||
"Condition":{"StringEquals":{"aws:PrincipalTag/Team":"platform"}}}]}""".formatted(bucket);
|
||||
UserCredentials keys = user(ACCOUNT, name, read);
|
||||
policy(name, "federation", ALLOW_FEDERATION);
|
||||
try (S3Client owner = AwsTestClients.create(S3Client.builder().forcePathStyle(true), ACCOUNT, Region.US_EAST_1);
|
||||
StsClient sts = AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(),
|
||||
Region.US_EAST_1)) {
|
||||
owner.createBucket(r -> r.bucket(bucket));
|
||||
cleanup.register(() -> {
|
||||
try (S3Client client = AwsTestClients.create(S3Client.builder().forcePathStyle(true),
|
||||
ACCOUNT, Region.US_EAST_1)) {
|
||||
client.deleteObject(r -> r.bucket(bucket).key("key"));
|
||||
client.deleteBucket(r -> r.bucket(bucket));
|
||||
}
|
||||
});
|
||||
owner.putObject(r -> r.bucket(bucket).key("key"), RequestBody.fromString("content"));
|
||||
|
||||
Credentials tagged = sts.getFederationToken(r -> r.name("fed-" + suffix()).policy(readWhenTagged)
|
||||
.tags(sessionTag("Team", "platform"))).credentials();
|
||||
try (S3Client reader = federatedClient(tagged)) {
|
||||
assertEquals("content", reader.getObjectAsBytes(r -> r.bucket(bucket).key("key")).asUtf8String());
|
||||
}
|
||||
|
||||
Credentials untagged = sts.getFederationToken(r -> r.name("fed-" + suffix())
|
||||
.policy(readWhenTagged)).credentials();
|
||||
try (S3Client reader = federatedClient(untagged)) {
|
||||
denied(() -> reader.getObjectAsBytes(r -> r.bucket(bucket).key("key")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void sameNamedUsersInDifferentAccountsKeepTheirOwnTags() {
|
||||
String name = "principal-account-" + suffix();
|
||||
@@ -185,6 +318,11 @@ class PrincipalTagEnforcementIntegrationTest {
|
||||
return keys;
|
||||
}
|
||||
|
||||
/** A second inline policy on a user of this account, for a case that needs two grants. */
|
||||
private void policy(String userName, String policyName, String document) {
|
||||
EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), userName, policyName, document);
|
||||
}
|
||||
|
||||
private String role(IamClient admin, String account, String name, String trust, String policy) {
|
||||
String arn = admin.createRole(r -> r.roleName(name).path("/teams/platform/")
|
||||
.assumeRolePolicyDocument(trust)).role().arn();
|
||||
@@ -194,10 +332,23 @@ class PrincipalTagEnforcementIntegrationTest {
|
||||
}
|
||||
|
||||
private static String trust(String team) {
|
||||
return trust(team, "\"sts:AssumeRole\"");
|
||||
}
|
||||
|
||||
/**
|
||||
* A trust policy that permits tagging the session as well as assuming the role, which a
|
||||
* request passing session tags needs: "trust policies for all roles connected to the identity
|
||||
* provider passing tags must have the sts:TagSession permission."
|
||||
*/
|
||||
private static String trustAllowingTags() {
|
||||
return trust(null, "[\"sts:AssumeRole\",\"sts:TagSession\"]");
|
||||
}
|
||||
|
||||
private static String trust(String team, String action) {
|
||||
String condition = team == null ? "" : ",\"Condition\":{\"StringEquals\":{\"aws:PrincipalTag/Team\":\"" + team + "\"}}";
|
||||
return """
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole",
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"}%s}]}""".formatted(ACCOUNT, condition);
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":%s,
|
||||
"Principal":{"AWS":"arn:aws:iam::%s:root"}%s}]}""".formatted(action, ACCOUNT, condition);
|
||||
}
|
||||
|
||||
private static IamClient admin(String account) {
|
||||
@@ -215,6 +366,11 @@ class PrincipalTagEnforcementIntegrationTest {
|
||||
.tokenCode(device.codeNow())).credentials();
|
||||
}
|
||||
|
||||
private S3Client federatedClient(Credentials session) {
|
||||
return AwsTestClients.create(S3Client.builder().forcePathStyle(true), sessionCredentials(session),
|
||||
Region.US_EAST_1, baseUri);
|
||||
}
|
||||
|
||||
private IamClient sessionClient(Credentials session) {
|
||||
return AwsTestClients.create(IamClient.builder(), sessionCredentials(session), Region.US_EAST_1, baseUri);
|
||||
}
|
||||
@@ -233,6 +389,14 @@ class PrincipalTagEnforcementIntegrationTest {
|
||||
return Tag.builder().key(key).value(value).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* A session tag for a request that mints a session. Both services model a {@code Tag} of their
|
||||
* own, and IAM's is the one this class names most, so STS's is qualified here, once.
|
||||
*/
|
||||
private static software.amazon.awssdk.services.sts.model.Tag sessionTag(String key, String value) {
|
||||
return software.amazon.awssdk.services.sts.model.Tag.builder().key(key).value(value).build();
|
||||
}
|
||||
|
||||
private static String suffix() {
|
||||
return UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
@@ -449,6 +449,41 @@ class StsQueryHandlerTest {
|
||||
assertFalse(StsRequestShapes.hasMember("AssumeRoot", "Tags"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags the request's own {@code Tags} member carries are recorded on the session the
|
||||
* operation mints, which is what its requests then publish as {@code aws:PrincipalTag}. An
|
||||
* operation that declares no such member records nothing: the long-term session mints from the
|
||||
* caller's own credentials and takes no tags at all.
|
||||
*/
|
||||
@Test
|
||||
void theTagsAnOperationDeclaresAreRecordedOnTheSessionItMints() {
|
||||
IamRole role = new IamRole();
|
||||
role.setRoleName("TestRole");
|
||||
role.setArn("arn:aws:iam::000000000000:role/TestRole");
|
||||
IamService assumed = mock(IamService.class);
|
||||
when(assumed.findRole(anyString(), anyString())).thenReturn(Optional.of(role));
|
||||
MultivaluedMap<String, String> params = sessionRequest("AssumeRole");
|
||||
params.putSingle("Tags.member.1.Key", "Project");
|
||||
params.putSingle("Tags.member.1.Value", "atlas");
|
||||
|
||||
Response response = newHandler(assumed, new RegionResolver(REGION, "000000000000"))
|
||||
.handle("AssumeRole", params);
|
||||
|
||||
assertEquals(200, response.getStatus(), (String) response.getEntity());
|
||||
verify(assumed).recordSessionTags(anyString(), eq(Map.of("Project", "atlas")));
|
||||
|
||||
IamService longTerm = mock(IamService.class);
|
||||
MultivaluedMap<String, String> untagged = sessionRequest("GetSessionToken");
|
||||
untagged.putSingle("Tags.member.1.Key", "Project");
|
||||
untagged.putSingle("Tags.member.1.Value", "atlas");
|
||||
|
||||
Response longTermResponse = newHandler(longTerm, new RegionResolver(REGION, "000000000000"))
|
||||
.handle("GetSessionToken", untagged);
|
||||
|
||||
assertEquals(200, longTermResponse.getStatus(), (String) longTermResponse.getEntity());
|
||||
verify(longTerm, never()).recordSessionTags(anyString(), anyMap());
|
||||
}
|
||||
|
||||
/** The least a request needs to reach issuance on an operation that models a token size. */
|
||||
private static MultivaluedMap<String, String> sessionRequest(String action) {
|
||||
Map<String, String> members = switch (action) {
|
||||
@@ -1011,7 +1046,8 @@ class StsQueryHandlerTest {
|
||||
* A role and its account's OIDC provider are IAM resources of one partition, so a trust policy
|
||||
* naming the provider ARN CreateOpenIDConnectProvider returned keeps matching and the session
|
||||
* lands in the stored role's partition, whatever region AssumeRoleWithWebIdentity is signed for
|
||||
* and whichever partition its RoleArn names.
|
||||
* and whichever partition its RoleArn names. The session tags the token passed are recorded on
|
||||
* it as well, this operation taking them from the token rather than from a request member.
|
||||
*/
|
||||
@Test
|
||||
void webIdentityMatchesTheProviderAndMintsTheSessionInTheRolesPartition() throws Exception {
|
||||
@@ -1034,11 +1070,14 @@ class StsQueryHandlerTest {
|
||||
when(verifier.peekIssuer("jwt0")).thenReturn(Optional.of(issuer));
|
||||
when(verifier.verify(eq("jwt0"), any(), eq(issuer), anyString()))
|
||||
.thenReturn(new WebIdentityToken(issuer, "system:serviceaccount:default:app",
|
||||
List.of("sts.amazonaws.com")));
|
||||
List.of("sts.amazonaws.com"), Map.of("Project", "atlas")));
|
||||
OidcIssuerKeyLookup keys = mock(OidcIssuerKeyLookup.class);
|
||||
when(keys.findVerificationKey(issuer)).thenReturn(Optional.of(mock(RSAPublicKey.class)));
|
||||
WebIdentityTrustPolicyEvaluator trust = mock(WebIdentityTrustPolicyEvaluator.class);
|
||||
when(trust.allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"))).thenReturn(true);
|
||||
// The token passes a session tag, which the trust policy has to permit as well.
|
||||
when(trust.allowsTagging(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app")))
|
||||
.thenReturn(true);
|
||||
|
||||
StsQueryHandler handler = new StsQueryHandler(iamService, mock(AccountResolver.class),
|
||||
new RegionResolver(REGION, "000000000000"), config, mock(AssumeRolePolicyEvaluator.class),
|
||||
@@ -1056,6 +1095,10 @@ class StsQueryHandlerTest {
|
||||
verify(trust).allows(eq("{}"), eq(providerArn), eq("oidc.example.com/id/ABC"), anyMap(), eq("app"));
|
||||
assertEquals("arn:aws-cn:sts::000000000000:assumed-role/web-role/app",
|
||||
extract(ARN, (String) response.getEntity()));
|
||||
verify(iamService).recordSessionTags(anyString(), eq(Map.of("Project", "atlas")));
|
||||
// The token's tags are state its session carries, so they count with the token itself.
|
||||
assertEquals(Integer.toString(200 + "Project".length() + "atlas".length()),
|
||||
extract(SESSION_TOKEN_SIZE, (String) response.getEntity()));
|
||||
}
|
||||
|
||||
/** A session keeps its role's partition even when AssumeRole is signed for another one. */
|
||||
|
||||
Reference in new issue
Block a user