From b58d181a307f2e5a395624395ed6afcd08421f79 Mon Sep 17 00:00:00 2001 From: Priamo Germosen <6233424+pgermosen@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:14:18 -0400 Subject: [PATCH] feat(iam): authorize the account password policy's self-service flag (#5717) The account password policy accepted AllowUsersToChangePassword, echoed it back from GetAccountPasswordPolicy, and no authorization decision read it: the six references in src/main were the field, its accessors, the setter call and the XML element. So under enforcement a user needed a policy naming their own user however the flag was set, and the option AWS describes as account-level authorized nothing. The user guide: the option "gives users access to the iam:ChangePassword action for only their user and to the iam:GetAccountPasswordPolicy action", and it "does not attach a permissions policy to each user. Rather, IAM applies the permissions at the account-level for all users." So it is one document for the whole account rather than a grant assembled per user: iam:ChangePassword on user/${aws:username} and on user/*/${aws:username}, the two patterns AWS's own IAMUserChangePassword policy writes, the second for a user under a path, plus iam:GetAccountPasswordPolicy. The resource ARNs are minted in the request's partition, for the account whose password policy sets the flag. Writing it with the variable rather than the caller's resolved ARN is what makes it the grant the guide describes, and it carries two properties for free. The scope to "only their user" is the variable's, so one stored document serves every user in the account. And the grant belongs to IAM users without a principal check of its own: a role session and the account root have no aws:username, the variable resolves to nothing, and a resource holding a variable with no value "will not match any resource". It therefore rests on the substitution #5639 added, now on main; without it the statement is literal text and matches nobody, which is what the probe below shows. The grant reaches the caller wherever the principal is an IAM user: its own access key, a session token it minted, and the simulate path. It is appended to the identity policies the evaluator already reads, so nothing about evaluation order changes: an explicit Deny still refuses the call and a permissions boundary still caps it. collectUserPolicies stays the user's own set, so ListUserPolicies, ListAttachedUserPolicies and GetAccountAuthorizationDetails report nothing new, which is the "does not attach a permissions policy" half of the guide. That half holds for the answers AWS scopes to attached policies. ListPoliciesGrantingServiceAccess reports policies by name and type and has none to report here, and GetContextKeysForPrincipalPolicy returns "only context keys referenced by the identity-based policies attached to the specified entity, and any additional policies that you provide", so it reads the attached set rather than the evaluated one: it had been naming the ${aws:username} of the grant's own resource, twice, once per pattern, out of a document the user does not hold. A last-accessed report answers the other question, "every AWS service that the resource could access using permissions policies", and an account-level permission is one the user can reach: GenerateServiceLastAccessedDetails lists iam for a user carrying no policy of their own while the flag is set, and nothing for that same user once it is cleared. The grant goes into the documents the service list is read from rather than into the policies the report names, since it is no policy of the user's and has no name or ARN to report as one. One thing the variable form exposed. SimulatePrincipalPolicy built its context from the call's ContextEntries alone, so a policy scoped to ${aws:username} simulated as if the key were absent and this grant answered implicitDeny for a permission the account really gives. The guide lists what a simulation starts with, "aws:PrincipalAccount, aws:PrincipalId, aws:PrincipalType, aws:Type, aws:UserId, aws:UserName", adding that "because these keys are populated for you ... You provide the values for all other condition keys". So the handler now populates them for a user policy source, through the same CallerArns writer the enforcement filter uses, which makes a simulation read what an enforced request reads: aws:PrincipalArn, aws:PrincipalType, aws:username, aws:userid and the account. The guide's aws:PrincipalId and aws:Type are in no request context here, so a simulation does not invent them either, and iam.md says so rather than leaving the list to imply all six. A value the call supplied still wins, in whatever case it spelled the key, since the context is keyed the way the evaluator compares key names: keyed by the raw spelling, a supplied aws:principaltype and a populated aws:PrincipalType were two entries and the later lowercasing kept whichever hashing happened to reach first. The account comes from the identity that resolved rather than from the ARN the call wrote, which need not be one this emulator can parse: a PolicySourceArn is resolved by its trailing name, so arn:aws:iam:user/bob names a user while parsing as nothing, and parsing the request's own text turned that call into a 500. A role named as the source is not a session: there is no session name for an aws:userid and no documented aws:PrincipalType for it, so those keys stay absent and a statement matching on one does not match. The flag that answers for a user is their own account's. A PolicySourceArn is the one way to name a user elsewhere, and the lookup already resolves them in the account their ARN names, so the flag is read there as well and the grant's resource ARNs are minted for that account. This account's grant therefore never resolves ${aws:username} to a user its password policy does not cover, and a user of another account is not refused a permission their own account really gives: an allowed answer needs their account to set the flag and the resource to be theirs. Thirteen integration tests under enforcement: the flag letting a user with no policies change its own password and read the policy, the grant appearing in neither listing nor in GetAccountAuthorizationDetails, nor among the context keys a simulation's caller is told to supply, while a policy the user really carries appears in all three, a last-accessed report listing iam for a user carrying nothing else while the flag is set and nothing once it is cleared, an explicit Deny of iam:ChangePassword still refusing the call, a permissions boundary still capping it, the grant reaching none of GetUser, UpdateLoginProfile or CreateUser, the flag read both ways by one user whose policies never change, the scope checked through SimulatePrincipalPolicy against another user's ARN, a supplied context value surviving a key spelled in another case, a PolicySourceArn that parses as nothing still simulating, this account's flag not reaching a user of another account, and that user's own account's flag reaching them over their own ARNs. Each of the authorizing ones ends on something only the grant allows, which the first round of them lacked: two asserted refusals alone and passed with the grant withheld. Probed six ways, by withholding the grant, by disabling substitution, by dropping the simulator's populated keys, and by reverting each of three tests' fixes, failing all ten, all ten, the one simulation, and one test apiece. The three added here were probed the same way, one behaviour at a time: the other account's user went back to implicitDeny, the context keys answered aws:username twice, and withholding the grant from the report emptied it. Verified on main: 6680 tests across the 342 IAM, core, enforcement and resource-policy classes that reach the evaluator, 13 skipped and none failing, with Checkstyle, docs-check and partition-check clean, the last because the grant mints its resource ARNs rather than writing a partition literal. --- docs/services/iam.md | 45 +- .../floci/services/iam/IamQueryHandler.java | 41 +- .../floci/services/iam/IamService.java | 145 +++++- ...erviceGrantEnforcementIntegrationTest.java | 455 ++++++++++++++++++ 4 files changed, 673 insertions(+), 13 deletions(-) create mode 100644 src/test/java/io/github/hectorvent/floci/services/iam/PasswordSelfServiceGrantEnforcementIntegrationTest.java diff --git a/docs/services/iam.md b/docs/services/iam.md index 4ed61be371..7755ead207 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -362,12 +362,31 @@ change away and straight back that the setting exists for. History is recorded w window is set, so switching the policy on has something to compare against, bounded at the 24 the policy can ask for, and it goes with the profile when `DeleteLoginProfile` removes it. -`AllowUsersToChangePassword` is accepted and reported but grants nothing. The user -guide says the option gives all users in the account "access to the iam:ChangePassword action for -only their user and to the iam:GetAccountPasswordPolicy action", applied at the account level -rather than by attaching a policy to each user. Floci authorizes both actions from identity -policies alone, so under [enforcement](#iam-enforcement-mode) a caller needs a policy naming their -own user however the flag is set. +`AllowUsersToChangePassword` authorizes. The user guide says the option gives all users in the +account "access to the iam:ChangePassword action for only their user and to the +iam:GetAccountPasswordPolicy action", and that it "does not attach a permissions policy to each +user. Rather, IAM applies the permissions at the account-level for all users". So under +[enforcement](#iam-enforcement-mode) an IAM user carrying no policy at all may change its own +password and read the policy while the flag is set, and neither call is authorized once it is +cleared. The grant is assembled for the caller it applies to, naming that user's own ARN, so it +authorizes `iam:ChangePassword` for them and for nobody else, and it reaches no other action: not +`UpdateLoginProfile`, not `GetUser`. The flag that answers for a user is their own account's, so a +`PolicySourceArn` naming another account's user simulates with that account's grant, over that +account's user ARNs. + +Being account-level rather than attached, the grant appears in nothing that lists a user's +policies, `ListUserPolicies`, `ListAttachedUserPolicies` and `GetAccountAuthorizationDetails` +included, nor in `ListPoliciesGrantingServiceAccess`, which reports policies by name and type and +has none to report here. A last-accessed report answers a different question, "every AWS service +that the resource could access using permissions policies", so `GenerateServiceLastAccessedDetails` +does list `iam` for a user carrying no policy of their own while the flag is set, and lists nothing +for that same user once it is cleared. `GetContextKeysForPrincipalPolicy` stays with the attached +set, returning "only context keys referenced by the identity-based policies attached to the +specified entity, and any additional policies that you provide", so it does not name the +`${aws:username}` the grant's own resource uses, which a simulation populates anyway. In +authorization it is an identity-based grant like any other: an explicit `Deny` still refuses the +call and a permissions boundary still caps it. It belongs to IAM users: a role session has no +console password to change, and the root user is not an IAM user. `DeleteUser` returns `DeleteConflict`, as on AWS, while the user still has a login profile, access keys, inline policies, attached managed policies, group memberships, an @@ -396,6 +415,20 @@ they substitute a literal character rather than naming a context key. The list i nor de-duplicated, matching AWS's own documented example response, which repeats a key referenced by more than one statement. +`SimulatePrincipalPolicy` populates the principal keys itself when the policy source is an IAM +user, as AWS's simulator does: the guide lists `aws:PrincipalAccount`, `aws:PrincipalId`, +`aws:PrincipalType`, `aws:Type`, `aws:UserId` and `aws:UserName` as "populated for you", with the +caller providing "the values for all other condition keys", so a policy scoped to +`${aws:username}` simulates the way it is evaluated. What a simulation gets is the principal half +of the request context, the same keys the enforcement filter writes: `aws:PrincipalArn`, +`aws:PrincipalType`, `aws:username`, `aws:userid` and the account. `aws:PrincipalId` and +`aws:Type` are in no request context here, so a simulation does not populate them either; a +statement matching on one matches nothing, as it would on an enforced request. A value passed in +`ContextEntries` wins, being the one the call asked to simulate with, whatever case it spells the +key in. A role named as the policy source is not a session, so there is no session name for an +`aws:userid` and no documented `aws:PrincipalType` for it; those keys stay absent and a statement +matching on one does not match. + `PolicySourceArn` on `SimulatePrincipalPolicy` and `GetContextKeysForPrincipalPolicy` resolves an IAM user or role only, not a group. `SimulateCustomPolicy` accepts only one `PermissionsBoundaryPolicyInputList` document, matching AWS's own documented limit; extra documents diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java index 8942b38ae8..020ceeb44a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamQueryHandler.java @@ -2107,7 +2107,24 @@ public class IamQueryHandler { CallerContext caller = iamService.resolvePrincipalContext(policySourceArn); List actionNames = requireActionNames(params); List resourceArns = extractResourceArnsOrWildcard(params); - Map> context = extractContextEntries(params); + // Keyed without regard to case, as the evaluator compares condition key names: a value + // the call supplied has to shadow a populated one however the call spelled the key. + Map> context = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + context.putAll(extractContextEntries(params)); + // The simulator fills the principal keys in itself rather than asking for them, so a + // policy scoped to ${aws:username} or keyed on who is calling simulates as it evaluates. + // A value the call supplied stays, being the one the caller asked to simulate with. The + // account comes from the identity that was resolved, not from the ARN the call wrote, + // which need not be one this evaluator can parse. + iamService.simulationPrincipalKeys(policySourceArn).ifPresent(principal -> { + Map> populated = new HashMap<>(); + principal.putPrincipalKeys(populated); + String account = AwsArnUtils.accountOrDefault(principal.principalArn(), null); + if (account != null) { + populated.put("aws:PrincipalAccount", List.of(account)); + } + populated.forEach(context::putIfAbsent); + }); String result = simulationResultsXml(caller, actionNames, resourceArns, context); return Response.ok(AwsQueryResponse.envelope("SimulatePrincipalPolicy", AwsNamespaces.IAM, result)).build(); } @@ -2177,7 +2194,11 @@ public class IamQueryHandler { private Response handleGetContextKeysForPrincipalPolicy(MultivaluedMap params) { String policySourceArn = getParam(params, "PolicySourceArn"); - CallerContext caller = iamService.resolvePrincipalContext(policySourceArn); + // "Only context keys referenced by the identity-based policies attached to the specified + // entity, and any additional policies that you provide, are included": a grant the account + // applies without attaching it is therefore not read here, though a simulation evaluates + // with it. + CallerContext caller = iamService.resolveAttachedPrincipalContext(policySourceArn); List allDocuments = new ArrayList<>(caller.identityPolicies()); allDocuments.addAll(extractIndexedValues(params, "PolicyInputList.member")); List keys = policyEvaluator.contextKeysReferencedIn(allDocuments); @@ -2543,7 +2564,15 @@ public class IamQueryHandler { case "user" -> { IamUser user = requireMatchingArn(iamService.getUser(parsed.name()).getArn(), arn, iamService.getUser(parsed.name())); - yield new AccessAdvisorTarget(identityPolicyDocuments(accountId, arn), List.of(entityOf(user))); + // The report lists "every AWS service that the resource could access using + // permissions policies", so a permission the account applies to its users without + // attaching it counts: a user with no policies of their own still reaches IAM + // while the password policy allows self-service. It is added to the documents the + // service list is read from rather than to policiesForIdentity, since it is no + // policy of the user's and has no name or ARN to report as one. + List documents = new ArrayList<>(identityPolicyDocuments(accountId, arn)); + documents.addAll(iamService.accountLevelUserGrants(accountId)); + yield new AccessAdvisorTarget(documents, List.of(entityOf(user))); } case "role" -> { IamRole role = requireMatchingArn(iamService.getRole(parsed.name()).getArn(), arn, @@ -2715,7 +2744,11 @@ public class IamQueryHandler { } } - /** The documents behind an identity ARN, reusing the scoping rules above. */ + /** + * The documents behind an identity ARN, reusing the scoping rules above. These are the + * identity's own policies only: a grant the account applies without attaching it is no policy + * of theirs, so the user branch above adds it to what it reports rather than finding it here. + */ private List identityPolicyDocuments(String accountId, String arn) { List documents = new ArrayList<>(); for (GrantingPolicy candidate : policiesForIdentity(accountId, arn)) { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java index eb49344240..5f5ab3a0ea 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/IamService.java @@ -123,6 +123,24 @@ public class IamService implements SessionAccountLookup, ResourceProvider { */ private static final String FEDERATED_USER_SESSION_LIMITS = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":[\"iam:*\",\"sts:*\"],\"Resource\":\"*\"}]}"; + /** + * What the account password policy's {@code AllowUsersToChangePassword} authorizes. The guide: + * the option "gives users access to the iam:ChangePassword action for only their user and to + * the iam:GetAccountPasswordPolicy action", and "does not attach a permissions policy to each + * user. Rather, IAM applies the permissions at the account-level for all users". So this is one + * document for the whole account, and {@code ${aws:username}} is what binds it to the caller, + * exactly as AWS's own {@code IAMUserChangePassword} policy writes the same grant. The second + * resource is that policy's second pattern, for a user under a path. A principal with no + * {@code aws:username}, a role session or the account root, resolves the variable to nothing + * and the statement then matches no user at all, which is the behaviour the guide describes for + * a key with no value and the reason this grant needs no principal check of its own. + */ + private static final String PASSWORD_SELF_SERVICE_GRANT = + "{\"Version\":\"2012-10-17\",\"Statement\":[" + + "{\"Effect\":\"Allow\",\"Action\":\"iam:ChangePassword\"," + + "\"Resource\":[\"%s\",\"%s\"]}," + + "{\"Effect\":\"Allow\",\"Action\":\"iam:GetAccountPasswordPolicy\"," + + "\"Resource\":\"*\"}]}"; private static final String DEFAULT_DEPLOYER_USER = "floci-deployer"; private static final String DEFAULT_DEPLOYER_ACCESS_KEY_ID = "floci"; private static final String DEFAULT_DEPLOYER_SECRET_ACCESS_KEY = "floci"; @@ -4873,7 +4891,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return CallerContext.of(List.of(SCOPED_IDENTITY_SESSION_BASE_POLICY)); } return issuingUser(session) - .map(user -> new CallerContext(collectUserPolicies(user.getUserName()), null, + .map(user -> new CallerContext(userIdentityPolicies(user.getUserName()), null, resolveUserBoundaryDocument(user.getUserName()))) .orElse(CallerContext.of(List.of())); } @@ -4963,7 +4981,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { Optional akOpt = accessKeys.get(accessKeyId); if (akOpt.isPresent()) { String userName = akOpt.get().getUserName(); - List identityPolicies = collectUserPolicies(userName); + List identityPolicies = userIdentityPolicies(userName); String boundaryDoc = resolveUserBoundaryDocument(userName); return new CallerContext(identityPolicies, null, boundaryDoc); } @@ -5177,6 +5195,33 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } + /** + * The principal keys a policy simulation starts with, for the identity named by a + * {@code PolicySourceArn}. The simulator does not ask a caller for these: the guide lists + * {@code aws:PrincipalAccount}, {@code aws:PrincipalId}, {@code aws:PrincipalType}, + * {@code aws:Type}, {@code aws:UserId} and {@code aws:UserName} as "populated for you", and + * says the caller provides "the values for all other condition keys". + * + *

What a simulation gets here is the principal half of the request context, the same + * {@link CallerArns#putPrincipalKeys} the enforcement filter writes, so a policy simulates the + * way it is enforced: {@code aws:PrincipalArn}, {@code aws:PrincipalType}, + * {@code aws:username} and {@code aws:userid}, with the account added by the caller of this + * method. The guide's {@code aws:PrincipalId} and {@code aws:Type} are not in that context on + * any request path, so populating them in a simulation alone would answer for keys an + * enforced request cannot, and they stay absent here too. + * + *

Only a user source answers here. A role named as a policy source is not a session, so + * there is no session name to put in an {@code aws:userid} and no documented value for its + * {@code aws:PrincipalType} in a simulation; those keys stay absent, and a policy that matches + * on one does not match, which is what an absent key means everywhere else. + */ + public Optional simulationPrincipalKeys(String principalArn) { + if (principalArn == null || !principalArn.contains(":user/")) { + return Optional.empty(); + } + return userFromArnOrName(principalArn).map(IamService::callerForUser); + } + /** * Both of the caller's ARNs from a single lookup, so they always describe the same credential: * two lookups could straddle a session's expiry and answer for it only once. @@ -5348,12 +5393,30 @@ public class IamService implements SessionAccountLookup, ResourceProvider { } public CallerContext resolvePrincipalContext(String principalArn) { + return principalContext(principalArn, true); + } + + /** + * The same context without the account-level grants that apply to an identity without being + * attached to it, for {@code GetContextKeysForPrincipalPolicy}: AWS scopes that answer to "the + * identity-based policies attached to the specified entity, and any additional policies that + * you provide", so the key {@link #PASSWORD_SELF_SERVICE_GRANT} references is not one the + * caller has to supply. A simulation does evaluate with the grant, the way the request path + * does, and stays on {@link #resolvePrincipalContext}. + */ + public CallerContext resolveAttachedPrincipalContext(String principalArn) { + return principalContext(principalArn, false); + } + + private CallerContext principalContext(String principalArn, boolean withAccountGrants) { if (principalArn == null || principalArn.isBlank()) { throw new AwsException("ValidationError", "PolicySourceArn is required.", 400); } if (principalArn.contains(":user/")) { String userName = principalArn.substring(principalArn.lastIndexOf('/') + 1); - List identityPolicies = collectUserPolicies(principalArn); + List identityPolicies = withAccountGrants + ? userIdentityPolicies(principalArn) + : collectUserPolicies(principalArn); if (identityPolicies == null) { throw new AwsException("NoSuchEntity", "User " + userName + " cannot be found.", 404); } @@ -5520,6 +5583,82 @@ public class IamService implements SessionAccountLookup, ResourceProvider { return findRole(AwsArnUtils.accountOrDefault(roleArnOrName, regionResolver.getAccountId()), roleName); } + /** + * The policies an IAM user is evaluated with: its own and its groups', plus the account-level + * grant {@link #PASSWORD_SELF_SERVICE_GRANT} carries when the account password policy allows + * users to change their own password. + * + *

{@link #collectUserPolicies} stays the user's own set, which is what the guide means by + * applying the permissions at the account level rather than attaching a policy: an answer AWS + * scopes to the policies attached to a user reads the attached set, so the grant is in no + * policy listing and in no context-key answer. It is in this set, the one authorization is + * decided from, and in {@link #accountLevelUserGrants}, which a report of what a user can + * reach adds on top of the attached set. + */ + private List userIdentityPolicies(String userArnOrName) { + List docs = collectUserPolicies(userArnOrName); + if (docs == null) { + return null; + } + // The flag that answers is the user's own account's, which is the account the lookup above + // resolved them in: a PolicySourceArn may name another account's user, and that user + // carries whatever their own account's password policy says, never this one's. + Optional grant = passwordSelfServiceGrant( + AwsArnUtils.accountOrDefault(userArnOrName, regionResolver.getAccountId())); + if (grant.isEmpty()) { + return docs; + } + List withGrant = new ArrayList<>(docs); + withGrant.add(grant.get()); + return withGrant; + } + + /** + * The account-level grants an IAM user of {@code accountId} is authorized by without holding a + * policy of its own, which today is the password self-service grant alone. Separate from + * {@link #userIdentityPolicies} because a caller reporting on a user needs these without the + * user's own documents, and because "the policies attached to a user" and "what the user can + * reach" are different questions that AWS answers from different sets. + */ + public List accountLevelUserGrants(String accountId) { + return passwordSelfServiceGrant(accountId).map(List::of).orElseGet(List::of); + } + + /** + * An account's password self-service grant, present only while that account's password policy + * sets {@code AllowUsersToChangePassword}. One document for every user in the account, its + * resource ARNs minted for that same account in the request's partition, with + * {@code ${aws:username}} left for the evaluator to resolve per caller. + */ + private Optional passwordSelfServiceGrant(String accountId) { + boolean allowed = accountPasswordPolicy(accountId) + .map(AccountPasswordPolicy::isAllowUsersToChangePassword) + .orElse(false); + if (!allowed) { + return Optional.empty(); + } + return Optional.of(PASSWORD_SELF_SERVICE_GRANT.formatted( + regionResolver.buildGlobalArn("iam", accountId, "user/${aws:username}"), + regionResolver.buildGlobalArn("iam", accountId, "user/*/${aws:username}"))); + } + + /** + * The password policy of a named account rather than the request's own, for a user that + * resolved in another one. Mirrors {@link #findUser(String, String)}: the store is + * account-namespaced, and the request's own account goes through + * {@link #getAccountPasswordPolicy()}, which also picks up a policy persisted before the + * store was namespaced. + */ + private Optional accountPasswordPolicy(String accountId) { + if (accountId.equals(regionResolver.getAccountId())) { + return getAccountPasswordPolicy(); + } + if (passwordPolicies instanceof AccountAwareStorageBackend aware) { + return aware.getForAccount(accountId, ACCOUNT_PASSWORD_POLICY_KEY); + } + return passwordPolicies.get(ACCOUNT_PASSWORD_POLICY_KEY); + } + private List collectUserPolicies(String userArnOrName) { Optional userOpt = userFromArnOrName(userArnOrName); if (userOpt.isEmpty()) { diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/PasswordSelfServiceGrantEnforcementIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/PasswordSelfServiceGrantEnforcementIntegrationTest.java new file mode 100644 index 0000000000..aeeb8f0384 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/PasswordSelfServiceGrantEnforcementIntegrationTest.java @@ -0,0 +1,455 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.testing.EnforcementFixtures; +import io.github.hectorvent.floci.testing.IamEnforcementProfile; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.common.http.TestHTTPResource; +import io.quarkus.test.junit.QuarkusTest; +import io.quarkus.test.junit.TestProfile; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The account password policy's {@code AllowUsersToChangePassword}, which the guide describes as + * an account-level grant: the option "gives users access to the iam:ChangePassword action for only + * their user and to the iam:GetAccountPasswordPolicy action", and "does not attach a permissions + * policy to each user. Rather, IAM applies the permissions at the account-level for all users". + * + *

Runs in an account of its own, like the other classes that set account-wide state: the + * emulator is shared, and a password policy left visible to another class changes what that class + * is authorized to do. + */ +@QuarkusTest +@TestProfile(IamEnforcementProfile.class) +class PasswordSelfServiceGrantEnforcementIntegrationTest { + + private static final String ACCOUNT = "000000000913"; + private static final String OTHER_ACCOUNT = "000000000914"; + private static final String PASSWORD = "Sup3r$ecret!"; + private static final String NEW_PASSWORD = "An0ther$ecret!"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @TestHTTPResource("/") + URI baseUri; + + @Test + void theAccountFlagLetsAUserChangeItsOwnPassword() { + allowUsersToChangePassword(true); + String accessKeyId = userWithAConsolePassword(); + + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD).statusCode(200); + as(accessKeyId, "GetAccountPasswordPolicy", Map.of()).statusCode(200); + } + + /** The grant is not a policy on the user, so nothing that lists their policies shows it. */ + @Test + void theGrantIsNotAttachedToTheUser() { + allowUsersToChangePassword(true); + String userName = "pw-grant-" + suffix(); + String accessKeyId = userWithAConsolePassword(userName); + + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD).statusCode(200); + assertEquals(List.of(), inlinePolicyNames(userName)); + assertEquals(List.of(), attachedPolicyArns(userName)); + assertEquals(List.of(), inlinePoliciesInAccountDetails(userName)); + + // The same readings do report a policy the user really carries, so the empty ones mean an + // absent grant rather than a path that names nothing. + admin("PutUserPolicy", Map.of("UserName", userName, "PolicyName", "own", + "PolicyDocument", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:GetUser","Resource":"*"}]}""")) + .statusCode(200); + assertEquals(List.of("own"), inlinePolicyNames(userName)); + assertEquals(List.of("own"), inlinePoliciesInAccountDetails(userName)); + } + + private List inlinePolicyNames(String userName) { + return admin("ListUserPolicies", Map.of("UserName", userName)).statusCode(200) + .extract().xmlPath() + .getList("ListUserPoliciesResponse.ListUserPoliciesResult.PolicyNames.member", + String.class); + } + + private List attachedPolicyArns(String userName) { + return admin("ListAttachedUserPolicies", Map.of("UserName", userName)).statusCode(200) + .extract().xmlPath() + .getList("ListAttachedUserPoliciesResponse.ListAttachedUserPoliciesResult" + + ".AttachedPolicies.member.PolicyArn", String.class); + } + + /** The policy names {@code GetAccountAuthorizationDetails} reports for one user. */ + private List inlinePoliciesInAccountDetails(String userName) { + return admin("GetAccountAuthorizationDetails", Map.of("Filter.member.1", "User")) + .statusCode(200).extract().xmlPath() + .getList("GetAccountAuthorizationDetailsResponse" + + ".GetAccountAuthorizationDetailsResult.UserDetailList.member" + + ".findAll { it.UserName == '" + userName + "' }" + + ".UserPolicyList.member.PolicyName", String.class); + } + + /** + * A last-accessed report lists "every AWS service that the resource could access using + * permissions policies", so this one counts: a user carrying no policy at all reaches IAM + * while the flag is set, and reaches nothing once it is cleared. The report is fixed when the + * job runs, so each reading generates its own. + */ + @Test + void theGrantIsLastAccessedInformation() { + allowUsersToChangePassword(true); + String userName = "pw-advisor-" + suffix(); + String accessKeyId = userWithAConsolePassword(userName); + // The grant is live for this user, so the report is reporting a permission they have. + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD).statusCode(200); + + assertEquals(List.of("iam"), servicesLastAccessed(userName)); + + // The flag is what puts it there: cleared, the same user with the same policies, none, + // reaches nothing. + allowUsersToChangePassword(false); + assertEquals(List.of(), servicesLastAccessed(userName)); + } + + /** The service namespaces a user's last-accessed report lists. */ + private List servicesLastAccessed(String userName) { + String jobId = admin("GenerateServiceLastAccessedDetails", + Map.of("Arn", "arn:aws:iam::" + ACCOUNT + ":user/" + userName)) + .statusCode(200) + .extract().path("GenerateServiceLastAccessedDetailsResponse" + + ".GenerateServiceLastAccessedDetailsResult.JobId"); + return admin("GetServiceLastAccessedDetails", Map.of("JobId", jobId)).statusCode(200) + .extract().xmlPath() + .getList("GetServiceLastAccessedDetailsResponse" + + ".GetServiceLastAccessedDetailsResult.ServicesLastAccessed.member" + + ".ServiceNamespace", String.class); + } + + /** + * And it leaves the caller nothing to supply: {@code GetContextKeysForPrincipalPolicy} answers + * for "the identity-based policies attached to the specified entity, and any additional + * policies that you provide", so the {@code ${aws:username}} in the grant's own resource is + * not a key that answer names. A simulation populates it regardless. + */ + @Test + void theGrantReferencesNoContextKeyToSupply() { + allowUsersToChangePassword(true); + String userName = "pw-keys-" + suffix(); + userWithAConsolePassword(userName); + + assertEquals(List.of(), contextKeys(userName)); + + // A key an attached policy does reference comes back, so the empty reading is the grant + // staying out rather than the whole answer being empty. + admin("PutUserPolicy", Map.of("UserName", userName, "PolicyName", "named-user", + "PolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"iam:GetUser","Resource":"*", + "Condition":{"StringEquals":{"aws:username":"someone"}}}]}""")) + .statusCode(200); + assertEquals(List.of("aws:username"), contextKeys(userName)); + } + + /** The context keys {@code GetContextKeysForPrincipalPolicy} names for one user. */ + private List contextKeys(String userName) { + return admin("GetContextKeysForPrincipalPolicy", + Map.of("PolicySourceArn", "arn:aws:iam::" + ACCOUNT + ":user/" + userName)) + .statusCode(200).extract().xmlPath() + .getList("GetContextKeysForPrincipalPolicyResponse" + + ".GetContextKeysForPrincipalPolicyResult.ContextKeyNames.member", + String.class); + } + + /** An ordinary identity grant, so an explicit Deny of the same action still refuses it. */ + @Test + void anExplicitDenyStillRefusesTheCall() { + allowUsersToChangePassword(true); + String userName = "pw-denied-" + suffix(); + String accessKeyId = userWithAConsolePassword(userName); + admin("PutUserPolicy", Map.of("UserName", userName, "PolicyName", "deny-change", + "PolicyDocument", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Deny","Action":"iam:ChangePassword","Resource":"*"}]}""")) + .statusCode(200); + + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD) + .statusCode(403).body(containsString("AccessDenied")); + // The policy is what refuses it: the same user reads the password policy, which that Deny + // does not name. + as(accessKeyId, "GetAccountPasswordPolicy", Map.of()).statusCode(200); + } + + /** And a permissions boundary caps it, as it caps any identity-based permission. */ + @Test + void aPermissionsBoundaryStillCapsIt() { + allowUsersToChangePassword(true); + String userName = "pw-bounded-" + suffix(); + String accessKeyId = userWithAConsolePassword(userName); + String boundaryArn = admin("CreatePolicy", Map.of( + "PolicyName", "pw-boundary-" + suffix(), + "PolicyDocument", """ + {"Version":"2012-10-17","Statement":[ + {"Effect":"Allow","Action":"iam:GetAccountPasswordPolicy", + "Resource":"*"}]}""")) + .statusCode(200) + .extract().path("CreatePolicyResponse.CreatePolicyResult.Policy.Arn"); + cleanup.register(() -> EnforcementFixtures.removePolicy(port(), + EnforcementFixtures.auth(ACCOUNT, "iam"), boundaryArn)); + admin("PutUserPermissionsBoundary", + Map.of("UserName", userName, "PermissionsBoundary", boundaryArn)).statusCode(200); + cleanup.register(() -> admin("DeleteUserPermissionsBoundary", + Map.of("UserName", userName)).statusCode(200)); + + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD) + .statusCode(403).body(containsString("AccessDenied")); + // The boundary allows the other half of the grant, so it is the boundary narrowing the + // grant rather than the grant having gone missing. + as(accessKeyId, "GetAccountPasswordPolicy", Map.of()).statusCode(200); + } + + /** Two actions, and the user still has none of the others it might want for a password. */ + @Test + void theGrantReachesNothingElse() { + allowUsersToChangePassword(true); + String userName = "pw-narrow-" + suffix(); + String accessKeyId = userWithAConsolePassword(userName); + + as(accessKeyId, "GetUser", Map.of("UserName", userName)) + .statusCode(403).body(containsString("AccessDenied")); + as(accessKeyId, "UpdateLoginProfile", + Map.of("UserName", userName, "Password", NEW_PASSWORD)) + .statusCode(403).body(containsString("AccessDenied")); + as(accessKeyId, "CreateUser", Map.of("UserName", "pw-other-" + suffix())) + .statusCode(403).body(containsString("AccessDenied")); + + // The one call the grant does carry, so this test fails if the grant went missing rather + // than merely staying narrow. + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD).statusCode(200); + } + + /** The flag is what decides it, read both ways by one user whose policies never change. */ + @Test + void theFlagIsWhatDecidesIt() { + allowUsersToChangePassword(false); + String accessKeyId = userWithAConsolePassword(); + + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD) + .statusCode(403).body(containsString("AccessDenied")); + as(accessKeyId, "GetAccountPasswordPolicy", Map.of()) + .statusCode(403).body(containsString("AccessDenied")); + + allowUsersToChangePassword(true); + as(accessKeyId, "GetAccountPasswordPolicy", Map.of()).statusCode(200); + changePassword(accessKeyId, PASSWORD, NEW_PASSWORD).statusCode(200); + } + + /** + * "For only their user": the grant's resource is {@code user/${aws:username}}, so it resolves + * to the caller and names nobody else. Nothing is passed for that key: the simulator populates + * the principal keys itself, as AWS's does, so the simulation reads the way the request path + * reads. + */ + @Test + void theGrantNamesOnlyTheCallersOwnUser() { + allowUsersToChangePassword(true); + String mine = "pw-mine-" + suffix(); + String theirs = "pw-theirs-" + suffix(); + userWithAConsolePassword(mine); + userWithAConsolePassword(theirs); + + simulate(mine, "arn:aws:iam::" + ACCOUNT + ":user/" + mine).statusCode(200) + .body(decisionPath(), equalTo("allowed")); + simulate(mine, "arn:aws:iam::" + ACCOUNT + ":user/" + theirs).statusCode(200) + .body(decisionPath(), equalTo("implicitDeny")); + } + + /** + * The flag is the account's own, so it says nothing about a user of another account. Only a + * {@code PolicySourceArn} can name one, and naming one together with a resource ARN minted in + * this account would otherwise have the two halves meet: this account's grant resolving + * {@code ${aws:username}} to the other account's user. + */ + @Test + void theFlagDoesNotReachAnotherAccountsUser() { + allowUsersToChangePassword(true); + String userName = "pw-elsewhere-" + suffix(); + otherAccountUser(userName); + + simulateSource("arn:aws:iam::" + OTHER_ACCOUNT + ":user/" + userName, + "arn:aws:iam::" + ACCOUNT + ":user/" + userName) + .statusCode(200) + .body(decisionPath(), equalTo("implicitDeny")); + } + + /** + * The other half of that: the flag that answers for a user is their own account's. The ARN + * resolves them where it says they are, so the grant is that account's, naming that account's + * user ARNs, and a simulation run from this account reads it as that account would. + */ + @Test + void anotherAccountsUserCarriesItsOwnAccountsFlag() { + String userName = "pw-neighbour-" + suffix(); + otherAccountUser(userName); + allowUsersToChangePassword(OTHER_ACCOUNT, true); + + String source = "arn:aws:iam::" + OTHER_ACCOUNT + ":user/" + userName; + simulateSource(source, "arn:aws:iam::" + OTHER_ACCOUNT + ":user/" + userName) + .statusCode(200) + .body(decisionPath(), equalTo("allowed")); + // Their grant names their own account's ARNs and nothing in this one, which set no flag. + simulateSource(source, "arn:aws:iam::" + ACCOUNT + ":user/" + userName) + .statusCode(200) + .body(decisionPath(), equalTo("implicitDeny")); + } + + /** A user of the other account, with no policies and no console password. */ + private void otherAccountUser(String userName) { + String otherAuth = EnforcementFixtures.auth(OTHER_ACCOUNT, "iam"); + cleanup.register(() -> EnforcementFixtures.removeUser(port(), otherAuth, userName)); + iam(OTHER_ACCOUNT, "CreateUser", Map.of("UserName", userName)).statusCode(200); + } + + /** + * The keys the simulation fills in do not displace the ones the call passed, whichever case it + * spells them in: condition key names are compared without regard to case everywhere else, so + * a lower-cased {@code aws:principaltype} is the same key as the one populated here. + */ + @Test + void aSuppliedContextValueWinsWhateverCaseItIsSpelledIn() { + allowUsersToChangePassword(true); + String userName = "pw-typed-" + suffix(); + userWithAConsolePassword(userName); + admin("PutUserPolicy", Map.of("UserName", userName, "PolicyName", "as-a-role", + "PolicyDocument", """ + {"Version":"2012-10-17","Statement":[{"Effect":"Allow", + "Action":"iam:GetUser","Resource":"*", + "Condition":{"StringEquals":{"aws:PrincipalType":"AssumedRole"}}}]}""")) + .statusCode(200); + + for (String spelling : List.of("aws:PrincipalType", "aws:principaltype")) { + admin("SimulatePrincipalPolicy", Map.of( + "PolicySourceArn", "arn:aws:iam::" + ACCOUNT + ":user/" + userName, + "ActionNames.member.1", "iam:GetUser", + "ResourceArns.member.1", "*", + "ContextEntries.member.1.ContextKeyName", spelling, + "ContextEntries.member.1.ContextKeyValues.member.1", "AssumedRole")) + .statusCode(200) + .body(decisionPath("iam:GetUser"), equalTo("allowed")); + } + } + + /** + * A {@code PolicySourceArn} that names a user without being an ARN this emulator can parse is + * resolved by its trailing name, as it was before the principal keys were populated, so the + * account they carry comes from the identity that resolved rather than from the text of the + * call. + */ + @Test + void aPolicySourceArnItCannotParseStillSimulates() { + allowUsersToChangePassword(true); + String userName = "pw-oddarn-" + suffix(); + userWithAConsolePassword(userName); + + admin("SimulatePrincipalPolicy", Map.of( + "PolicySourceArn", "arn:aws:iam:user/" + userName, + "ActionNames.member.1", "iam:ChangePassword", + "ResourceArns.member.1", "arn:aws:iam::" + ACCOUNT + ":user/" + userName)) + .statusCode(200) + .body(decisionPath(), equalTo("allowed")); + } + + private static String decisionPath() { + return decisionPath("iam:ChangePassword"); + } + + private static String decisionPath(String action) { + return "SimulatePrincipalPolicyResponse.SimulatePrincipalPolicyResult.EvaluationResults" + + ".member.find { it.EvalActionName == '" + action + "' }.EvalDecision"; + } + + private ValidatableResponse simulate(String userName, String resourceArn) { + return simulateSource("arn:aws:iam::" + ACCOUNT + ":user/" + userName, resourceArn); + } + + private ValidatableResponse simulateSource(String policySourceArn, String resourceArn) { + return admin("SimulatePrincipalPolicy", Map.of( + "PolicySourceArn", policySourceArn, + "ActionNames.member.1", "iam:ChangePassword", + "ResourceArns.member.1", resourceArn)); + } + + private void allowUsersToChangePassword(boolean allowed) { + allowUsersToChangePassword(ACCOUNT, allowed); + } + + private void allowUsersToChangePassword(String account, boolean allowed) { + iam(account, "UpdateAccountPasswordPolicy", + Map.of("AllowUsersToChangePassword", Boolean.toString(allowed))).statusCode(200); + cleanup.register(() -> iam(account, "DeleteAccountPasswordPolicy", Map.of()) + .statusCode(200)); + } + + private String userWithAConsolePassword() { + return userWithAConsolePassword("pw-self-" + suffix()); + } + + /** An IAM user holding a console password and an access key, and no policies at all. */ + private String userWithAConsolePassword(String userName) { + String auth = EnforcementFixtures.auth(ACCOUNT, "iam"); + cleanup.register(() -> EnforcementFixtures.removeUser(port(), auth, userName)); + admin("CreateUser", Map.of("UserName", userName)).statusCode(200); + admin("CreateLoginProfile", Map.of("UserName", userName, "Password", PASSWORD)) + .statusCode(200); + cleanup.register(() -> admin("DeleteLoginProfile", Map.of("UserName", userName)) + .statusCode(200)); + return admin("CreateAccessKey", Map.of("UserName", userName)).statusCode(200) + .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey" + + ".AccessKeyId"); + } + + private ValidatableResponse changePassword(String accessKeyId, String oldPassword, + String newPassword) { + return as(accessKeyId, "ChangePassword", + Map.of("OldPassword", oldPassword, "NewPassword", newPassword)); + } + + private ValidatableResponse admin(String action, Map params) { + return iam(ACCOUNT, action, params); + } + + private ValidatableResponse as(String accessKeyId, String action, Map params) { + return iam(accessKeyId, action, params); + } + + private ValidatableResponse iam(String accessKeyId, String action, + Map params) { + RequestSpecification spec = given() + .header("Authorization", EnforcementFixtures.auth(accessKeyId, "iam")) + .contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + params.forEach(spec::formParam); + return spec.when().post("/").then(); + } + + private int port() { + return baseUri.getPort(); + } + + private static String suffix() { + return UUID.randomUUID().toString().substring(0, 8); + } +}