diff --git a/docs/services/iam.md b/docs/services/iam.md index 5f38141553..fd9bbcba39 100644 --- a/docs/services/iam.md +++ b/docs/services/iam.md @@ -305,6 +305,7 @@ validation. | GetLoginProfile | Returns a user's login profile. | | UpdateLoginProfile | Updates a user's login profile password and/or reset-required flag. | | DeleteLoginProfile | Deletes a user's login profile. | +| ChangePassword | Changes the console password of the user who is calling. | `UserName` is optional on `CreateLoginProfile`, `GetLoginProfile` and `DeleteLoginProfile`: it defaults to the user resolved from the signing access key, the same fallback `GetUser` uses. It is @@ -321,6 +322,37 @@ also checked against that policy's length and character-class requirements, with `PasswordPolicyViolation` returned on either action if it doesn't comply. The password itself is never echoed back by any of these actions, matching AWS. +`ChangePassword` is the self-service half of `UpdateLoginProfile`. It takes no `UserName` and acts +only on the user whose access key signed the request, which is what the API reference means by "the +IAM user who is calling this operation", and the account root password is not affected by it. A +caller with no IAM user behind its key, which is Floci's stand-in for account root credentials, is +refused with `InvalidUserType`, the error the CLI reference documents for that case. `OldPassword` +must match the stored password, and the reference publishes no error for a mismatch, so Floci +answers `InvalidParameterValue`, the common error type for a parameter value the service cannot +accept. It is checked before the new password is held to the account policy, so a caller who cannot +prove the current password learns nothing about what the policy requires. A successful change +clears `PasswordResetRequired`, which is what lets a user whose password an administrator reset +restore their own console access programmatically, and it updates the `password_last_changed` the +credential report reads. + +`PasswordReusePrevention` is enforced on `ChangePassword` and on `UpdateLoginProfile`, which share +one history per login profile, so an administrator reset cannot put back a password a user has just +been refused. The reference defines the value as "the number of previous passwords that IAM users +are prevented from reusing", and says that with no value set users "are not prevented from reusing +previous passwords". The password the profile currently holds is refused alongside the superseded +ones, which the reference does not spell out: read the other way, the smallest window the policy +accepts would still allow setting a password to the value it already has, and would not refuse the +change away and straight back that the setting exists for. History is recorded whether or not a +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. + `DeleteUser` returns `DeleteConflict`, as on AWS, while the user still has a login profile, access keys, inline policies, attached managed policies, group memberships, an [enabled MFA device](#multi-factor-authentication), a diff --git a/docs/services/index.md b/docs/services/index.md index c5bd2a89d1..cda7b79b1e 100644 --- a/docs/services/index.md +++ b/docs/services/index.md @@ -22,7 +22,7 @@ Operation counts are exact. For dispatch-table services (Query and JSON 1.1) eac | [Lambda MicroVMs](lambda-microvms.md) | `/2025-09-09/...` + `/2026-04-04/...` | REST JSON | 22 | | [API Gateway v1](api-gateway.md) | `/restapis/...` | REST JSON | 79 | | [API Gateway v2](api-gateway.md#v2) | `/v2/apis/...` | REST JSON | 53 + data-plane | -| [IAM](iam.md) | `POST /` with `Action=` param | Query | 166 | +| [IAM](iam.md) | `POST /` with `Action=` param | Query | 167 | | [STS](sts.md) | `POST /` with `Action=` param | Query | 7 | | [AWS Sign-In](iam.md#aws-sign-in-login-credentials) | `/v1/authorize`, `/v1/token` | REST JSON | 2 | | [Organizations](organizations.md) | `POST /` + `X-Amz-Target: AWSOrganizationsV20161128.*` | JSON 1.1 | 56 | diff --git a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java index fe6962402d..ea95d8df3d 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/AwsQueryController.java @@ -104,6 +104,7 @@ public class AwsQueryController { "TagPolicy", "UntagPolicy", "ListPolicyTags", "TagInstanceProfile", "UntagInstanceProfile", "ListInstanceProfileTags", "CreateLoginProfile", "GetLoginProfile", "DeleteLoginProfile", "UpdateLoginProfile", + "ChangePassword", "GenerateCredentialReport", "GetCredentialReport", "GetAccountSummary", "GetAccountAuthorizationDetails", "SimulatePrincipalPolicy", "SimulateCustomPolicy", 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 09c8b5986b..3e45bf929e 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 @@ -130,6 +130,7 @@ public class IamQueryHandler { case "GetLoginProfile" -> handleGetLoginProfile(params, authorization); case "UpdateLoginProfile" -> handleUpdateLoginProfile(params); case "DeleteLoginProfile" -> handleDeleteLoginProfile(params, authorization); + case "ChangePassword" -> handleChangePassword(params, authorization); // Multi-factor authentication case "CreateVirtualMFADevice" -> handleCreateVirtualMFADevice(params); @@ -571,6 +572,40 @@ public class IamQueryHandler { return Response.ok(AwsQueryResponse.envelopeNoResult("DeleteLoginProfile", AwsNamespaces.IAM)).build(); } + /** + * Changes the calling user's console password. The operation takes no {@code UserName}: the + * reference says it "changes the password of the IAM user who is calling this operation", and + * the CLI reference adds that it "can be called by IAM users only. If this command is called + * using AWS account (root) credentials, the command returns an InvalidUserType error". A + * signing key that belongs to no stored user is Floci's stand-in for exactly that caller, so + * it answers the same way rather than reporting the key as missing. + */ + private Response handleChangePassword(MultivaluedMap params, + String authorization) { + // Both members are required, and read through getParam rather than requireParam because + // requireParam refuses a blank value where passwordType permits one: the pattern starts + // at \u0020, so a password of spaces is a value the model accepts. The shape check + // therefore stays with the pattern, which also names which of the two members failed. + iamService.changePassword(callingIamUser(authorization), + getParam(params, "OldPassword"), getParam(params, "NewPassword")); + return Response.ok( + AwsQueryResponse.envelopeNoResult("ChangePassword", AwsNamespaces.IAM)).build(); + } + + /** + * The IAM user whose access key signed the request, for the one operation that acts on the + * caller and gives no way to name anyone else. Unlike {@link #resolveUserName}, a key with no + * user behind it is not a missing entity here: the caller is not an IAM user, which is the + * case {@code InvalidUserType} is published for. + */ + private String callingIamUser(String authorization) { + String accessKeyId = accountResolver.extractAccessKeyId(authorization); + return iamService.findUserNameByAccessKeyId(accessKeyId) + .orElseThrow(() -> new AwsException("InvalidUserType", + "The request was rejected because the type of user for the transaction " + + "was incorrect.", 400)); + } + private String loginProfileXml(LoginProfile profile) { return new XmlBuilder() .elem("PasswordResetRequired", profile.isPasswordResetRequired()) 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 d4d288cd89..72f1a7342a 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 @@ -387,6 +387,15 @@ public class IamService implements SessionAccountLookup, ResourceProvider { private final String seededAccountAlias; /** Guards case-insensitive IAM name uniqueness checks and their corresponding writes. */ private final Object resourceNameLock = new Object(); + /** + * Guards every check-then-write on a login profile. ChangePassword is the reason it has to + * exist: it reads the profile to compare the old password, then writes the new one, so two + * requests presenting the same valid old password would otherwise both pass the comparison + * and both report success while only the later write survived. Every writer takes it, since a + * guard one writer skips guarantees nothing: a racing UpdateLoginProfile would overwrite the + * password a ChangePassword had just been told it could set. + */ + private final Object loginProfileLock = new Object(); /** * AWS-managed policies ({@code arn::iam::aws:policy/...}), keyed by ARN, one map @@ -888,11 +897,13 @@ public class IamService implements SessionAccountLookup, ResourceProvider { credential.getServiceSpecificCredentialId(), credential); } } - loginProfiles.get(userName).ifPresent(profile -> { - loginProfiles.delete(userName); - profile.setUserName(newUserName); - loginProfiles.put(newUserName, profile); - }); + synchronized (loginProfileLock) { + loginProfiles.get(userName).ifPresent(profile -> { + loginProfiles.delete(userName); + profile.setUserName(newUserName); + loginProfiles.put(newUserName, profile); + }); + } for (AccessKey key : keysToMove) { key.setUserName(newUserName); accessKeys.put(key.getAccessKeyId(), key); @@ -2338,13 +2349,19 @@ public class IamService implements SessionAccountLookup, ResourceProvider { /** A user holds at most one login profile: creating a second is EntityAlreadyExists. */ public LoginProfile createLoginProfile(String userName, String password, boolean passwordResetRequired) { getUser(userName); - if (loginProfiles.get(userName).isPresent()) { - throw new AwsException("EntityAlreadyExists", - "Login Profile for User " + userName + " already exists.", 409); + LoginProfile profile; + synchronized (loginProfileLock) { + if (loginProfiles.get(userName).isPresent()) { + throw new AwsException("EntityAlreadyExists", + "Login Profile for User " + userName + " already exists.", 409); + } + validatePassword(password, "password"); + // No profile to pass: a password being set for the first time replaces nothing, and a + // profile deleted and recreated takes its history with it. + checkPasswordPolicy(password, null); + profile = new LoginProfile(userName, password, passwordResetRequired); + loginProfiles.put(userName, profile); } - validateLoginProfilePassword(password); - LoginProfile profile = new LoginProfile(userName, password, passwordResetRequired); - loginProfiles.put(userName, profile); LOG.infov("Created IAM login profile for user: {0}", userName); return profile; } @@ -2364,42 +2381,166 @@ public class IamService implements SessionAccountLookup, ResourceProvider { * clear the reset-required flag, and vice versa. */ public void updateLoginProfile(String userName, String password, Boolean passwordResetRequired) { - LoginProfile profile = getLoginProfile(userName); - if (password != null) { - validateLoginProfilePassword(password); - profile.setPassword(password); - profile.setPasswordLastChanged(Instant.now()); + synchronized (loginProfileLock) { + LoginProfile profile = getLoginProfile(userName); + if (password != null) { + validatePassword(password, "password"); + checkPasswordPolicy(password, profile); + recordSupersededPassword(profile); + profile.setPassword(password); + profile.setPasswordLastChanged(Instant.now()); + } + if (passwordResetRequired != null) { + profile.setPasswordResetRequired(passwordResetRequired); + } + loginProfiles.put(userName, profile); } - if (passwordResetRequired != null) { - profile.setPasswordResetRequired(passwordResetRequired); - } - loginProfiles.put(userName, profile); LOG.infov("Updated IAM login profile for user: {0}", userName); } public void deleteLoginProfile(String userName) { getUser(userName); - if (loginProfiles.get(userName).isEmpty()) { - throw new AwsException("NoSuchEntity", - "Login Profile for User " + userName + " cannot be found.", 404); + synchronized (loginProfileLock) { + if (loginProfiles.get(userName).isEmpty()) { + throw new AwsException("NoSuchEntity", + "Login Profile for User " + userName + " cannot be found.", 404); + } + loginProfiles.delete(userName); } - loginProfiles.delete(userName); LOG.infov("Deleted IAM login profile for user: {0}", userName); } /** - * Base wire validation shared by Create/UpdateLoginProfile, then, only when the account has - * ever set one (matching {@link #getAccountPasswordPolicy}'s own NoSuchEntity-by-default - * semantics), the account's password policy. + * Changes the password of the IAM user who is calling, which is the only user + * {@code ChangePassword} can act on: the reference says it "changes the password of the IAM + * user who is calling this operation" and that "the AWS account root user password is not + * affected by this operation". The caller is resolved from the signing access key before this + * is reached, so the user name here is already that user. + * + *

The old password is checked before the new one is held to the account's policy, so a + * caller who cannot prove the current password is refused on that alone and learns nothing + * about what the policy would have required. + * + *

The comparison and the write are one step under {@code loginProfileLock}, which is what + * makes the refusal above mean anything: read apart from the write, two requests presenting + * the same valid old password would both pass the comparison and both be told they had set + * the password, while only the later write survived. + * + *

A successful change clears {@code PasswordResetRequired}. The user guide's own reason for + * the "Password expiration requires administrator reset" option is that it stops users + * updating their own password through the console, and says that even then "IAM users with + * iam:ChangePassword permission and active access keys can reset their own IAM user console + * password programmatically", which is only true if the change itself clears the state the + * reset left behind. + * + *

An old password that does not match is the one refusal the reference leaves unnamed: + * every error it publishes for this operation describes something else, and the error it + * documents for a caller that is not an IAM user is {@code InvalidUserType}, raised by the + * handler. The common error types are additive per action, so this answers + * {@code InvalidParameterValue}, which is the published one for a parameter value the service + * cannot accept, with the same 400 as the operation's other sender faults. */ - private void validateLoginProfilePassword(String password) { - if (password == null || !LOGIN_PROFILE_PASSWORD_PATTERN.matcher(password).matches()) { - throw new AwsException("ValidationError", - "1 validation error detected: Value at 'password' failed to satisfy constraint: " - + "Member must have length less than or equal to 128 and greater than or " - + "equal to 1", 400); + public void changePassword(String userName, String oldPassword, String newPassword) { + validatePassword(oldPassword, "oldPassword"); + validatePassword(newPassword, "newPassword"); + synchronized (loginProfileLock) { + LoginProfile profile = getLoginProfile(userName); + if (!oldPassword.equals(profile.getPassword())) { + throw new AwsException("InvalidParameterValue", + "The old password supplied is not the current password for user " + + userName + ".", 400); + } + checkPasswordPolicy(newPassword, profile); + recordSupersededPassword(profile); + profile.setPassword(newPassword); + profile.setPasswordLastChanged(Instant.now()); + profile.setPasswordResetRequired(false); + loginProfiles.put(userName, profile); + } + LOG.infov("Changed the IAM console password of user: {0}", userName); + } + + /** + * The account's password policy applied to a password about to be stored, and only when the + * account has ever set one, matching {@link #getAccountPasswordPolicy}'s own + * NoSuchEntity-by-default semantics. {@code replacing} is the profile the password is being + * written over, or null when there is none to reuse a password from. + */ + private void checkPasswordPolicy(String password, LoginProfile replacing) { + getAccountPasswordPolicy().ifPresent(policy -> { + checkPasswordAgainstPolicy(password, policy); + if (replacing != null) { + checkPasswordNotReused(replacing, password, policy); + } + }); + } + + /** + * Refuses a password the account's reuse window still holds. The reference defines + * {@code PasswordReusePrevention} as "the number of previous passwords that IAM users are + * prevented from reusing", with no value meaning "IAM users are not prevented from reusing + * previous passwords", so the window is that many superseded passwords. + * + *

The password the profile currently holds is refused alongside them, which the reference + * does not spell out. Reading it the other way makes a window of 1 refuse nothing a user + * would attempt: it would leave setting a password to the value it already has allowed, and + * that is reuse in the only sense the setting exists to stop. Counting the current password + * first is also what makes the A to B and back to A case refusable at the smallest window the + * policy accepts. + */ + private static void checkPasswordNotReused(LoginProfile profile, String password, + AccountPasswordPolicy policy) { + Integer window = policy.getPasswordReusePrevention(); + if (window == null) { + return; + } + List held = profile.getPreviousPasswords(); + List refused = new ArrayList<>(); + refused.add(profile.getPassword()); + refused.addAll(held.subList(0, Math.min(window, held.size()))); + if (refused.contains(password)) { + throw new AwsException("PasswordPolicyViolation", + "Password does not conform to the account password policy. It must not be the " + + "current password or one of the previous " + window + + " passwords.", 400); + } + } + + /** + * Moves the password a profile is about to lose into its history, newest first. Bounded at the + * largest window {@code PasswordReusePrevention} accepts, since nothing can be asked about a + * password further back than that. + */ + private static void recordSupersededPassword(LoginProfile profile) { + List held = profile.getPreviousPasswords(); + held.add(0, profile.getPassword()); + while (held.size() > PASSWORD_REUSE_PREVENTION_CEILING) { + held.remove(held.size() - 1); + } + } + + /** + * {@code passwordType}, which every password member on every one of these operations shares. + * The member is named so the message is the one AWS gives for the parameter that failed: + * {@code ChangePassword} has two of them, and a caller told that 'password' failed has to + * guess which. + * + *

An absent member and an empty one are different answers. The pattern requires at least + * one character, so an empty value fails the constraint, where an absent one was never + * supplied at all. + */ + private static void validatePassword(String password, String member) { + if (password == null) { + throw new AwsException("ValidationError", + "1 validation error detected: Value null at '" + member + + "' failed to satisfy constraint: Member must not be null", 400); + } + if (!LOGIN_PROFILE_PASSWORD_PATTERN.matcher(password).matches()) { + throw new AwsException("ValidationError", + "1 validation error detected: Value at '" + member + + "' failed to satisfy constraint: Member must have length less than " + + "or equal to 128 and greater than or equal to 1", 400); } - getAccountPasswordPolicy().ifPresent(policy -> checkPasswordAgainstPolicy(password, policy)); } private void checkPasswordAgainstPolicy(String password, AccountPasswordPolicy policy) { @@ -3476,7 +3617,7 @@ public class IamService implements SessionAccountLookup, ResourceProvider { *

The API Reference publishes a length of 20 to 128 as well as the pattern, so both are * checked, and both are reported when both are broken, in the order it prints them. The * pattern message is the one recorded against AWS; the length wording is the form AWS uses for - * a member carrying both bounds, which {@link #validateLoginProfilePassword} spells the same + * a member carrying both bounds, which {@link #validatePassword} spells the same * way. */ private void requireCredentialIdFormat(String credentialId) { diff --git a/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java b/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java index 284423b9b4..1936feaeef 100644 --- a/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java +++ b/src/main/java/io/github/hectorvent/floci/services/iam/model/LoginProfile.java @@ -4,13 +4,16 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; +import java.util.ArrayList; +import java.util.List; /** * A user's console (password) login profile. At most one per user, mirroring AWS: creating * one when the user already has one is {@code EntityAlreadyExists}, and a user with no - * console password simply has no entry here. The password is stored in plain text, matching - * how {@link AccessKey} already stores its secret: this is an emulator, not a credential - * store, and AWS itself never echoes the password back on any of these actions. + * console password simply has no entry here. The password, and the history the reuse window is + * checked against, are stored in plain text, matching how {@link AccessKey} already stores its + * secret: this is an emulator, not a credential store, and AWS itself never echoes the password + * back on any of these actions. */ @RegisterForReflection @JsonIgnoreProperties(ignoreUnknown = true) @@ -27,6 +30,13 @@ public class LoginProfile { * a profile persisted before this field existed; callers fall back to {@link #createDate}. */ private Instant passwordLastChanged; + /** + * The passwords this profile held before the current one, most recent first, bounded at the 24 + * {@code PasswordReusePrevention} is allowed to ask for. Recorded whether or not the account + * sets that policy, so switching it on has something to compare against, and empty for a + * profile persisted before this field existed. + */ + private List previousPasswords = new ArrayList<>(); public LoginProfile() {} @@ -54,4 +64,16 @@ public class LoginProfile { public Instant getPasswordLastChanged() { return passwordLastChanged; } public void setPasswordLastChanged(Instant passwordLastChanged) { this.passwordLastChanged = passwordLastChanged; } + + public List getPreviousPasswords() { + if (previousPasswords == null) { + previousPasswords = new ArrayList<>(); + } + return previousPasswords; + } + + public void setPreviousPasswords(List previousPasswords) { + this.previousPasswords = + previousPasswords != null ? new ArrayList<>(previousPasswords) : new ArrayList<>(); + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamChangePasswordIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamChangePasswordIntegrationTest.java new file mode 100644 index 0000000000..38d7f0f431 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamChangePasswordIntegrationTest.java @@ -0,0 +1,174 @@ +package io.github.hectorvent.floci.services.iam; + +import io.github.hectorvent.floci.core.common.AwsQueryController; +import io.github.hectorvent.floci.testing.PartitionCleanup; +import io.quarkus.test.junit.QuarkusTest; +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.util.Map; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; + +/** + * {@code ChangePassword} over the wire, which is the only IAM operation that acts on the caller + * and gives no way to name anyone else. + * + *

Driven through the whole stack because two of the things worth checking live outside the + * handler. The caller is read from the signing access key, so a request signed with a key that + * belongs to a user has to reach that user and nobody else. And the action name is shared with + * Cognito, so a request that arrives without a usable credential scope has to be routed to IAM by + * {@link AwsQueryController}: Cognito is further down that chain and answers + * {@code UnsupportedOperation} to every form request, so the routing is what decides whether the + * operation exists at all on that path. + * + *

Runs in an account of its own, like the other IAM classes that set account-wide state: the + * emulator is shared, and an account password policy left visible to another class changes what + * that class's passwords are held to. + */ +@QuarkusTest +class IamChangePasswordIntegrationTest { + + private static final String ACCOUNT = "000000000911"; + private static final String REGION = "us-east-1"; + private static final String PASSWORD = "Sup3r$ecret!"; + private static final String NEW_PASSWORD = "An0ther$ecret!"; + + @RegisterExtension + final PartitionCleanup cleanup = new PartitionCleanup(); + + @Test + void theSignerChangesItsOwnPassword() { + String accessKeyId = userWithAConsolePassword("changes-own"); + + signedAs(accessKeyId, Map.of("OldPassword", PASSWORD, "NewPassword", NEW_PASSWORD)) + .statusCode(200) + .body("ChangePasswordResponse.ResponseMetadata.RequestId", not(equalTo(""))); + + // Nothing echoes a password back, so the proof the write took is the next call: the old + // password is no longer the current one and the new one is. + signedAs(accessKeyId, Map.of("OldPassword", PASSWORD, "NewPassword", "Th1rd$ecret!")) + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidParameterValue")); + signedAs(accessKeyId, Map.of("OldPassword", NEW_PASSWORD, "NewPassword", "Th1rd$ecret!")) + .statusCode(200); + } + + @Test + void aSignerWithNoConsolePasswordIsNoSuchEntity() { + String accessKeyId = userWithoutAConsolePassword("no-profile"); + + signedAs(accessKeyId, Map.of("OldPassword", PASSWORD, "NewPassword", NEW_PASSWORD)) + .statusCode(404) + .body("ErrorResponse.Error.Code", equalTo("NoSuchEntity")); + } + + @Test + void anAccountCredentialIsInvalidUserType() { + // The account's own credential stands in for the root user, which the CLI reference says + // this operation answers InvalidUserType for. + admin("ChangePassword", Map.of("OldPassword", PASSWORD, "NewPassword", NEW_PASSWORD)) + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidUserType")); + } + + @Test + void anUnsignedRequestIsAnsweredByIamRatherThanCognito() { + // No credential scope, so the service comes from the action name alone. Cognito also + // publishes ChangePassword; reaching it would answer UnsupportedOperation instead. + given() + .contentType("application/x-www-form-urlencoded") + .formParam("Action", "ChangePassword") + .formParam("Version", "2010-05-08") + .formParam("OldPassword", PASSWORD) + .formParam("NewPassword", NEW_PASSWORD) + .when().post("/") + .then() + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("InvalidUserType")) + .body(not(containsString("UnsupportedOperation"))); + } + + @Test + void anAbsentMemberNamesItself() { + String accessKeyId = userWithAConsolePassword("absent-member"); + + signedAs(accessKeyId, Map.of("NewPassword", NEW_PASSWORD)) + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("ValidationError")) + .body("ErrorResponse.Error.Message", containsString("'oldPassword'")); + } + + @Test + void theNewPasswordIsHeldToTheAccountPasswordPolicy() { + String accessKeyId = userWithAConsolePassword("policy"); + admin("UpdateAccountPasswordPolicy", Map.of("MinimumPasswordLength", "20", + "RequireSymbols", "true", "RequireNumbers", "true")).statusCode(200); + cleanup.register(() -> admin("DeleteAccountPasswordPolicy", Map.of()).statusCode(200)); + + signedAs(accessKeyId, Map.of("OldPassword", PASSWORD, "NewPassword", "sh0rt!")) + .statusCode(400) + .body("ErrorResponse.Error.Code", equalTo("PasswordPolicyViolation")); + + signedAs(accessKeyId, + Map.of("OldPassword", PASSWORD, "NewPassword", "L0ngEn0ugh$ecret!!!!")) + .statusCode(200); + } + + /** A user holding a console password, with an access key to sign its own requests with. */ + private String userWithAConsolePassword(String label) { + String userName = user(label); + admin("CreateLoginProfile", Map.of("UserName", userName, "Password", PASSWORD)) + .statusCode(200); + cleanup.register(() -> admin("DeleteLoginProfile", Map.of("UserName", userName)) + .statusCode(200)); + return accessKeyFor(userName); + } + + /** The same, minus the console password: an IAM user with nothing to change. */ + private String userWithoutAConsolePassword(String label) { + return accessKeyFor(user(label)); + } + + private String user(String label) { + String userName = "change-password-" + label; + admin("CreateUser", Map.of("UserName", userName)).statusCode(200); + cleanup.register(() -> admin("DeleteUser", Map.of("UserName", userName)).statusCode(200)); + return userName; + } + + private String accessKeyFor(String userName) { + String accessKeyId = admin("CreateAccessKey", Map.of("UserName", userName)).statusCode(200) + .extract().path("CreateAccessKeyResponse.CreateAccessKeyResult.AccessKey" + + ".AccessKeyId"); + cleanup.register(() -> admin("DeleteAccessKey", + Map.of("UserName", userName, "AccessKeyId", accessKeyId)).statusCode(200)); + return accessKeyId; + } + + private ValidatableResponse signedAs(String accessKeyId, Map params) { + return iam(accessKeyId, "ChangePassword", params); + } + + private ValidatableResponse admin(String action, Map params) { + return iam(ACCOUNT, action, params); + } + + private static ValidatableResponse iam(String accessKeyId, String action, + Map params) { + RequestSpecification spec = given() + .header("Authorization", "AWS4-HMAC-SHA256 Credential=" + accessKeyId + + "/20261012/" + REGION + "/iam/aws4_request, SignedHeaders=host, " + + "Signature=abc") + .contentType("application/x-www-form-urlencoded") + .formParam("Action", action) + .formParam("Version", "2010-05-08"); + params.forEach(spec::formParam); + return spec.when().post("/").then(); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java index e39161df87..5495afbc45 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamConcurrencyTest.java @@ -346,6 +346,57 @@ class IamConcurrencyTest { } } + /** + * Every racing ChangePassword presents the same valid old password, so exactly one can be + * right: once the first write lands, the old password the others hold is no longer the current + * one. A request told it succeeded has to be the one whose password is in the store, since the + * caller has no way to find out otherwise, the operation echoing nothing back. + */ + @Test + void concurrentPasswordChangesLeaveExactlyOneWinner() throws Exception { + ExecutorService pool = Executors.newFixedThreadPool(THREADS); + try { + for (int trial = 0; trial < TRIALS; trial++) { + IamService iam = newIamService(); + iam.createUser("racer", "/"); + iam.createLoginProfile("racer", "Passw0rd$start", false); + CountDownLatch start = new CountDownLatch(1); + CountDownLatch done = new CountDownLatch(N); + List winners = new CopyOnWriteArrayList<>(); + List unexpected = new CopyOnWriteArrayList<>(); + + for (int i = 0; i < N; i++) { + String candidate = "Passw0rd$" + i; + pool.execute(() -> { + try { + start.await(10, TimeUnit.SECONDS); + iam.changePassword("racer", "Passw0rd$start", candidate); + winners.add(candidate); + } catch (io.github.hectorvent.floci.core.common.AwsException e) { + if (!"InvalidParameterValue".equals(e.getErrorCode())) { + unexpected.add(e.getErrorCode()); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + done.countDown(); + } + }); + } + start.countDown(); + assertTrue(done.await(30, TimeUnit.SECONDS), "password workers stalled"); + + String stored = iam.getLoginProfile("racer").getPassword(); + if (winners.size() != 1 || !winners.contains(stored) || !unexpected.isEmpty()) { + fail("changePassword trial " + trial + ": winners=" + winners + + " stored=" + stored + " unexpectedErrors=" + unexpected); + } + } + } finally { + pool.shutdownNow(); + } + } + private static String[] createPolicies(IamService iam, String prefix) { String[] arns = new String[N]; for (int i = 0; i < N; i++) { diff --git a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java index 46ec1e3660..3f43e1156d 100644 --- a/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/iam/IamServiceTest.java @@ -871,6 +871,194 @@ class IamServiceTest { assertEquals("alice", profile.getUserName()); } + @Test + void changePasswordReplacesThePasswordAndClearsTheResetFlag() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", true); + + iamService.changePassword("alice", "Sup3r$ecret!", "An0ther$ecret!"); + + LoginProfile profile = iamService.getLoginProfile("alice"); + assertFalse(profile.isPasswordResetRequired(), + "a self-service change is what clears the reset an administrator required"); + assertNotNull(profile.getPasswordLastChanged()); + // The proof the write took is behavioural rather than a read of the stored field: the + // new password is now the current one and the old one is not. + iamService.changePassword("alice", "An0ther$ecret!", "Th1rd$ecret!"); + assertEquals("InvalidParameterValue", assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "An0ther$ecret!", "F0urth$ecret!")) + .getErrorCode()); + } + + @Test + void changePasswordWithTheWrongOldPasswordChangesNothing() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + + AwsException ex = assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "N0tTheOne!", "An0ther$ecret!")); + + assertEquals("InvalidParameterValue", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + // The refusal left the password alone, so the original still changes it. + iamService.changePassword("alice", "Sup3r$ecret!", "An0ther$ecret!"); + } + + @Test + void changePasswordChecksTheOldPasswordBeforeTheAccountPolicy() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + AccountPasswordPolicy policy = new AccountPasswordPolicy(); + policy.setMinimumPasswordLength(12); + iamService.updateAccountPasswordPolicy(policy); + + // Both halves of the request are wrong. A caller who cannot prove the current password is + // told that and nothing about what the policy would have required. + AwsException ex = assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "N0tTheOne!", "short")); + + assertEquals("InvalidParameterValue", ex.getErrorCode()); + } + + @Test + void changePasswordHoldsTheNewPasswordToTheAccountPolicy() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + AccountPasswordPolicy policy = new AccountPasswordPolicy(); + policy.setMinimumPasswordLength(12); + policy.setRequireSymbols(true); + policy.setRequireNumbers(true); + iamService.updateAccountPasswordPolicy(policy); + + AwsException ex = assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "Sup3r$ecret!", "short")); + + assertEquals("PasswordPolicyViolation", ex.getErrorCode()); + assertEquals(400, ex.getHttpStatus()); + iamService.changePassword("alice", "Sup3r$ecret!", "An0ther$ecret!"); + } + + @Test + void changePasswordNamesTheMemberThatFailedItsConstraint() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + + AwsException missing = assertThrows(AwsException.class, + () -> iamService.changePassword("alice", null, "An0ther$ecret!")); + assertEquals("ValidationError", missing.getErrorCode()); + assertTrue(missing.getMessage().contains("Value null at 'oldPassword'"), missing.getMessage()); + + // An empty member is a value that fails the pattern rather than a member never supplied, + // and the message names the one that failed, there being two password members here. + AwsException empty = assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "Sup3r$ecret!", "")); + assertEquals("ValidationError", empty.getErrorCode()); + assertTrue(empty.getMessage().contains("Value at 'newPassword'"), empty.getMessage()); + } + + @Test + void changePasswordRefusesAPasswordTheReuseWindowStillHolds() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + AccountPasswordPolicy policy = new AccountPasswordPolicy(); + policy.setPasswordReusePrevention(1); + iamService.updateAccountPasswordPolicy(policy); + + iamService.changePassword("alice", "Sup3r$ecret!", "An0ther$ecret!"); + + // The window is one superseded password, and the one in hand counts alongside it, so + // neither going back nor standing still is allowed. + assertEquals("PasswordPolicyViolation", assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "An0ther$ecret!", "Sup3r$ecret!")) + .getErrorCode()); + assertEquals("PasswordPolicyViolation", assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "An0ther$ecret!", "An0ther$ecret!")) + .getErrorCode()); + } + + @Test + void changePasswordAllowsAPasswordThatHasLeftTheReuseWindow() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + AccountPasswordPolicy policy = new AccountPasswordPolicy(); + policy.setPasswordReusePrevention(1); + iamService.updateAccountPasswordPolicy(policy); + + iamService.changePassword("alice", "Sup3r$ecret!", "An0ther$ecret!"); + iamService.changePassword("alice", "An0ther$ecret!", "Th1rd$ecret!"); + + // A window of one reaches the current password and the one before it, and the first is + // now two back, so it is reachable again. + iamService.changePassword("alice", "Th1rd$ecret!", "Sup3r$ecret!"); + assertNotNull(iamService.getLoginProfile("alice").getPasswordLastChanged()); + } + + @Test + void changePasswordWithNoReusePolicyTakesTheOldPasswordBack() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + AccountPasswordPolicy policy = new AccountPasswordPolicy(); + policy.setMinimumPasswordLength(8); + iamService.updateAccountPasswordPolicy(policy); + + // A policy that sets no window prevents nothing: the reference's default is that users + // "are not prevented from reusing previous passwords". + iamService.changePassword("alice", "Sup3r$ecret!", "An0ther$ecret!"); + iamService.changePassword("alice", "An0ther$ecret!", "Sup3r$ecret!"); + } + + @Test + void updateLoginProfileIsHeldToTheSameReuseWindow() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Sup3r$ecret!", false); + AccountPasswordPolicy policy = new AccountPasswordPolicy(); + policy.setPasswordReusePrevention(2); + iamService.updateAccountPasswordPolicy(policy); + iamService.updateLoginProfile("alice", "An0ther$ecret!", null); + + // An administrator reset is a password the policy applies to as much as a self-service + // change, and the two share one history. + assertEquals("PasswordPolicyViolation", assertThrows(AwsException.class, + () -> iamService.updateLoginProfile("alice", "Sup3r$ecret!", null)).getErrorCode()); + assertEquals("PasswordPolicyViolation", assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "An0ther$ecret!", "Sup3r$ecret!")) + .getErrorCode()); + } + + @Test + void loginProfileHistoryStopsAtTheWidestWindowThePolicyAccepts() { + iamService.createUser("alice", "/"); + iamService.createLoginProfile("alice", "Passw0rd$0", false); + for (int i = 1; i <= 30; i++) { + iamService.updateLoginProfile("alice", "Passw0rd$" + i, null); + } + + // Nothing can be asked about a password further back than the largest window, so the + // history stops there rather than growing with every change. + assertEquals(24, iamService.getLoginProfile("alice").getPreviousPasswords().size()); + assertEquals("Passw0rd$29", + iamService.getLoginProfile("alice").getPreviousPasswords().get(0)); + } + + @Test + void changePasswordForAUserWithoutAConsolePasswordIsNoSuchEntity() { + iamService.createUser("alice", "/"); + + AwsException ex = assertThrows(AwsException.class, + () -> iamService.changePassword("alice", "Sup3r$ecret!", "An0ther$ecret!")); + + assertEquals("NoSuchEntity", ex.getErrorCode()); + assertEquals(404, ex.getHttpStatus()); + } + + @Test + void changePasswordForAnUnknownUserIsNoSuchEntity() { + AwsException ex = assertThrows(AwsException.class, + () -> iamService.changePassword("nobody", "Sup3r$ecret!", "An0ther$ecret!")); + + assertEquals("NoSuchEntity", ex.getErrorCode()); + } + @Test void deleteUserWithLoginProfileIsDeleteConflict() { iamService.createUser("alice", "/");