diff --git a/.github/workflows/iam-data-drift.yml b/.github/workflows/iam-data-drift.yml index 3f9fafce1d..3459809f79 100644 --- a/.github/workflows/iam-data-drift.yml +++ b/.github/workflows/iam-data-drift.yml @@ -103,6 +103,9 @@ on: - 'tools/aws/sources/route53-condition-keys.json' - 'tools/aws/fetch_route53_conditions.py' - 'tools/aws/test_fetch_route53_conditions.py' + - 'tools/aws/sources/sts-source-identity.json' + - 'tools/aws/fetch_sts_source_identity.py' + - 'tools/aws/test_fetch_sts_source_identity.py' - 'src/main/resources/aws/rest-routes.json' - 'tools/aws/regen_rest_routes.py' - 'tools/aws/test_regen_rest_routes.py' diff --git a/Makefile b/Makefile index d9b4689620..4db960fd97 100644 --- a/Makefile +++ b/Makefile @@ -620,7 +620,9 @@ IAM_ACTION_RESOURCES_PATHS := src/main/resources/aws/iam-action-resources.json \ IAM_AUTHORIZED_ACTIONS_PATHS := src/main/resources/aws/iam-authorized-actions.json \ tools/aws/regen_iam_authorized_actions.py tools/aws/test_regen_iam_authorized_actions.py \ src/main/resources/aws/rest-routes.json tools/aws/sources/s3-required-actions.json \ - tools/aws/fetch_s3_required_actions.py tools/aws/test_fetch_s3_required_actions.py + tools/aws/fetch_s3_required_actions.py tools/aws/test_fetch_s3_required_actions.py \ + tools/aws/sources/sts-source-identity.json tools/aws/fetch_sts_source_identity.py \ + tools/aws/test_fetch_sts_source_identity.py IAM_PASSED_ROLES_PATHS := src/main/resources/aws/iam-passed-roles.json $(IAM_PASSED_ROLES_GENERATOR) \ tools/aws/test_regen_iam_passed_roles.py tools/aws/sources/eks-roles.json tools/aws/fetch_eks_roles.py \ tools/aws/test_fetch_eks_roles.py tools/aws/sources/emr-roles.json tools/aws/fetch_emr_roles.py \ @@ -649,7 +651,8 @@ REQUEST_CONDITION_KEYS_PATHS := src/main/resources/aws/request-condition-keys.js tools/aws/test_fetch_eventbridge_conditions.py tools/aws/sources/eks-condition-keys.json \ tools/aws/fetch_eks_conditions.py tools/aws/test_fetch_eks_conditions.py \ tools/aws/sources/route53-condition-keys.json tools/aws/fetch_route53_conditions.py \ - tools/aws/test_fetch_route53_conditions.py + tools/aws/test_fetch_route53_conditions.py tools/aws/sources/sts-source-identity.json \ + tools/aws/fetch_sts_source_identity.py tools/aws/test_fetch_sts_source_identity.py DOCUMENTED_ROUTES_PATHS := src/main/resources/aws/rest-routes.json tools/aws/regen_rest_routes.py \ tools/aws/test_regen_rest_routes.py tools/aws/regen_partitions.py tools/aws/regen_query_services.py IAM_REQUEST_RESOURCES_PATHS := src/main/resources/aws/iam-request-resources.json \ diff --git a/docs/services/iam.md b/docs/services/iam.md index 5bf368515e..7770d9a8ba 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -3387,7 +3387,8 @@ As with passed roles, an operation Floci does not serve is in the table too. under the further spellings the RDS, DocumentDB, Neptune, ElastiCache and Redshift handlers read. IAM's and STS's are read as those handlers read them, through the one Query list reader: `Tags.member.N` or the bare `Tags.N`, at every number sent, in the order of the numbers, so a key - sent twice keeps the later number's value, as the session or the resource does. + sent twice keeps the later number's value, as the resource does; an `AssumeRole` naming a key twice + is refused (see [STS](sts.md#session-tags)). EC2's are read from every tag specification, under `TagSpecification` or `TagSpecifications`, as EC2 applies either, to the first that names no resource type. SQS's are read from `Tag.N.Key` and `Tag.N.Value` over the Query protocol. The tagging action is also checked for tags under any other @@ -4112,6 +4113,12 @@ floci populates: matches: a `Deny` on `DateLessThan` `aws:TokenIssueTime` refuses the sessions issued before that time and leaves later sessions and long-term keys alone. A session stored by an earlier floci version, which did not record its issue time, carries no value for it. +- `aws:SourceIdentity`: the source identity an `AssumeRole` session was minted with, on every request + it makes and every session assumed from it, as the IAM user guide gives it: "after a source identity + is set, the aws:SourceIdentity key is present in all subsequent requests made during the role + session". The key is the one the generated `iam-authorized-actions.json` gives the value its + operation sets. Absent for a session minted with none and for every long-term key. See + [STS](sts.md#source-identity). - `aws:CurrentTime` and `aws:EpochTime`: the time of the request, which the guide says "is always included in the request context": `aws:CurrentTime` as an ISO 8601 date, `aws:EpochTime` as whole seconds since January 1, 1970, so it matches the `Date` and the `Numeric` operators. @@ -4232,9 +4239,11 @@ floci populates: the role's trust policy reads them (see [STS](sts.md)); `sts:ExternalId` is absent when the request passes none. The actions and request members come from the same `request-condition-keys.json`. `AssumeRoleWithWebIdentity` and `AssumeRoleWithSAML` are not signed, so no identity-based policy is - evaluated for them. `sts:SourceIdentity` and `sts:TransitiveTagKeys` are not populated for `AssumeRole`: - source identity is not modelled, and the tag key is not in this file for the action, which is what fills - the context here. The tags the request passes are its `aws:RequestTag/` and `aws:TagKeys`, from + evaluated for them. `sts:SourceIdentity` is the `SourceIdentity` an `AssumeRole` passes, or the one its + calling session carries on, read through this file from the IAM user guide's page on source identity, and + setting one needs `sts:SetSourceIdentity` as well (see [STS](sts.md#source-identity)). + `sts:TransitiveTagKeys` is not populated for `AssumeRole`: the key is not in this file for the action, + which is what fills the context here. The tags the request passes are its `aws:RequestTag/` and `aws:TagKeys`, from `iam-tag-on-create.json`, for the caller's policies and the role's trust policy alike. A session's own tags are modelled, and reach a policy as `aws:PrincipalTag/`; `sts:TransitiveTagKeys` reaches the role's trust policy, which the STS handler reads with a context of its own (see diff --git a/docs/services/sts.md b/docs/services/sts.md index a70a56ec98..dc3381bc5b 100644 --- a/docs/services/sts.md +++ b/docs/services/sts.md @@ -505,8 +505,7 @@ policy reading both: with `aws:RequestTag` "you can allow the principal to pass tags, but only with the specified values", and with `aws:TagKeys` "pass only session tags with the specified tag keys". The assume and the `sts:TagSession` permission are each read once for every set of tags a reading of the list gives, past a gap in its -numbering or with each value of a key sent twice, as the caller's policies are, so a `Deny` on a tag -holds however the list is sent. A request passing no tags carries neither key, so a trust statement +numbering, as the caller's policies are, so a `Deny` on a tag holds however the list is numbered. A request passing no tags carries neither key, so a trust statement that requires one does not allow it. The session's tags sit over the tags of the identity it acts as. For a role session that is the @@ -514,9 +513,12 @@ role's own tags, for a federated user the tags of the user whose key minted it, 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". +own spelling is the one published. An `AssumeRole` naming a key twice, in either case, is refused as +AWS refuses it, with `InvalidParameterValue` and +`Duplicate tag keys found. Please note that Tag keys are case insensitive.`, which AWS's own +evaluation suite records. Two tags of an assertion, a token or a `GetFederationToken` 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 @@ -624,12 +626,63 @@ the role tag of an earlier link fails, which does not follow from the published being nothing the earlier session passed down, so what is built here is the rule the API Reference states. +#### Source identity + +An `AssumeRole` may name the session's source identity, which botocore holds to 2 to 256 of +`[\w+=,.@-]`, so a value beginning with `aws:`, a prefix "reserved for Amazon Web Services internal +use", is refused with the rest, for its colon: +`1 validation error detected: Value '' at 'sourceIdentity' failed to satisfy constraint: Member must satisfy regular expression pattern: [\w+=,.@-]*`, +as AWS answers it. The response returns the value in `SourceIdentity`. + +Setting one needs `sts:SetSourceIdentity`: "to specify a source identity, principals (IAM users and +roles) must have permissions to sts:SetSourceIdentity", configured "in the role trust policy and in +the principal's permissions policy". The Service Authorization Reference lists the action among the +ones `AssumeRole` is authorized by, and the IAM user guide's page on source identity, vendored into +`tools/aws/sources/sts-source-identity.json` by `tools/aws/fetch_sts_source_identity.py`, says when +it is needed, which the generated `iam-authorized-actions.json` carries as `AssumeRole`'s companion +action. [Enforcement](iam.md#iam-enforcement-mode) checks the caller's own policies for it on the +role's ARN, and STS checks the role's trust policy for it before the assume itself, AWS naming +`sts:SetSourceIdentity` where a trust statement allowing both actions is conditioned on another +`sts:SourceIdentity`. Each refusal names the action, the trust policy's as +`User: is not authorized to perform: sts:SetSourceIdentity on resource: `. + +The request carries the value as `sts:SourceIdentity`, read from its `SourceIdentity` through the +generated `request-condition-keys.json`, which the same vendored page fills: "when an identity sets a +source identity, the sts:SourceIdentity key is present in the request". The caller's policies and the +trust policy both read it. The session's later requests, to any service, carry it as +`aws:SourceIdentity`: "for subsequent actions taken during the role session, the aws:SourceIdentity +key is present in the request". + +The value "persists when a role is used to assume another role through the AWS CLI or AWS API, known +as role chaining", and "cannot be changed during the role session". A session assumed from one +carrying a source identity carries it too, without its request naming it, and that assume is read +with both keys, "both the aws:SourceIdentity and sts:SourceIdentity keys are present in the request +context". The permission is "required in both the permissions policy of the principal who is assuming +the role and in the role trust policy of the target role", so the chained assume needs +`sts:SetSourceIdentity` of both: a chained caller's own permissions must allow it even where the +target's trust policy names the caller's role, which in the same account would otherwise stand in for +them. The generated table carries that as the companion's `callerPolicyWhenChained`, from the page's +sentence on role chaining. A chained request naming the value its session carries is allowed, +and one naming another is refused, before the trust policy is read, with `ValidationError` and +`The source identity is already set for this assume role session`, as AWS answers it. + ### Known limitations -- **The source-identity condition key is not in the request context.** `sts:SourceIdentity` is - not populated, so a condition on it does not match, and `sts:SetSourceIdentity` is not checked at - all. `sts:TransitiveTagKeys` is populated for the trust policy and not for the caller's own - identity-based policies, as [Transitive tags](#transitive-tags) says. +- **The transitive tag key is read for the trust policy alone.** `sts:TransitiveTagKeys` is + populated for the trust policy and not for the caller's own identity-based policies, as + [Transitive tags](#transitive-tags) says. +- **A chained assume into a trust policy that grants the assume alone names + `sts:SetSourceIdentity`.** Floci reads the trust policy's `sts:SetSourceIdentity` before its + `sts:AssumeRole` and names whichever refuses. AWS's evaluation suite records that order where a + statement granting both is conditioned on another `sts:SourceIdentity`, and records + `sts:AssumeRole` where the chained session's target grants the assume alone. +- **A federated assume's source identity is not read.** The + `https://aws.amazon.com/SAML/Attributes/SourceIdentity` attribute of an `AssumeRoleWithSAML` + assertion and the `https://aws.amazon.com/source_identity` claim of an + `AssumeRoleWithWebIdentity` token set no source identity yet. A calling session's source identity + does not reach either: neither is a chained assume, "calling AssumeRoleWithSAML does not require the + use of AWS security credentials", and so too for `AssumeRoleWithWebIdentity`, so theirs is the + assertion's or the token's. - **A federated assume's tags are not request tags of its trust policy.** The trust policy of an `AssumeRoleWithSAML` or `AssumeRoleWithWebIdentity` does not see the tags the assertion or the token passes as `aws:RequestTag/` and `aws:TagKeys`, which the Service Authorization Reference diff --git a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java index 108ae4834c..6cbc8eb914 100644 --- a/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java +++ b/src/main/java/io/floci/aws/core/common/IamConditionContextResolver.java @@ -469,6 +469,34 @@ public class IamConditionContextResolver { .map(TagOnCreate::requestTagContexts).orElse(List.of())); } + /** + * Whether the request names {@code member}: a Query form's parameter, or a JSON body's top-level member. + */ + static boolean namesMember(ContainerRequestContext ctx, String member) { + if (formParameters(ctx).containsKey(member)) { + return true; + } + JsonNode body = PassedRoles.jsonBody(ctx); + return body != null && body.has(member); + } + + /** + * {@code context} with each key the request condition key table reads for {@code action} from {@code member} + * taking {@code value} where the context has none of its own, for a value the request does not name but its caller + * carries: a chained AssumeRole's source identity, for which "both the aws:SourceIdentity and sts:SourceIdentity + * keys are present in the request context". + */ + public static Map> withCarriedMember(Map> context, String action, + String member, String value) { + Map> carried = context == null ? new HashMap<>() : new HashMap<>(context); + for (String key : RequestConditionKeys.requestKeys(action)) { + if (RequestConditionKeys.members(action, key).contains(member)) { + carried.putIfAbsent(key, List.of(value)); + } + } + return carried; + } + /** * The context once for each set of tags the request carries, with that set's keys where the context has * none of its own, so each resource's tags are checked apart; the context alone when it carries none. diff --git a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java index ba9f5652ea..c278a515f2 100644 --- a/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java +++ b/src/main/java/io/floci/aws/core/common/IamEnforcementFilter.java @@ -9,6 +9,8 @@ import io.floci.aws.services.cloudwatch.metrics.OtlpMetricsController; import io.floci.aws.services.iam.AccessDeniedMessages; import io.floci.aws.services.iam.AccessDeniedMessages.PolicyType; import io.floci.aws.services.iam.IamActionRegistry; +import io.floci.aws.services.iam.IamAuthorizedActions; +import io.floci.aws.services.iam.IamAuthorizedActions.Companion; import io.floci.aws.services.iam.IamCloudTrailEvents; import io.floci.aws.services.iam.IamPolicyEvaluator; import io.floci.aws.services.iam.IamPolicyEvaluator.Decision; @@ -586,6 +588,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { conditionContext = conditionContext == null ? new HashMap<>() : new HashMap<>(conditionContext); callerArns.get().putPrincipalKeys(conditionContext); } + List companions = IamAuthorizedActions.companions(resolvedOperation.operation()); + conditionContext = withCarriedValues(companions, action, ctx, conditionContext); // Internal transfers bypass customer policies only for a registered session scope in a tagged bucket. if (isScratchTransfer(ctx, credentialScope, action, resources, akid, callerArns.orElse(null))) { return; @@ -600,7 +604,8 @@ public class IamEnforcementFilter implements ContainerRequestFilter { for (Map> target : remainingTargets) { Map> targetContext = new HashMap<>(target); callerArns.ifPresent(arns -> arns.putPrincipalKeys(targetContext)); - targetContexts.addAll(IamConditionContextResolver.withRequestTags(targetContext, requestTags)); + targetContexts.addAll(IamConditionContextResolver.withRequestTags( + withCarriedValues(companions, action, ctx, targetContext), requestTags)); } RequestPrincipal principal = RequestPrincipal.caller(callerArns.orElse(null)); @@ -646,6 +651,28 @@ public class IamEnforcementFilter implements ContainerRequestFilter { accountId, akid)) { return; } + // An operation setting a value needs the action the generated table gives it for that as well, on the + // resources the operation is checked on and with its keys: an AssumeRole passing a SourceIdentity, or made + // by a session carrying one, needs sts:SetSourceIdentity, since "to specify a source identity, principals + // (IAM users and roles) must have permissions to sts:SetSourceIdentity", and when chaining it is "required in + // both the permissions policy of the principal who is assuming the role and in the role trust policy". + // A caller that is itself a role session needs it of its own permissions as well, a trust policy naming its + // role not standing in for them, when the table says so (Companion#callerPolicyWhenChained). + boolean roleSession = callerArns.map(arns -> CallerArns.TYPE_ASSUMED_ROLE.equals(arns.principalType())) + .orElse(false); + for (Companion companion : companions) { + boolean sets = IamConditionContextResolver.namesMember(ctx, companion.member()) + || (conditionContext != null && conditionContext.containsKey(companion.carried())); + if (sets && roleSession && companion.callerPolicyWhenChained() + && abortIfOwnPolicyDenies(ctx, caller, companion.action(), credentialScope, resources, + targetContexts, akid)) { + return; + } + if (sets && abortIfDenied(ctx, caller, principal, companion.action(), action, credentialScope, resources, + targetContexts, region, accountId, akid)) { + return; + } + } // Tagged group creation requires either tagging permission, using the same resolved // caller (including session, boundary and SCP ceilings) as the primary operation, on the @@ -1119,6 +1146,47 @@ public class IamEnforcementFilter implements ContainerRequestFilter { region, accountId, akid); } + /** + * Checks {@code action} against the caller's own policies alone, its identity-based policies with its boundary, + * session policy and SCPs, no resource's policy granting it, on each resource with each context. Returns true when + * the request was aborted. + */ + private boolean abortIfOwnPolicyDenies(ContainerRequestContext ctx, CallerContext caller, String action, + String credentialScope, List resources, + List>> targetContexts, String akid) { + for (String resource : resources) { + for (Map> context : targetContexts) { + if (evaluator.evaluate(caller, null, action, resource, context) == Decision.DENY) { + LOG.infov("IAM enforcement DENY: akid={0} action={1} resource={2}", akid, action, resource); + ctx.abortWith(accessDeniedForRequest(action, credentialScope, ctx, resource)); + return true; + } + } + } + return false; + } + + /** + * {@code context} with each value the caller carries that the operation's request would set, where the request + * does not set it: a chained AssumeRole's source identity is its {@code sts:SourceIdentity} as well as the + * caller's {@code aws:SourceIdentity}, "both the aws:SourceIdentity and sts:SourceIdentity keys are present in + * the request context". + */ + private static Map> withCarriedValues(List companions, String action, + ContainerRequestContext ctx, + Map> context) { + Map> carried = context; + for (Companion companion : companions) { + List value = carried == null ? null : carried.get(companion.carried()); + if (value != null && !value.isEmpty() + && !IamConditionContextResolver.namesMember(ctx, companion.member())) { + carried = IamConditionContextResolver.withCarriedMember(carried, action, companion.member(), + value.getFirst()); + } + } + return carried; + } + /** * Checks {@code action}, which may be one the operation needs besides its own. A denial names * {@code action}, the permission that is missing, while the CloudTrail event records diff --git a/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java b/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java index 1d192526fd..6fcd55362e 100644 --- a/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java +++ b/src/main/java/io/floci/aws/services/iam/AssumeRolePolicyEvaluator.java @@ -115,6 +115,18 @@ public class AssumeRolePolicyEvaluator { return decision == TrustDecision.ALLOW || decision == TrustDecision.ALLOW_ACCOUNT; } + /** + * Whether the trust policy lets this caller perform {@code action} on the role beside the assume: an action the + * generated {@code iam-authorized-actions.json} gives the assume for a value it sets + * ({@code sts:SetSourceIdentity}), read on the same document, with the same principals and the same conditions + * as the assume itself. + */ + public boolean allowsCompanion(String action, String trustPolicyDocument, IamService.CallerArns caller, + String callerAccount, Map> requestContext) { + TrustDecision decision = decide(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 diff --git a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java index d72d5483a4..78724465c0 100644 --- a/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java +++ b/src/main/java/io/floci/aws/services/iam/IamAuthorizedActions.java @@ -7,8 +7,10 @@ import jakarta.ws.rs.core.MultivaluedMap; import java.io.IOException; import java.io.InputStream; +import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; @@ -43,6 +45,9 @@ import java.util.Set; * the operations of those scopes a request on whose route is checked as the action its HTTP method names * ({@link #actionFor(String, String, String)}): API Gateway's management API is authorized as * {@code apigateway:GET}, {@code apigateway:POST} and so on, and {@code TagResource} is a PUT in v1 and a POST in v2. + * And it lists the actions an operation needs beside its own only when it sets a value ({@link #companions}): an + * AssumeRole passing a {@code SourceIdentity}, or made by a session carrying one, needs {@code sts:SetSourceIdentity}, + * as the IAM user guide's page on source identity says. * *

A missing or malformed resource is a build defect, not a runtime condition, so loading fails * with {@link IllegalStateException} rather than degrading to an empty map, which would silently put @@ -71,10 +76,24 @@ public final class IamAuthorizedActions { * no resource type, as {@code :} in lower case, the operations authorized by method, as * {@code :}, the action of an operation for a request of one model's route, keyed by * {@code :@}, the operations whose action a request parameter chooses, and the - * reference's spelling of an action named as its operation in another case. + * reference's spelling of an action named as its operation in another case, and the actions each operation needs + * beside its own when it sets a value, keyed by {@code :}. */ record Table(Map actions, Set withoutResourceTypes, Set byMethod, - Map byModel, Map versioned, Map spellings) { + Map byModel, Map versioned, Map spellings, + Map> companions) { + } + + /** + * An action an operation needs beside its own when its request names {@code member}, or its caller carries the + * value that member sets as the global key {@code carried}: an AssumeRole passing a {@code SourceIdentity}, or + * made by a session whose requests carry {@code aws:SourceIdentity}, needs {@code sts:SetSourceIdentity}. With + * {@code callerPolicyWhenChained}, a caller that is itself a role session needs it of its own permissions, + * whatever the resource's policy grants: "when you assume a role with another role, called role chaining, + * permissions for sts:SetSourceIdentity are required in both the permissions policy of the principal who is + * assuming the role and in the role trust policy of the target role". + */ + public record Companion(String action, String member, String carried, boolean callerPolicyWhenChained) { } /** @@ -145,6 +164,14 @@ public final class IamAuthorizedActions { return action != null && Holder.TABLE.withoutResourceTypes().contains(action.toLowerCase(Locale.ROOT)); } + /** + * The actions {@code operation}, as {@code :}, needs beside its own when it sets a value; + * none for an operation the file gives none. + */ + public static List companions(String operation) { + return Holder.TABLE.companions().getOrDefault(operation, List.of()); + } + /** The file's entries. */ static Table parse(InputStream in) throws IOException { JsonNode document = MAPPER.readTree(in); @@ -171,7 +198,28 @@ public final class IamAuthorizedActions { }); return new Table(Map.copyOf(actions), withoutResourceTypes(document.path("actionsWithoutResourceTypes")), byMethod(document.path("authorizedByMethod")), byModel(document.path("authorizedByModel")), - versioned(document.path("versioned")), spellings(document.path("spellings"))); + versioned(document.path("versioned")), spellings(document.path("spellings")), + companions(document.path("companions"))); + } + + /** Each namespace's operations' companion actions, keyed {@code :}. */ + private static Map> companions(JsonNode namespaces) { + Map> found = new LinkedHashMap<>(); + namespaces.properties().forEach(namespace -> namespace.getValue().properties().forEach(operation -> { + List needed = new ArrayList<>(); + for (JsonNode companion : operation.getValue()) { + String member = companion.path("member").asText(""); + String carried = companion.path("carried").asText(""); + if (member.isEmpty() || !carried.startsWith("aws:")) { + throw new IllegalStateException(RESOURCE_NAME + " gives " + namespace.getKey() + ":" + + operation.getKey() + " a companion naming no member or no global key"); + } + needed.add(new Companion(actionOf(namespace.getKey(), operation.getKey(), companion.path("action")), + member, carried, companion.path("callerPolicyWhenChained").asBoolean(false))); + } + found.put(namespace.getKey() + ":" + operation.getKey(), List.copyOf(needed)); + })); + return Map.copyOf(found); } /** Each namespace's operations' actions for one model's requests, keyed {@code :@}. */ diff --git a/src/main/java/io/floci/aws/services/iam/IamService.java b/src/main/java/io/floci/aws/services/iam/IamService.java index 83cd84ed7b..901ad12c05 100644 --- a/src/main/java/io/floci/aws/services/iam/IamService.java +++ b/src/main/java/io/floci/aws/services/iam/IamService.java @@ -5291,6 +5291,33 @@ public class IamService implements SessionAccountLookup, ResourceProvider { }); } + /** + * Records the values {@code sessionAccessKeyId} was minted with that its requests carry, under the global keys + * they are carried as ({@link SessionCredential#getCarriedKeys}): its source identity as + * {@code aws:SourceIdentity}. + */ + public void recordCarriedKeys(String sessionAccessKeyId, Map keys) { + if (sessionAccessKeyId == null || keys == null || keys.isEmpty()) { + return; + } + sessions.get(sessionAccessKeyId).ifPresent(session -> { + session.setCarriedKeys(keys); + sessions.put(sessionAccessKeyId, session); + }); + } + + /** + * The values the credentials {@code accessKeyId} carry under the global keys they are carried as, which a session + * assumed from them carries on: a source identity "persists when a role is used to assume another role". A + * long-term key carries none, there being no session behind it. + */ + public Map callerCarriedKeys(String accessKeyId) { + return findSessionForCallerContext(accessKeyId) + .map(SessionCredential::getCarriedKeys) + .map(Map::copyOf) + .orElseGet(Map::of); + } + /** * The transitive session tags the credentials {@code accessKeyId} carry, which a session * assumed from them inherits: "if you used temporary credentials to perform this operation, @@ -6699,10 +6726,20 @@ public class IamService implements SessionAccountLookup, ResourceProvider { String userId, String userName, boolean permissionsBoundary, Map principalTags, SessionMfa sessionMfa, PrincipalOrganization.OrganizationContext organization, - Instant tokenIssueTime) { + Instant tokenIssueTime, Map carriedKeys) { public CallerArns { principalTags = Map.copyOf(principalTags); + carriedKeys = carriedKeys == null ? Map.of() : Map.copyOf(carriedKeys); + } + + /** A caller carrying no value a session was minted with, which every caller but a session's is. */ + public CallerArns(String callerArn, String principalArn, String principalType, + String userId, String userName, boolean permissionsBoundary, + Map principalTags, SessionMfa sessionMfa, + PrincipalOrganization.OrganizationContext organization, Instant tokenIssueTime) { + this(callerArn, principalArn, principalType, userId, userName, permissionsBoundary, principalTags, + sessionMfa, organization, tokenIssueTime, Map.of()); } /** A caller whose account's organization has not been read, which every unresolved site gives. */ @@ -6739,7 +6776,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { /** Copy of this caller with what the session it signed with says about MFA. */ public CallerArns withSessionMfa(SessionMfa mfa) { return new CallerArns(callerArn, principalArn, principalType, userId, userName, - permissionsBoundary, principalTags, mfa, organization, tokenIssueTime); + permissionsBoundary, principalTags, mfa, organization, tokenIssueTime, carriedKeys); } /** @@ -6750,13 +6787,22 @@ public class IamService implements SessionAccountLookup, ResourceProvider { public CallerArns withOrganization(PrincipalOrganization.OrganizationContext context) { return context == null ? this : new CallerArns(callerArn, principalArn, principalType, userId, userName, permissionsBoundary, principalTags, sessionMfa, context, - tokenIssueTime); + tokenIssueTime, carriedKeys); } /** The same caller, signing with temporary credentials issued at {@code issuedAt}. */ public CallerArns withTokenIssueTime(Instant issuedAt) { return new CallerArns(callerArn, principalArn, principalType, userId, userName, - permissionsBoundary, principalTags, sessionMfa, organization, issuedAt); + permissionsBoundary, principalTags, sessionMfa, organization, issuedAt, carriedKeys); + } + + /** + * The same caller, carrying the values its session was minted with under the global keys they are carried as + * ({@link SessionCredential#getCarriedKeys}). + */ + public CallerArns withCarriedKeys(Map keys) { + return new CallerArns(callerArn, principalArn, principalType, userId, userName, + permissionsBoundary, principalTags, sessionMfa, organization, tokenIssueTime, keys); } /** A caller without stored principal tags, including account-root and federated identities. */ @@ -6823,6 +6869,10 @@ public class IamService implements SessionAccountLookup, ResourceProvider { *

{@code aws:TokenIssueTime} follows the same rule: it is "included in the request * context only when the principal uses temporary credentials to make the request" and "is * not present in AWS CLI, AWS API, or AWS SDK requests that are made using access keys". + * + *

So do the keys a session carries a value it was minted with as, {@code aws:SourceIdentity} for its + * source identity: "after a source identity is set, the aws:SourceIdentity key is present in all subsequent + * requests made during the role session". */ public void putPrincipalKeys(Map> context) { context.put("aws:PrincipalArn", List.of(principalArn)); @@ -6843,6 +6893,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { if (tokenIssueTime != null) { context.put("aws:TokenIssueTime", List.of(tokenIssueTime.toString())); } + carriedKeys.forEach((key, value) -> context.put(key, List.of(value))); } /** @@ -6964,7 +7015,8 @@ public class IamService implements SessionAccountLookup, ResourceProvider { // instead of at each of the identities below. CallerArns.SessionMfa mfa = sessionMfa(session); return callerForSession(session) - .map(caller -> caller.withSessionMfa(mfa).withTokenIssueTime(session.getIssuedAt())); + .map(caller -> caller.withSessionMfa(mfa).withTokenIssueTime(session.getIssuedAt()) + .withCarriedKeys(session.getCarriedKeys())); } return Optional.empty(); diff --git a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java index 37c9e0b8cf..bbce7ca701 100644 --- a/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java +++ b/src/main/java/io/floci/aws/services/iam/StsQueryHandler.java @@ -45,8 +45,10 @@ import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -187,6 +189,10 @@ public class StsQueryHandler { if (validation != null) { return validation; } + Response duplicateTags = refuseDuplicateTagKeys(params); + if (duplicateTags != null) { + return duplicateTags; + } MfaOutcome mfa = authenticateMfa(params); if (mfa.denial() != null) { return mfa.denial(); @@ -211,8 +217,24 @@ public class StsQueryHandler { // tagging the session for these as well as for the tags the request passes. Map inheritedTags = inheritedTransitiveTags("AssumeRole"); + // The source identity the session is minted with: the one the request passes, or the one the calling session + // carries, which "persists when a role is used to assume another role" and "cannot be changed during the role + // session". A chained request passing another is refused before the trust policy is read, as AWS refuses it + // even where the target's trust would not allow the value. + Optional sourceIdentityKey = sourceIdentityCompanion(); + String carriedIdentity = sourceIdentityKey + .map(key -> iamService.callerCarriedKeys(callerAccessKeyId()).get(key.carried())) + .orElse(null); + String passedIdentity = getParam(params, SOURCE_IDENTITY); + if (passedIdentity != null && carriedIdentity != null && !passedIdentity.equals(carriedIdentity)) { + return AwsQueryResponse.error("ValidationError", + "The source identity is already set for this assume role session", AwsNamespaces.STS, 400); + } + String sourceIdentity = passedIdentity != null ? passedIdentity : carriedIdentity; + IamRole role = iamService.findRole(accountId, roleName).orElse(null); - Response trustDenied = enforceTrustPolicy(roleArn, role, accountId, params, mfa, inheritedTags); + Response trustDenied = enforceTrustPolicy(roleArn, role, accountId, params, mfa, inheritedTags, + sourceIdentity); if (trustDenied != null) { return trustDenied; } @@ -258,6 +280,12 @@ public class StsQueryHandler { List transitiveKeys = new ArrayList<>(inheritedTags.keySet()); transitiveKeys.addAll(transitiveTagKeys(params)); iamService.recordSessionTags(accessKeyId, sessionTags, transitiveKeys); + // Its requests carry the source identity as the key the generated table gives it, which a session assumed + // from this one carries on. + if (sourceIdentity != null) { + sourceIdentityKey.ifPresent(key -> iamService.recordCarriedKeys(accessKeyId, + Map.of(key.carried(), sourceIdentity))); + } String result = new XmlBuilder() .raw(credentialsXml(accessKeyId, secretKey, sessionToken, expiration)) @@ -266,10 +294,49 @@ public class StsQueryHandler { .elem("AssumedRoleId", assumedRoleId) .end("AssumedRoleUser") .raw(sessionSizeXml("AssumeRole", assembledSession("AssumeRole", params, inheritedTags))) + .elem(SOURCE_IDENTITY, sourceIdentity) .build(); return Response.ok(AwsQueryResponse.envelope("AssumeRole", AwsNamespaces.STS, result)).build(); } + /** + * The AssumeRole request member and response member botocore gives a session's source identity, "the source + * identity specified by the principal that is calling the AssumeRole operation". + */ + private static final String SOURCE_IDENTITY = "SourceIdentity"; + + /** + * What the generated {@code iam-authorized-actions.json} gives an AssumeRole setting a source identity: the action + * it needs beside the assume, {@code sts:SetSourceIdentity}, and the key the session's requests then carry the + * value as, {@code aws:SourceIdentity}. Empty were the file to give none, which leaves the value echoed and + * carried by no key. + */ + private static Optional sourceIdentityCompanion() { + return IamAuthorizedActions.companions("sts:AssumeRole").stream() + .filter(companion -> SOURCE_IDENTITY.equals(companion.member())) + .findFirst(); + } + + /** + * An AssumeRole naming a session tag key twice, in any case, is refused as AWS refuses it, with + * {@code InvalidParameterValue} and "Duplicate tag keys found. Please note that Tag keys are case insensitive.", + * which AWS's own evaluation suite records (behavioral/sts/check_assume_role_duplicate_tag_keys_rejected.py in + * aws/aws-emulator-evaluation-suite, verified against sandboxed AWS accounts). The keys are read as + * {@link #requestTags} reads them. + */ + private static Response refuseDuplicateTagKeys(MultivaluedMap params) { + Set keys = new HashSet<>(); + for (AwsQueryLists.IndexedMember tag : AwsQueryLists.members(params, "Tags", null)) { + String key = params.getFirst(tag.prefix() + ".Key"); + if (key != null && !keys.add(key.toLowerCase(Locale.ROOT))) { + return AwsQueryResponse.error("InvalidParameterValue", + "Duplicate tag keys found. Please note that Tag keys are case insensitive.", + AwsNamespaces.STS, 400); + } + } + return null; + } + /** * The one limit AWS enforces on a session token, which its refusal names as well. AWS "has * replaced the packed policy size and the overall session token size limits with a single @@ -516,7 +583,7 @@ public class StsQueryHandler { */ private Response enforceTrustPolicy(String roleArn, IamRole role, String roleAccountId, MultivaluedMap params, MfaOutcome mfa, - Map inheritedTags) { + Map inheritedTags, String sourceIdentity) { String callerAccount = regionResolver.getAccountId(); IamService.CallerArns caller = iamService.resolveCallerArns(callerAccessKeyId()) .orElseGet(() -> IamService.CallerArns.accountRoot( @@ -564,8 +631,31 @@ public class StsQueryHandler { // tags page has a trust policy reading them: with aws:RequestTag "you can allow the principal to pass the // specified session tags, but only with the specified values", and with aws:TagKeys "pass only session tags // with the specified tag keys". + // A source identity the calling session carries on is the request's sts:SourceIdentity as well, "both the + // aws:SourceIdentity and sts:SourceIdentity keys are present in the request context", the first from the + // caller's own keys. + Optional sourceIdentityKey = sourceIdentityCompanion(); + if (sourceIdentity != null) { + trustContext = IamConditionContextResolver.withCarriedMember(trustContext, "sts:AssumeRole", + SOURCE_IDENTITY, sourceIdentity); + } List>> trustContexts = IamConditionContextResolver.requestContextsOfForm( "sts:AssumeRole", params, trustContext); + // Setting the source identity needs the trust policy's permission too: "permissions for sts:SetSourceIdentity + // are required in both the permissions policy of the principal who is assuming the role and in the role trust + // policy of the target role". It is read before the assume: AWS names sts:SetSourceIdentity when a trust + // statement allowing both is conditioned on another sts:SourceIdentity, where the assume is not allowed either. + if (sourceIdentity != null && sourceIdentityKey.isPresent()) { + String action = sourceIdentityKey.get().action(); + for (Map> context : trustContexts) { + if (!trustPolicyEvaluator.allowsCompanion(action, role.getAssumeRolePolicyDocument(), caller, + callerAccount, context)) { + return AwsQueryResponse.error("AccessDenied", "User: " + callerArn + + " is not authorized to perform: " + action + " on resource: " + roleArn, + AwsNamespaces.STS, 403); + } + } + } for (Map> context : trustContexts) { if (!trustPolicyEvaluator.allows(role.getAssumeRolePolicyDocument(), caller, callerAccount, context)) { return AwsQueryResponse.error("AccessDenied", "User: " + callerArn diff --git a/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java b/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java index 716c2145ee..2fa0c37cd9 100644 --- a/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java +++ b/src/main/java/io/floci/aws/services/iam/model/SessionCredential.java @@ -98,6 +98,15 @@ public class SessionCredential { * transitive tag key, then no tags are passed from this session to any subsequent sessions". */ private List transitiveTagKeys = new ArrayList<>(); + /** + * The global keys this session's requests carry a value it was minted with as, each with the value: a session + * minted with a source identity carries it as {@code aws:SourceIdentity}, the key the generated + * {@code iam-authorized-actions.json} gives the value its operation set. "After a source identity is set, the + * aws:SourceIdentity key is present in all subsequent requests made during the role session", and the value + * "persists when a role is used to assume another role", so a session assumed from this one carries it too. Empty + * for a session minted with none and for one stored before Floci recorded them. + */ + private Map carriedKeys = new LinkedHashMap<>(); public SessionCredential() {} @@ -238,4 +247,12 @@ public class SessionCredential { this.transitiveTagKeys = transitiveTagKeys == null ? new ArrayList<>() : new ArrayList<>(transitiveTagKeys); } + + public Map getCarriedKeys() { + return carriedKeys; + } + + public void setCarriedKeys(Map carriedKeys) { + this.carriedKeys = carriedKeys == null ? new LinkedHashMap<>() : new LinkedHashMap<>(carriedKeys); + } } diff --git a/src/main/resources/aws/iam-authorized-actions.json b/src/main/resources/aws/iam-authorized-actions.json index 239f85be09..36670b9c87 100644 --- a/src/main/resources/aws/iam-authorized-actions.json +++ b/src/main/resources/aws/iam-authorized-actions.json @@ -1801,5 +1801,17 @@ "GetBucketCors": "s3:GetBucketCORS", "PutBucketCors": "s3:PutBucketCORS" } + }, + "companions": { + "sts": { + "AssumeRole": [ + { + "action": "sts:SetSourceIdentity", + "member": "SourceIdentity", + "carried": "aws:SourceIdentity", + "callerPolicyWhenChained": true + } + ] + } } } diff --git a/src/main/resources/aws/request-condition-keys.json b/src/main/resources/aws/request-condition-keys.json index 679bc441eb..6400258e02 100644 --- a/src/main/resources/aws/request-condition-keys.json +++ b/src/main/resources/aws/request-condition-keys.json @@ -108,13 +108,19 @@ ], "sts:AssumeRole": [ "sts:ExternalId", - "sts:RoleSessionName" + "sts:RoleSessionName", + "sts:SourceIdentity" ], "sts:AssumeRoleWithSAML": [ - "sts:RoleSessionName" + "sts:RoleSessionName", + "sts:SourceIdentity" ], "sts:AssumeRoleWithWebIdentity": [ - "sts:RoleSessionName" + "sts:RoleSessionName", + "sts:SourceIdentity" + ], + "sts:SetSourceIdentity": [ + "sts:SourceIdentity" ] }, "members": { @@ -265,6 +271,9 @@ ], "sts:RoleSessionName": [ "RoleSessionName" + ], + "sts:SourceIdentity": [ + "SourceIdentity" ] }, "sts:AssumeRoleWithWebIdentity": { @@ -324,7 +333,8 @@ }, "sts:AssumeRole": { "ExternalId": "externalIdType", - "RoleSessionName": "roleSessionNameType" + "RoleSessionName": "roleSessionNameType", + "SourceIdentity": "sourceIdentityType" }, "sts:AssumeRoleWithWebIdentity": { "RoleSessionName": "roleSessionNameType" diff --git a/src/test/java/io/floci/aws/services/iam/AssumeRoleSourceIdentityIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/AssumeRoleSourceIdentityIntegrationTest.java new file mode 100644 index 0000000000..469ab37d1e --- /dev/null +++ b/src/test/java/io/floci/aws/services/iam/AssumeRoleSourceIdentityIntegrationTest.java @@ -0,0 +1,247 @@ +package io.floci.aws.services.iam; + +import io.floci.aws.testing.AwsTestClients; +import io.floci.aws.testing.EnforcementFixtures; +import io.floci.aws.testing.EnforcementFixtures.UserCredentials; +import io.floci.aws.testing.IamEnforcementProfile; +import io.floci.aws.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; +import software.amazon.awssdk.awscore.exception.AwsServiceException; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.iam.IamClient; +import software.amazon.awssdk.services.sts.StsClient; +import software.amazon.awssdk.services.sts.model.AssumeRoleResponse; +import software.amazon.awssdk.services.sts.model.Credentials; + +import java.net.URI; +import java.util.UUID; + +import static io.floci.aws.testing.EnforcementFixtures.auth; +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * An AssumeRole's source identity, as the IAM user guide's page on it and AWS's own evaluation suite give it: setting + * one needs {@code sts:SetSourceIdentity} of the caller's permissions and of the role's trust policy, the trust + * policy reads it as {@code sts:SourceIdentity}, the response returns it, the session's requests carry it as + * {@code aws:SourceIdentity}, and it "persists when a role is used to assume another role" and "cannot be changed + * during the role session". + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class AssumeRoleSourceIdentityIntegrationTest { + + private static final String ACCOUNT = "444444444444"; + private static final String ASSUME_AND_SET_ACTIONS = "\"sts:AssumeRole\",\"sts:SetSourceIdentity\""; + private static final String ASSUME_AND_SET = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":["sts:AssumeRole","sts:SetSourceIdentity"],"Resource":"*"}]}"""; + private static final String ASSUME_ONLY = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"sts:AssumeRole","Resource":"*"}]}"""; + /** A grant of a probe call only to a request carrying {@code aws:SourceIdentity} as {@code alice}. */ + private static final String LIST_AS_ALICE = """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"iam:ListUsers","Resource":"*", + "Condition":{"StringEquals":{"aws:SourceIdentity":"alice"}}}, + {"Effect":"Allow","Action":["sts:AssumeRole","sts:SetSourceIdentity"],"Resource":"*"}]}"""; + + @TestHTTPResource("/") + URI baseUri; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void aSourceIdentityIsReturnedAndCarriedByTheSessionsRequests() { + String role = role("echo", trustOfTheAccount(ASSUME_AND_SET_ACTIONS), LIST_AS_ALICE); + try (StsClient sts = sts(user("echo", ASSUME_AND_SET))) { + AssumeRoleResponse alice = sts.assumeRole(r -> r.roleArn(role).roleSessionName("session-a") + .sourceIdentity("alice")); + assertEquals("alice", alice.sourceIdentity()); + try (IamClient asAlice = iam(alice.credentials())) { + assertDoesNotThrow(() -> asAlice.listUsers()); + } + AssumeRoleResponse bob = sts.assumeRole(r -> r.roleArn(role).roleSessionName("session-b") + .sourceIdentity("bob")); + try (IamClient asBob = iam(bob.credentials())) { + denied(() -> asBob.listUsers()); + } + AssumeRoleResponse none = sts.assumeRole(r -> r.roleArn(role).roleSessionName("session-n")); + assertNull(none.sourceIdentity()); + try (IamClient withNone = iam(none.credentials())) { + denied(() -> withNone.listUsers()); + } + } + } + + /** + * "To specify a source identity, principals (IAM users and roles) must have permissions to + * sts:SetSourceIdentity", configured "in the role trust policy and in the principal's permissions policy": either + * missing refuses the assume naming that action, and an assume setting none needs neither. + */ + @Test + void settingASourceIdentityNeedsTheCallersAndTheTrustPolicysPermission() { + String trusting = role("trusting", trustOfTheAccount(ASSUME_AND_SET_ACTIONS), + ASSUME_ONLY); + try (StsClient withoutPermission = sts(user("plain", ASSUME_ONLY))) { + AwsServiceException refused = denied(() -> withoutPermission.assumeRole(r -> r.roleArn(trusting) + .roleSessionName("session-s").sourceIdentity("alice"))); + assertTrue(refused.awsErrorDetails().errorMessage() + .contains("is not authorized to perform: sts:SetSourceIdentity"), refused.getMessage()); + assertDoesNotThrow(() -> withoutPermission.assumeRole(r -> r.roleArn(trusting) + .roleSessionName("session-s"))); + } + String assumeOnly = role("assume-only", trustOfTheAccount("\"sts:AssumeRole\""), ASSUME_ONLY); + try (StsClient permitted = sts(user("permitted", ASSUME_AND_SET))) { + AwsServiceException refused = denied(() -> permitted.assumeRole(r -> r.roleArn(assumeOnly) + .roleSessionName("session-s").sourceIdentity("alice"))); + assertTrue(refused.awsErrorDetails().errorMessage() + .endsWith("is not authorized to perform: sts:SetSourceIdentity on resource: " + assumeOnly), + refused.getMessage()); + assertDoesNotThrow(() -> permitted.assumeRole(r -> r.roleArn(assumeOnly).roleSessionName("session-s"))); + } + } + + /** + * A chained assume carries the calling session's source identity on without passing it, the target's trust + * policy reading it as {@code sts:SourceIdentity}. Passing another is refused with AWS's ValidationError, passing + * the same one is not, and a session whose value the trust policy's condition does not match is refused naming + * {@code sts:SetSourceIdentity}, as AWS's evaluation suite records. The permission is "required in both the + * permissions policy of the principal who is assuming the role and in the role trust policy of the target role". + */ + @Test + void aChainedSessionCarriesItsSourceIdentityOnAndCannotChangeIt() { + String first = role("first", trustOfTheAccount(ASSUME_AND_SET_ACTIONS), + ASSUME_AND_SET); + String firstWithoutPermission = role("first-plain", + trustOfTheAccount(ASSUME_AND_SET_ACTIONS), ASSUME_ONLY); + String second = role("second", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"%s"},"Action":["sts:AssumeRole","sts:SetSourceIdentity"], + "Condition":{"StringEquals":{"sts:SourceIdentity":"alice"}}}]}""".formatted(first), LIST_AS_ALICE); + // A trust policy naming the account, so the caller's own permissions decide what it may do, and one naming the + // calling role itself, which grants it both actions and still leaves the caller's own permissions to decide. + String accountTrusting = role("chain-account", trustOfTheAccount(ASSUME_AND_SET_ACTIONS), ASSUME_ONLY); + String namesTheCaller = role("chain-names", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"%s"},"Action":["sts:AssumeRole","sts:SetSourceIdentity"]}]}""" + .formatted(firstWithoutPermission), ASSUME_ONLY); + String assumeOnly = role("chain-assume-only", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"%s"},"Action":"sts:AssumeRole"}]}""".formatted(first), ASSUME_ONLY); + try (StsClient sts = sts(user("chain", ASSUME_AND_SET))) { + Credentials asAlice = sts.assumeRole(r -> r.roleArn(first).roleSessionName("session-a") + .sourceIdentity("alice")) + .credentials(); + try (StsClient alice = sessionSts(asAlice)) { + AssumeRoleResponse chained = alice.assumeRole(r -> r.roleArn(second).roleSessionName("session-c")); + assertEquals("alice", chained.sourceIdentity()); + try (IamClient asChained = iam(chained.credentials())) { + assertDoesNotThrow(() -> asChained.listUsers()); + } + assertEquals("alice", alice.assumeRole(r -> r.roleArn(second).roleSessionName("same") + .sourceIdentity("alice")).sourceIdentity()); + AwsServiceException changed = assertThrows(AwsServiceException.class, () -> alice.assumeRole(r -> r + .roleArn(second).roleSessionName("other").sourceIdentity("bob"))); + assertEquals(400, changed.statusCode()); + assertEquals("ValidationError", changed.awsErrorDetails().errorCode()); + assertEquals("The source identity is already set for this assume role session", + changed.awsErrorDetails().errorMessage()); + denied(() -> alice.assumeRole(r -> r.roleArn(assumeOnly).roleSessionName("session-t"))); + } + Credentials asBob = sts.assumeRole(r -> r.roleArn(first).roleSessionName("session-b").sourceIdentity("bob")) + .credentials(); + try (StsClient bob = sessionSts(asBob)) { + AwsServiceException refused = denied(() -> bob.assumeRole(r -> r.roleArn(second) + .roleSessionName("session-c"))); + assertTrue(refused.awsErrorDetails().errorMessage() + .endsWith("is not authorized to perform: sts:SetSourceIdentity on resource: " + second), + refused.getMessage()); + } + Credentials withoutPermission = sts.assumeRole(r -> r.roleArn(firstWithoutPermission) + .roleSessionName("session-p").sourceIdentity("alice")).credentials(); + try (StsClient plain = sessionSts(withoutPermission)) { + for (String target : new String[] {accountTrusting, namesTheCaller}) { + AwsServiceException refused = denied(() -> plain.assumeRole(r -> r.roleArn(target) + .roleSessionName("session-c"))); + assertTrue(refused.awsErrorDetails().errorMessage() + .contains("is not authorized to perform: sts:SetSourceIdentity"), refused.getMessage()); + } + } + } + } + + /** A source identity outside botocore's pattern is refused with AWS's ValidationError, as is one naming a colon. */ + @Test + void aSourceIdentityOutsideItsPatternIsRefused() { + String role = role("pattern", trustOfTheAccount(ASSUME_AND_SET_ACTIONS), ASSUME_ONLY); + for (String value : new String[] {"bad identity", "aws:reserved"}) { + given().contentType("application/x-www-form-urlencoded") + .formParam("Action", "AssumeRole").formParam("Version", "2011-06-15") + .formParam("RoleArn", role).formParam("RoleSessionName", "session-s") + .formParam("SourceIdentity", value) + .header("Authorization", auth(ACCOUNT, "sts")) + .when().post("/").then().statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", equalTo("1 validation error detected: Value '" + value + + "' at 'sourceIdentity' failed to satisfy constraint: Member must satisfy regular " + + "expression pattern: [\\w+=,.@-]*")); + } + } + + private String role(String name, String trust, String policy) { + return EnforcementFixtures.createRole(cleanup, baseUri.getPort(), ACCOUNT, "/", + "source-" + name + "-" + suffix(), trust, policy); + } + + private static String trustOfTheAccount(String actions) { + return """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":[%s]}]}""".formatted(ACCOUNT, actions); + } + + private UserCredentials user(String name, String policy) { + String userName = "source-" + name + "-" + suffix(); + UserCredentials keys = EnforcementFixtures.createUser(cleanup, baseUri.getPort(), auth(ACCOUNT, "iam"), + userName); + EnforcementFixtures.putUserPolicy(baseUri.getPort(), auth(ACCOUNT, "iam"), userName, "p", policy); + return keys; + } + + private StsClient sts(UserCredentials keys) { + return AwsTestClients.create(StsClient.builder(), keys.accessKeyId(), keys.secretAccessKey(), + Region.US_EAST_1, baseUri); + } + + private StsClient sessionSts(Credentials session) { + return AwsTestClients.create(StsClient.builder(), sessionCredentials(session), Region.US_EAST_1, baseUri); + } + + private IamClient iam(Credentials session) { + return AwsTestClients.create(IamClient.builder(), sessionCredentials(session), Region.US_EAST_1, baseUri); + } + + private static AwsSessionCredentials sessionCredentials(Credentials session) { + return AwsSessionCredentials.create(session.accessKeyId(), session.secretAccessKey(), session.sessionToken()); + } + + private static AwsServiceException denied(Runnable call) { + AwsServiceException error = assertThrows(AwsServiceException.class, call::run); + assertEquals(403, error.statusCode()); + assertEquals("AccessDenied", error.awsErrorDetails().errorCode()); + return error; + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } +} diff --git a/src/test/java/io/floci/aws/services/iam/AssumeRoleTrustConditionsIntegrationTest.java b/src/test/java/io/floci/aws/services/iam/AssumeRoleTrustConditionsIntegrationTest.java index 6c88da2807..e1fecc5a93 100644 --- a/src/test/java/io/floci/aws/services/iam/AssumeRoleTrustConditionsIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/iam/AssumeRoleTrustConditionsIntegrationTest.java @@ -226,8 +226,8 @@ class AssumeRoleTrustConditionsIntegrationTest { /** * The trust policy is checked once for each set of tags the request carries as a reading of its list gives it, - * as the caller's own policies are: past a gap in the numbering, and with each value of a key sent twice, so a - * Deny on a tag holds whatever gaps or order the list is sent in. + * as the caller's own policies are, past a gap in the numbering, so a Deny on a tag holds whatever gaps the list + * is sent with. */ @Test void aDenyOnASessionTagReadsEveryTagTheSessionTakes() { @@ -240,11 +240,9 @@ class AssumeRoleTrustConditionsIntegrationTest { "Action":["sts:AssumeRole","sts:TagSession"]},%3$s]}""".formatted(TRUSTED_ACCOUNT, OTHER_ACCOUNT, deniesRed.formatted(TRUSTED_ACCOUNT))); String gap = tag(1, "Team", "a") + tag(3, "Project", "red"); - String outOfOrder = tag(2, "Project", "red") + tag(1, "Project", "blue"); assumeRoleWithTags(TRUSTED_ACCOUNT, role, tag(1, "Project", "blue")).then().statusCode(200); assertTaggingDenied(assumeRoleWithTags(TRUSTED_ACCOUNT, role, gap), role); - assertTaggingDenied(assumeRoleWithTags(TRUSTED_ACCOUNT, role, outOfOrder), role); // The caller's own Deny, which the enforcement filter reads before the trust policy. String user = "trust-tags-" + UUID.randomUUID().toString().substring(0, 8); @@ -257,10 +255,30 @@ class AssumeRoleTrustConditionsIntegrationTest { "Condition":{"StringEquals":{"aws:RequestTag/Project":"red"}}}]}""") .header("Authorization", auth(OTHER_ACCOUNT, "iam")).when().post("/").then().statusCode(200); assumeRoleWithTags(accessKeyId, role, tag(1, "Project", "blue")).then().statusCode(200); - for (String tags : new String[] {gap, outOfOrder}) { - assumeRoleWithTags(accessKeyId, role, tags).then().statusCode(403) - .body(containsString("AccessDenied")) - .body(containsString("is not authorized to perform: sts:TagSession")); + assumeRoleWithTags(accessKeyId, role, gap).then().statusCode(403) + .body(containsString("AccessDenied")) + .body(containsString("is not authorized to perform: sts:TagSession")); + } + + /** + * An AssumeRole naming a session tag key twice, in the same case or not, in order or not, is refused as AWS + * refuses it, with {@code InvalidParameterValue}: "Duplicate tag keys found. Please note that Tag keys are case + * insensitive." + */ + @Test + void aSessionTagKeyNamedTwiceIsRefused() { + String role = createRole(""" + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Principal":{"AWS":"arn:aws:iam::%s:root"},"Action":["sts:AssumeRole","sts:TagSession"]}]}""" + .formatted(TRUSTED_ACCOUNT)); + + assumeRoleWithTags(TRUSTED_ACCOUNT, role, tag(1, "team", "a")).then().statusCode(200); + for (String tags : new String[] {tag(1, "team", "a") + tag(2, "team", "b"), + tag(2, "Project", "red") + tag(1, "Project", "blue"), tag(1, "Team", "a") + tag(2, "team", "a")}) { + assumeRoleWithTags(TRUSTED_ACCOUNT, role, tags).then().statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("Duplicate tag keys found. Please note that Tag keys are case " + + "insensitive.")); } } diff --git a/tools/aws/fetch_sts_source_identity.py b/tools/aws/fetch_sts_source_identity.py new file mode 100644 index 0000000000..a9103388e0 --- /dev/null +++ b/tools/aws/fetch_sts_source_identity.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Vendor what the IAM user guide says about setting a source identity into tools/aws/sources/sts-source-identity.json, +a source of the request condition key table and the authorized actions table. + +AWS's Service Reference gives AssumeRole the key `sts:SourceIdentity` and lists `sts:SetSourceIdentity` among the +actions the operation is authorized by, beside `sts:AssumeRole` and `sts:TagSession`, without saying which request +member carries the key or when the action is needed, and botocore does not say either. The IAM user guide's page on +source identity does: + + To pass source identity while assuming a role, use the -–source-identity AWS CLI option or the SourceIdentity + AWS API parameter. + + To specify a source identity, principals (IAM users and roles) must have permissions to sts:SetSourceIdentity. + + When you assume a role with another role, called role chaining, permissions for sts:SetSourceIdentity are + required in both the permissions policy of the principal who is assuming the role and in the role trust policy + of the target role. + + https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html + +This script copies those sentences as they stand, with what each names: the operation of each "Using source identity +with " section that names the API parameter carrying the value, the action setting a source identity needs, +the key a request setting one carries and the key the session's later requests carry, and the sentences saying the +value persists through a chain. A section naming no API parameter is not read here. Nothing in the output is written +by hand; regen_request_condition_keys.py and regen_iam_authorized_actions.py read it. + +Run from anywhere in the repo: + python3 tools/aws/fetch_sts_source_identity.py # rewrite the vendored file from the page + python3 tools/aws/fetch_sts_source_identity.py --verify # online: the file still says what the page does +""" +from __future__ import annotations + +import argparse +import html +import json +import re +import sys +import urllib.request +from datetime import datetime, timezone +from pathlib import Path + +PAGE = "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html" +REPO_ROOT = Path(__file__).resolve().parents[2] +OUTPUT = REPO_ROOT / "tools/aws/sources/sts-source-identity.json" + +OPERATION_HEADING_RE = re.compile(r"^Using source identity with (?P[A-Z][A-Za-z]+)$") +MEMBER_RE = re.compile(r"\bTo pass source identity while assuming a role, use the \S+ AWS CLI option or the " + r"(?P[A-Z][A-Za-z]+) AWS API parameter\.") +PERMISSION_RE = re.compile(r"\bTo specify a source identity, principals \(IAM users and roles\) must have permissions " + r"to (?Psts:[A-Za-z]+)\.") +CHAINING_RE = re.compile(r"\bWhen you assume a role with another role, called role chaining, permissions for " + r"(?Psts:[A-Za-z]+) are required in both the permissions policy of the principal " + r"who is assuming the role and in the role trust policy of the target role\.") +KEYS_RE = re.compile(r"\bWhen an identity sets a source identity, the (?Psts:[A-Za-z]+) key is present in the " + r"request\. For subsequent actions taken during the role session, the " + r"(?Paws:[A-Za-z]+) key is present in the request\.") +PERSISTS_RE = re.compile(r"\bThe value that is set persists when a role is used to assume another role[^.]*\. " + r"The value that is set cannot be changed during the role session\.") +CHAINED_KEYS_RE = re.compile(r"\bTherefore, both the (?Paws:[A-Za-z]+) and (?Psts:[A-Za-z]+) keys " + r"are present in the request context\.") + + +def text(fragment: str) -> str: + """A fragment of a page as text, spaces collapsed, and none left before a mark an inline tag ends ahead of.""" + collapsed = re.sub(r"\s+", " ", html.unescape(re.sub(r"<[^>]+>", " ", fragment))).strip() + return re.sub(r" (?=[.,;)])", "", re.sub(r"\( ", "(", collapsed)) + + +def body(page: str) -> str: + """The page's own content, its navigation left out.""" + match = re.search(r'

(?P.*?)(?:
dict[str, str]: + """Each second-level section of the page as text, under its heading.""" + parts = re.split(r"]*>(.*?)", body(page), flags=re.S) + return {text(parts[i]): text(parts[i + 1]) for i in range(1, len(parts) - 1, 2)} + + +def _sentence(pattern: re.Pattern, where: str, what: str) -> re.Match: + found = pattern.search(where) + if found is None: + raise ValueError(f"{PAGE} no longer says {what}: its layout or its wording changed") + return found + + +def build(fetch) -> dict: + page = fetch(PAGE) + by_heading = sections(page) + whole = text(body(page)) + keys = [] + for heading, section in by_heading.items(): + operation = OPERATION_HEADING_RE.match(heading) + member = MEMBER_RE.search(section) if operation else None + if member is None: + continue + keys.append({"operation": operation.group("operation"), "member": member.group("member"), + "row": member.group(0)}) + if not keys: + raise ValueError(f"{PAGE} names no API parameter a source identity is passed in: its layout changed") + permission = _sentence(PERMISSION_RE, whole, "which action specifying a source identity needs") + chaining = _sentence(CHAINING_RE, whole, "which action a chained assume of a source identity needs") + if chaining.group("action") != permission.group("action"): + raise ValueError(f"{PAGE} names {permission.group('action')} for setting a source identity and " + f"{chaining.group('action')} for chaining one") + named = _sentence(KEYS_RE, whole, "which keys a source identity is present in the request as") + chained = _sentence(CHAINED_KEYS_RE, whole, "which keys a chained request carries a source identity as") + if (chained.group("request"), chained.group("session")) != (named.group("request"), named.group("session")): + raise ValueError(f"{PAGE} names other keys for a chained request than for one setting a source identity") + persists = _sentence(PERSISTS_RE, whole, "that a source identity persists through a chain") + for entry in keys: + entry["key"] = named.group("request") + return { + "_source": { + "page": PAGE, + "fetcher": str(Path(__file__).resolve().relative_to(REPO_ROOT)), + "retrieved": datetime.now(timezone.utc).strftime("%Y-%m-%d"), + "note": "The page's sentences on setting a source identity, copied as they stand, with what each names: " + "the API parameter each operation's section passes it in, the action setting one needs and its " + "chained form, the keys a request carries it as, and its persistence through a chain.", + }, + "keys": sorted(keys, key=lambda entry: entry["operation"]), + "permission": {"action": permission.group("action"), "sentence": permission.group(0), + "chaining": chaining.group(0)}, + "sessionKey": {"key": named.group("session"), "sentence": named.group(0), "chained": chained.group(0)}, + "persists": persists.group(0), + } + + +def fetch_url(url: str) -> str: + request = urllib.request.Request(url, headers={"User-Agent": "floci-tools"}) + with urllib.request.urlopen(request, timeout=60) as response: + return response.read().decode("utf-8") + + +def stale(vendored: dict, page: str) -> bool: + """Whether the page now gives something other than the vendored file, its date aside.""" + built = build(lambda url: page) + return {key: value for key, value in vendored.items() if key != "_source"} != { + key: value for key, value in built.items() if key != "_source"} + + +def main(argv: list[str] | None = None, fetch=fetch_url) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--verify", action="store_true", help="online: the vendored file matches the page") + args = parser.parse_args(argv) + try: + page = fetch(PAGE) + except OSError as e: + print(f"error: could not read the IAM user guide's source identity page ({e})", file=sys.stderr) + return 2 + if args.verify: + vendored = json.loads(OUTPUT.read_text(encoding="utf-8")) + if stale(vendored, page): + print(f"error: {OUTPUT.relative_to(REPO_ROOT)} no longer says what the IAM user guide does: run " + f"tools/aws/fetch_sts_source_identity.py and then make request-condition-keys-sync and " + f"iam-authorized-actions-sync", file=sys.stderr) + return 1 + print(f"{OUTPUT.relative_to(REPO_ROOT)} matches the IAM user guide") + return 0 + built = build(lambda url: page) + OUTPUT.write_text(json.dumps(built, indent=2) + "\n", encoding="utf-8") + print(f"wrote {OUTPUT.relative_to(REPO_ROOT)} ({len(built['keys'])} operations)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/aws/regen_iam_authorized_actions.py b/tools/aws/regen_iam_authorized_actions.py index e471d21e2d..4d31d305d9 100644 --- a/tools/aws/regen_iam_authorized_actions.py +++ b/tools/aws/regen_iam_authorized_actions.py @@ -66,6 +66,16 @@ is the namesake client's (`namesake_by_model`: S3's GetBucketLifecycleConfigurat `MEASURED_VERSIONED` give what the Service Authorization Reference's actions table does, quoted with its link. +Where the reference lists, among an operation's actions, one the operation needs only when its request sets a value, +the IAM user guide's page on source identity says when, copied unchanged into tools/aws/sources/sts-source-identity.json +by tools/aws/fetch_sts_source_identity.py (`companions`). AssumeRole lists `sts:SetSourceIdentity`, which "to specify a +source identity, principals (IAM users and roles) must have permissions to": the value passed in the request member the +page names for the operation, `SourceIdentity`, a member of its request in botocore, or carried by a chained caller as +the key its session's later requests carry, `aws:SourceIdentity`. And "when you assume a role with another role, called +role chaining, permissions for sts:SetSourceIdentity are required in both the permissions policy of the principal who is +assuming the role and in the role trust policy of the target role", so a chained caller's own permissions must allow it +whatever the target's trust policy grants (`callerPolicyWhenChained`). + The file also lists, for each credential scope whose REST routes `rest-routes.json` reads, the actions of that namespace the reference gives no resource type, from its `Actions`. A REST request `IamActionRegistry` maps is checked as the operation whose route it matches only when that operation's @@ -130,6 +140,9 @@ OUTPUT = REPO_ROOT / "src/main/resources/aws/iam-authorized-actions.json" ROUTES = REPO_ROOT / "src/main/resources/aws/rest-routes.json" # The S3 user guide's required actions of each S3 operation, as tools/aws/fetch_s3_required_actions.py copies them. S3_REQUIRED = REPO_ROOT / "tools/aws/sources/s3-required-actions.json" +# The IAM user guide's page on source identity, as tools/aws/fetch_sts_source_identity.py copies it. +SOURCE_IDENTITY = REPO_ROOT / "tools/aws/sources/sts-source-identity.json" +CARRIED_KEY_RE = re.compile(r"^aws:[A-Za-z]+$") LEVEL_RE = re.compile(r"^([A-Z][A-Za-z0-9]+)(?: \((Bucket|Account)-level\))?$") SPECIFYING_RE = re.compile(r"\bspecifying (\w+) in the request") _S3_ACTIONS_TABLE = "https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazons3.html" @@ -551,6 +564,53 @@ def authorized_by_method(documents: list[dict], methods: dict[str, dict[str, lis return found +def load_source_identity(source: Path = SOURCE_IDENTITY) -> dict | None: + """The vendored IAM user guide page on source identity, none when the file is missing.""" + return json.loads(source.read_text(encoding="utf-8")) if source.exists() else None + + +def request_members(namespace: str) -> dict[str, set[str]]: + """The members of each operation's request in botocore's model of the namespace.""" + data, _ = resolve_botocore_data(None) + model = load_model(latest_model_dir(data, namespace)) + return {name: set(model["shapes"][operation["input"]["shape"]].get("members", {})) + for name, operation in model["operations"].items() if "input" in operation} + + +def companions(documents: list[dict], page: dict | None, + requests: dict[str, dict[str, set[str]]] | None = None) -> dict[str, dict[str, list[dict]]]: + """The actions an operation needs beside its own only when it sets a value, from the IAM user guide's page on source + identity (`page`, `load_source_identity`): for each operation the page names the request member passing the value + in, the action the page says setting one needs, where the reference lists it among the operation's actions, with + the member and the key a chained caller carries the value as, and whether a chained caller's own permissions must + allow it, which the page's sentence on role chaining says. The member must be one of the operation's request in + botocore (`requests` by namespace, `request_members` unless given).""" + if not page: + return {} + action = page["permission"]["action"] + namespace = action.split(":", 1)[0] + found = {} + for document in documents: + if document.get("Name") != namespace: + continue + operations = {operation.get("Name"): operation for operation in document.get("Operations") or []} + for entry in page["keys"]: + operation = operations.get(entry["operation"]) + if operation is None or action not in {f"{service}:{name}" for service, name + in _authorized_actions(namespace, operation)}: + continue + members = (requests or {}).get(namespace) + if members is None: + members = request_members(namespace) + if entry["member"] not in members.get(entry["operation"], set()): + raise ValueError(f"botocore gives {namespace}:{entry['operation']} no request member " + f"{entry['member']}, which the source identity page passes the value in") + found.setdefault(namespace, {})[entry["operation"]] = [ + {"action": action, "member": entry["member"], "carried": page["sessionKey"]["key"], + "callerPolicyWhenChained": bool(page["permission"].get("chaining"))}] + return {namespace: dict(sorted(operations.items())) for namespace, operations in sorted(found.items())} + + def vendored_sections(documents: list[dict], page: dict | None, models: dict | None, query: dict[str, list[str]] | None, renamed: dict[str, dict[str, str]]) -> dict[str, dict]: """The `authorizedByModel`, `versioned` and `spellings` sections, given the operations `authorized_actions` renames @@ -567,9 +627,12 @@ def vendored_sections(documents: list[dict], page: dict | None, models: dict | N def build(documents: list[dict], provenance: str, routed: list[str], methods: dict[str, dict[str, list[str]]] | None = None, page: dict | None = None, - models: dict | None = None, query: dict[str, list[str]] | None = None) -> dict: + models: dict | None = None, query: dict[str, list[str]] | None = None, + source_identity: dict | None = None, requests: dict[str, dict[str, set[str]]] | None = None) -> dict: """The vendored document; `page` is the S3 user guide's operations (`load_s3_required`), `models` the vendored - routes' models, `query` botocore's S3 query parameters (`s3_query_parameters`, unless given).""" + routes' models, `query` botocore's S3 query parameters (`s3_query_parameters`, unless given), `source_identity` + the IAM user guide's page on source identity (`load_source_identity`) and `requests` botocore's request members + (`request_members`, unless given).""" if query is None and any(document.get("Name") == "s3" for document in documents): query = s3_query_parameters() renamed = authorized_actions(documents, page, models, query) @@ -584,6 +647,7 @@ def build(documents: list[dict], provenance: str, routed: list[str], "actionsWithoutResourceTypes": actions_without_resource_types(documents, routed), "authorizedByMethod": authorized_by_method(documents, methods or {}, renamed), **vendored_sections(documents, page, models, query, renamed), + "companions": companions(documents, source_identity, requests), } @@ -628,7 +692,7 @@ def validate(document: dict, routed: list[str], methods: dict[str, dict[str, lis def _section_problems(document: dict) -> list[str]: - """Problems with the shape of `authorizedByModel`, `versioned` and `spellings`.""" + """Problems with the shape of `authorizedByModel`, `versioned`, `spellings` and `companions`.""" problems = [] def action_of(namespace: str, action: object) -> bool: prefix, _, name = action.partition(":") if isinstance(action, str) else ("", "", "") @@ -650,6 +714,17 @@ def _section_problems(document: dict) -> list[str]: if not action_of(namespace, action) or action.split(":", 1)[1].lower() != operation.lower() \ or action.split(":", 1)[1] == operation: problems.append(f"spellings {namespace}:{operation} gives {action!r}, not its name spelled otherwise") + for namespace, operations in (document.get("companions") or {}).items(): + for operation, needed in (operations.items() if isinstance(operations, dict) else []): + for companion in (needed if isinstance(needed, list) else [None]): + if not isinstance(companion, dict) \ + or set(companion) != {"action", "member", "carried", "callerPolicyWhenChained"} \ + or not action_of(namespace, companion.get("action")) \ + or not NAME_RE.match(str(companion.get("member"))) \ + or not CARRIED_KEY_RE.match(str(companion.get("carried"))) \ + or not isinstance(companion.get("callerPolicyWhenChained"), bool): + problems.append(f"companions {namespace}:{operation} is not an action of {namespace}, a request " + f"member, a global key and whether a chained caller's policy must allow it") return problems @@ -830,6 +905,15 @@ def main(argv: list[str] | None = None) -> int: f"{fetch_s3_required_actions.PAGE} does (run tools/aws/fetch_s3_required_actions.py)", file=sys.stderr) return 1 + source_identity = load_source_identity() + if args.source_dir is None and source_identity is not None: + import fetch_sts_source_identity + if fetch_sts_source_identity.stale(source_identity, fetch_sts_source_identity.fetch_url( + fetch_sts_source_identity.PAGE)): + print(f"error: {SOURCE_IDENTITY.relative_to(REPO_ROOT)} no longer says what " + f"{fetch_sts_source_identity.PAGE} does (run tools/aws/fetch_sts_source_identity.py)", + file=sys.stderr) + return 1 models = _routes(args.routes)["models"] query = s3_query_parameters() upstream = authorized_actions(documents, page, models, query) @@ -843,7 +927,9 @@ def main(argv: list[str] | None = None) -> int: print(f"error: could not read the Service Reference ({e})", file=sys.stderr) return 2 untrue, added = verify_against(vendored, upstream) - for section, value in vendored_sections(documents, page, models, query, upstream).items(): + sections = {**vendored_sections(documents, page, models, query, upstream), + "companions": companions(documents, source_identity)} + for section, value in sections.items(): if vendored_document.get(section, {}) != value: untrue.append(f"{section} differs from what AWS gives: expected {json.dumps(value)}") untrue_unscoped, added_unscoped = verify_unscoped_against(unscoped, upstream_unscoped) @@ -872,7 +958,8 @@ def main(argv: list[str] | None = None) -> int: routes = _routes(args.routes) routed = routed_namespaces(routes) methods = route_methods(routes) - document = build(documents, provenance, routed, methods, load_s3_required(), routes["models"]) + document = build(documents, provenance, routed, methods, load_s3_required(), routes["models"], + source_identity=load_source_identity()) except (OSError, ValueError) as e: print(f"error: could not read the Service Reference ({e})", file=sys.stderr) return 2 diff --git a/tools/aws/regen_request_condition_keys.py b/tools/aws/regen_request_condition_keys.py index 275eb25975..801d8f0482 100644 --- a/tools/aws/regen_request_condition_keys.py +++ b/tools/aws/regen_request_condition_keys.py @@ -38,9 +38,10 @@ it. `SERVICES` names, for each namespace, the keys read and where: - `sts`: an AssumeRole request is checked with the session name and external ID it passes as `sts:RoleSessionName` and `sts:ExternalId`, so the caller's identity-based policy can require them as a trust policy can; an AssumeRole without `ExternalId` names none. AssumeRoleWithWebIdentity carries - `RoleSessionName` too, but is not signed, so no identity-based policy is evaluated for it. - `sts:SourceIdentity`, `sts:TransitiveTagKeys` and the session tags are not read: Floci does not model source - identity or session tags. + `RoleSessionName` too, but is not signed, so no identity-based policy is evaluated for it. An AssumeRole + request is checked with the source identity it passes as `sts:SourceIdentity`, as the IAM user guide gives it + (`CONDITION_SOURCES`). `sts:TransitiveTagKeys` and the session tags are not read here; the tags are the + tag-on-create table's. The table comes from two sources: @@ -87,6 +88,7 @@ from pathlib import Path import fetch_eks_conditions import fetch_eventbridge_conditions import fetch_route53_conditions +import fetch_sts_source_identity from regen_dynamodb_condition_keys import member_paths from regen_iam_tag_on_create import _condition_keys, _resource_keys from regen_partitions import resolve_botocore_data @@ -172,8 +174,11 @@ SERVICES = { # page and `vendored_service` reads it. And granted for Route 53: its developer guide's table of condition keys gives # `route53:VPCs` as "a list of VPCs in the request of" the six VPC association operations, "in the format of # VPCId=,VPCRegion="; tools/aws/fetch_route53_conditions.py vendors that page and `vendored_service` -# reads it. Each file is written by its own script from the page, unchanged, and nothing about an operation is stated -# here. +# reads it. And granted for STS: the IAM user guide's page on source identity says "to pass source identity while +# assuming a role, use the -–source-identity AWS CLI option or the SourceIdentity AWS API parameter", and "when an +# identity sets a source identity, the sts:SourceIdentity key is present in the request"; +# tools/aws/fetch_sts_source_identity.py vendors that page and `vendored_service` reads it. Each file is written by its +# own script from the page, unchanged, and nothing about an operation is stated here. CONDITION_SOURCES: dict[str, dict] = { "eks": {"model": "eks", "source": REPO_ROOT / "tools/aws/sources/eks-condition-keys.json", "fetcher": fetch_eks_conditions}, @@ -181,6 +186,8 @@ CONDITION_SOURCES: dict[str, dict] = { "fetcher": fetch_eventbridge_conditions}, "route53": {"model": "route53", "source": REPO_ROOT / "tools/aws/sources/route53-condition-keys.json", "fetcher": fetch_route53_conditions}, + "sts": {"model": "sts", "source": REPO_ROOT / "tools/aws/sources/sts-source-identity.json", + "fetcher": fetch_sts_source_identity}, } diff --git a/tools/aws/sources/sts-source-identity.json b/tools/aws/sources/sts-source-identity.json new file mode 100644 index 0000000000..2cdaa7d2ce --- /dev/null +++ b/tools/aws/sources/sts-source-identity.json @@ -0,0 +1,27 @@ +{ + "_source": { + "page": "https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html", + "fetcher": "tools/aws/fetch_sts_source_identity.py", + "retrieved": "2026-11-28", + "note": "The page's sentences on setting a source identity, copied as they stand, with what each names: the API parameter each operation's section passes it in, the action setting one needs and its chained form, the keys a request carries it as, and its persistence through a chain." + }, + "keys": [ + { + "operation": "AssumeRole", + "member": "SourceIdentity", + "row": "To pass source identity while assuming a role, use the -\u2013source-identity AWS CLI option or the SourceIdentity AWS API parameter.", + "key": "sts:SourceIdentity" + } + ], + "permission": { + "action": "sts:SetSourceIdentity", + "sentence": "To specify a source identity, principals (IAM users and roles) must have permissions to sts:SetSourceIdentity.", + "chaining": "When you assume a role with another role, called role chaining, permissions for sts:SetSourceIdentity are required in both the permissions policy of the principal who is assuming the role and in the role trust policy of the target role." + }, + "sessionKey": { + "key": "aws:SourceIdentity", + "sentence": "When an identity sets a source identity, the sts:SourceIdentity key is present in the request. For subsequent actions taken during the role session, the aws:SourceIdentity key is present in the request.", + "chained": "Therefore, both the aws:SourceIdentity and sts:SourceIdentity keys are present in the request context." + }, + "persists": "The value that is set persists when a role is used to assume another role through the AWS CLI or AWS API, known as role chaining. The value that is set cannot be changed during the role session." +} diff --git a/tools/aws/test_fetch_sts_source_identity.py b/tools/aws/test_fetch_sts_source_identity.py new file mode 100644 index 0000000000..e6f35f3c64 --- /dev/null +++ b/tools/aws/test_fetch_sts_source_identity.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Tests for fetch_sts_source_identity.py, on a page in the IAM user guide's markup.""" +from __future__ import annotations + +import pytest + +import fetch_sts_source_identity as f + +PERMISSIONS = ("

Permissions required to set source identity

  • To specify a source identity, " + "principals (IAM users and roles) must have permissions to sts:SetSourceIdentity. As the " + "administrator, you can configure this.

  • When you assume a role with another role, called " + "role chaining, permissions for sts:SetSourceIdentity are required in both the " + "permissions policy of the principal who is assuming the role and in the role trust policy of the " + "target role. Otherwise, the assume role operation will fail.

") +THINGS = ("

Things to know about source identity

The value that is set persists when a role is used to " + "assume another role through the AWS CLI or AWS API, known as role chaining. The value that is set " + "cannot be changed during the role session.

When an identity sets a source identity, the " + "sts:SourceIdentity key is present in the request. For subsequent actions taken during the " + "role session, the aws:SourceIdentity key is present in the request.

") +ASSUME_ROLE = ("

Using source identity with AssumeRole

To pass source identity while assuming a role, use " + "the -–source-identity AWS CLI option or the SourceIdentity AWS API " + "parameter.

") +SAML = "

Using source identity with AssumeRoleWithSAML

Set a SAML attribute.

" +CHAINED = ("

Control access using source identity information

Therefore, both the " + "aws:SourceIdentity and sts:SourceIdentity keys are present in the request " + "context.

") + + +def page(*parts: str) -> str: + sections = parts or (THINGS, PERMISSIONS, ASSUME_ROLE, SAML, CHAINED) + return f'

Monitor

{"".join(sections)}
' + + +def test_each_operation_naming_its_parameter_is_read_with_the_key_it_carries(): + built = f.build(lambda url: page()) + # A section naming no API parameter, as the SAML one, is not read here. + assert built["keys"] == [{"operation": "AssumeRole", "member": "SourceIdentity", "key": "sts:SourceIdentity", + "row": "To pass source identity while assuming a role, use the -–source-identity AWS " + "CLI option or the SourceIdentity AWS API parameter."}] + assert built["permission"]["action"] == "sts:SetSourceIdentity" + assert built["permission"]["chaining"].startswith("When you assume a role with another role, called role chaining") + assert built["sessionKey"]["key"] == "aws:SourceIdentity" + assert built["persists"].endswith("The value that is set cannot be changed during the role session.") + + +def test_a_page_whose_layout_or_wording_changed_is_refused(): + with pytest.raises(ValueError, match="names no API parameter"): + f.build(lambda url: page(THINGS, PERMISSIONS, SAML, CHAINED)) + with pytest.raises(ValueError, match="which action specifying a source identity needs"): + f.build(lambda url: page(THINGS, ASSUME_ROLE, CHAINED)) + with pytest.raises(ValueError, match="names sts:SetSourceIdentity for setting"): + f.build(lambda url: page(THINGS, PERMISSIONS.replace("permissions for sts:SetSourceIdentity", + "permissions for sts:SetOther"), + ASSUME_ROLE, CHAINED)) + with pytest.raises(ValueError, match="other keys for a chained request"): + f.build(lambda url: page(THINGS, PERMISSIONS, ASSUME_ROLE, + CHAINED.replace("aws:SourceIdentity", "aws:Other"))) + + +def test_the_file_is_stale_when_the_page_says_something_else(): + vendored = f.build(lambda url: page()) + assert not f.stale(vendored, page()) + assert f.stale(vendored, page(THINGS, PERMISSIONS, ASSUME_ROLE.replace("SourceIdentity", "Identity"), + CHAINED)) diff --git a/tools/aws/test_regen_iam_authorized_actions.py b/tools/aws/test_regen_iam_authorized_actions.py index b00745be0a..161141ba06 100644 --- a/tools/aws/test_regen_iam_authorized_actions.py +++ b/tools/aws/test_regen_iam_authorized_actions.py @@ -724,3 +724,55 @@ def test_the_new_sections_are_built_only_for_references_with_s3_and_validated(): assert any("authorizedByModel" in problem for problem in problems) assert any("versioned" in problem for problem in problems) assert any("spellings" in problem for problem in problems) + + +# --------------------------------------------------------------------------- # +# companions: an action an operation needs only when it sets a value +# --------------------------------------------------------------------------- # +SOURCE_IDENTITY = { + "keys": [{"operation": "AssumeRole", "member": "SourceIdentity", "key": "sts:SourceIdentity"}], + "permission": {"action": "sts:SetSourceIdentity", "chaining": "When you assume a role with another role, ..."}, + "sessionKey": {"key": "aws:SourceIdentity"}, +} +STS = service("sts", {"AssumeRole": ["sts:AssumeRole", "sts:SetContext", "sts:SetSourceIdentity", "sts:TagSession"], + "AssumeRoleWithSAML": []}, + ["AssumeRole", "SetSourceIdentity", "TagSession"]) +STS_REQUESTS = {"sts": {"AssumeRole": {"RoleArn", "RoleSessionName", "SourceIdentity"}}} + + +def test_the_action_the_page_names_and_the_reference_lists_is_the_operations_companion(): + assert r.companions([STS], SOURCE_IDENTITY, STS_REQUESTS) == {"sts": {"AssumeRole": [ + {"action": "sts:SetSourceIdentity", "member": "SourceIdentity", "carried": "aws:SourceIdentity", + "callerPolicyWhenChained": True}]}} + document = r.build([STS, *ANCHOR_SERVICES], "a test", [], source_identity=SOURCE_IDENTITY, + requests=STS_REQUESTS) + assert document["companions"]["sts"]["AssumeRole"][0]["action"] == "sts:SetSourceIdentity" + assert r.validate(document, []) == [] + + +def test_no_page_or_an_action_the_reference_does_not_list_gives_no_companion(): + assert r.companions([STS], None) == {} + unlisted = service("sts", {"AssumeRole": ["sts:AssumeRole", "sts:TagSession"]}, ["AssumeRole"]) + assert r.companions([unlisted], SOURCE_IDENTITY, STS_REQUESTS) == {} + + +def test_a_member_botocore_does_not_give_the_operation_is_refused(): + with pytest.raises(ValueError, match="no request member SourceIdentity"): + r.companions([STS], SOURCE_IDENTITY, {"sts": {"AssumeRole": {"RoleArn"}}}) + + +@pytest.mark.parametrize("companion", [ + {"action": "iam:PassRole", "member": "SourceIdentity", "carried": "aws:SourceIdentity", + "callerPolicyWhenChained": True}, + {"action": "sts:SetSourceIdentity", "member": "Source.Identity", "carried": "aws:SourceIdentity", + "callerPolicyWhenChained": True}, + {"action": "sts:SetSourceIdentity", "member": "SourceIdentity", "carried": "sts:SourceIdentity", + "callerPolicyWhenChained": True}, + {"action": "sts:SetSourceIdentity", "member": "SourceIdentity", "carried": "aws:SourceIdentity", + "callerPolicyWhenChained": "yes"}, + {"action": "sts:SetSourceIdentity", "member": "SourceIdentity", "carried": "aws:SourceIdentity"}, +]) +def test_a_malformed_companion_is_rejected(companion): + document = anchored() + document["companions"] = {"sts": {"AssumeRole": [companion]}} + assert any("companions sts:AssumeRole" in problem for problem in r.validate(document, [])) diff --git a/tools/aws/test_regen_request_condition_keys.py b/tools/aws/test_regen_request_condition_keys.py index 09222bff33..2b7311199b 100644 --- a/tools/aws/test_regen_request_condition_keys.py +++ b/tools/aws/test_regen_request_condition_keys.py @@ -151,6 +151,9 @@ def test_the_vendored_table_covers_its_namespaces(): "tools/aws/sources/route53-condition-keys.json", "tools/aws/fetch_route53_conditions.py", "tools/aws/test_fetch_route53_conditions.py", + "tools/aws/sources/sts-source-identity.json", + "tools/aws/fetch_sts_source_identity.py", + "tools/aws/test_fetch_sts_source_identity.py", "tools/aws/regen_iam_passed_roles.py", "tools/aws/regen_partitions.py", "tools/aws/regen_query_services.py", @@ -208,12 +211,15 @@ def test_eks_cluster_request_members_and_create_only_bootstrap_key(): assert "eks:DescribeCluster" not in document["actions"] -def test_assume_role_reads_its_session_name_and_external_id(): +def test_assume_role_reads_its_session_name_external_id_and_source_identity(): document = json.loads(OUTPUT.read_text()) assert document["members"]["sts:AssumeRole"] == { - "sts:ExternalId": ["ExternalId"], "sts:RoleSessionName": ["RoleSessionName"]} + "sts:ExternalId": ["ExternalId"], "sts:RoleSessionName": ["RoleSessionName"], + "sts:SourceIdentity": ["SourceIdentity"]} + # The IAM user guide names the member a source identity is passed in for AssumeRole alone: the federated + # operations take it from the assertion or the token. assert document["members"]["sts:AssumeRoleWithWebIdentity"] == {"sts:RoleSessionName": ["RoleSessionName"]} - assert document["actions"]["sts:AssumeRoleWithSAML"] == ["sts:RoleSessionName"] + assert document["actions"]["sts:AssumeRoleWithSAML"] == ["sts:RoleSessionName", "sts:SourceIdentity"] assert "sts:AssumeRoleWithSAML" not in document["members"] assert "sts:GetCallerIdentity" not in document["actions"]