diff --git a/src/main/java/org/tdl/vireo/auth/controller/AuthController.java b/src/main/java/org/tdl/vireo/auth/controller/AuthController.java index f500380b79..2a15fa880e 100644 --- a/src/main/java/org/tdl/vireo/auth/controller/AuthController.java +++ b/src/main/java/org/tdl/vireo/auth/controller/AuthController.java @@ -32,6 +32,7 @@ import org.tdl.vireo.model.repo.EmailTemplateRepo; import org.tdl.vireo.model.repo.UserRepo; import org.tdl.vireo.service.VireoEmailSender; +import org.tdl.vireo.utility.PasswordValidator; import org.tdl.vireo.utility.TemplateUtility; import edu.tamu.weaver.auth.controller.WeaverAuthController; @@ -113,19 +114,12 @@ public ApiResponse registration(@RequestBody(required = false) Map data) { + + if (!availabilityService.isChangeAvailable()) { + LOG.debug("Rejected a password change, because the capability is not available."); + + return new ApiResponse(INVALID, "Changing your password is not available."); + } + + if (!PasswordEligibilityRule.isEligible(user)) { + LOG.debug("Rejected a password change, because the account is not eligible."); + + return new ApiResponse(INVALID, "This account does not use a Vireo-managed password."); + } + + String currentPassword = data.get("currentPassword"); + String newPassword = data.get("newPassword"); + String confirm = data.get("confirm"); + + if (!cryptoService.validatePassword(currentPassword, user.getPassword())) { + LOG.debug("Authentication failed!"); + + // Matches AuthController.login, so the client surfaces the failure the same way. + ValidationResults failedAuthenticationResults = new ValidationResults(); + failedAuthenticationResults.addMessage(ValidationUtility.BUSINESS_MESSAGE_KEY, "password", "Authentication failed!"); + + return new ApiResponse(INVALID, failedAuthenticationResults); + } + + PasswordValidator.Result passwordResult = PasswordValidator.validate(newPassword, confirm); + + if (passwordResult != PasswordValidator.Result.ACCEPTED) { + String passwordMessage = PasswordValidator.messageFor(passwordResult); + LOG.debug(passwordMessage); + + return new ApiResponse(INVALID, passwordMessage); + } + + // Encode the untrimmed value so surrounding whitespace is preserved. + user.setPassword(cryptoService.encodePassword(newPassword)); + + user = userRepo.update(user); + + credentialNotificationService.notifyPasswordChanged(user); + + return new ApiResponse(SUCCESS, "Your password has been changed."); + } + + /** + * Sends a single-use reset link to the holder of the Account identified by its email. The + * stored password is never written on this path and no response carries a token or password + * value; the administrator only learns a link was sent. Checks run in order (availability, + * eligibility, template resolution) and nothing is sent if any rejects. + * + * @param data {@code email} identifying the target Account. + */ + @PreAuthorize("hasRole('ROLE_MANAGER')") + @RequestMapping(value = "/reset", method = POST) + public ApiResponse initiateReset(@RequestBody Map data) { + + if (!availabilityService.isResetAvailable()) { + LOG.debug("Rejected a password reset, because the capability is not available."); + + return new ApiResponse(INVALID, "Resetting a password is not available."); + } + + String email = data.get("email"); + + User user = userRepo.findByEmail(email); + + if (!PasswordEligibilityRule.isEligible(user)) { + LOG.debug("Rejected a password reset, because the account is not eligible."); + + return new ApiResponse(INVALID, "This account does not use a Vireo-managed password."); + } + + EmailTemplate emailTemplate = credentialNotificationService.resolveTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE); + + if (emailTemplate == null) { + LOG.debug("Unable to send a password reset, because the email template '" + CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE + "' is not installed."); + + return new ApiResponse(ERROR, "The email template '" + CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE + "' is not installed."); + } + + String token = resetTokenService.construct(user); + + String resetLink = url + "/reset-password?token=" + token; + + String content = templateUtility.templateParameters(emailTemplate.getMessage(), new String[][] { { "RESET_URL", resetLink } }); + + try { + emailSender.sendEmail(user.getEmail(), emailTemplate.getSubject(), content); + } catch (MessagingException e) { + LOG.warn("Unable to send a password reset email.", e); + + return ApiResponse.fromException(ERROR, "Unable to send the password reset email.", e); + } + + return new ApiResponse(SUCCESS, "A password reset link has been sent."); + } + + /** + * Redeems a reset token, replacing the stored password of the Account the token names. + * Deliberately un-annotated: this handler is anonymously reachable exactly as + * {@code /auth/register} is, because redemption happens before sign-in. Checks run in order + * (availability, token verification, eligibility, new password) and nothing is written if any + * rejects; a rejected candidate leaves the token itself usable until it expires. No response + * carries the Account_Email, the token, or the stored hash, and a successful redemption leaves + * the caller signed out. + * + * @param data {@code token}, {@code newPassword}, and {@code confirm}. + */ + @RequestMapping(value = "/reset/redeem", method = POST) + public ApiResponse redeemReset(@RequestBody Map data) { + + if (!availabilityService.isResetAvailable()) { + LOG.debug("Rejected a password reset redemption, because the capability is not available."); + + return new ApiResponse(INVALID, "Resetting a password is not available."); + } + + String token = data.get("token"); + + ResetTokenVerification verification = resetTokenService.verify(token); + + if (verification.getStatus() == ResetTokenVerification.Status.EXPIRED) { + LOG.debug("Rejected a password reset redemption, because the token has expired."); + + return new ApiResponse(INVALID, "This password reset link has expired. Please ask an administrator to send a new one."); + } + + if (verification.getStatus() != ResetTokenVerification.Status.VALID) { + LOG.debug("Rejected a password reset redemption, because the token is not valid."); + + return new ApiResponse(INVALID, "This password reset link is no longer valid."); + } + + User user = userRepo.findByEmail(verification.getEmail()); + + if (!PasswordEligibilityRule.isEligible(user)) { + LOG.debug("Rejected a password reset redemption, because the account is not eligible."); + + return new ApiResponse(INVALID, "This account does not use a Vireo-managed password."); + } + + String newPassword = data.get("newPassword"); + String confirm = data.get("confirm"); + + PasswordValidator.Result passwordResult = PasswordValidator.validate(newPassword, confirm); + + if (passwordResult != PasswordValidator.Result.ACCEPTED) { + String passwordMessage = PasswordValidator.messageFor(passwordResult); + LOG.debug(passwordMessage); + + // Leave the token usable: it is unaffected by a rejected candidate. + return new ApiResponse(INVALID, passwordMessage); + } + + // Encode the untrimmed value so surrounding whitespace is preserved. + user.setPassword(cryptoService.encodePassword(newPassword)); + + user = userRepo.update(user); + + // The new stored hash invalidates this token and every sibling token for this Account. + credentialNotificationService.notifyPasswordChanged(user); + + return new ApiResponse(SUCCESS, "Your password has been set. Please sign in."); + } + +} diff --git a/src/main/java/org/tdl/vireo/controller/UserController.java b/src/main/java/org/tdl/vireo/controller/UserController.java index 1c805e9743..7637fdea06 100644 --- a/src/main/java/org/tdl/vireo/controller/UserController.java +++ b/src/main/java/org/tdl/vireo/controller/UserController.java @@ -6,6 +6,7 @@ import static org.springframework.web.bind.annotation.RequestMethod.POST; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -27,6 +28,7 @@ import org.tdl.vireo.model.User; import org.tdl.vireo.model.repo.UserRepo; import org.tdl.vireo.model.request.FilteredPageRequest; +import org.tdl.vireo.utility.PasswordEligibilityRule; import edu.tamu.weaver.auth.annotation.WeaverCredentials; import edu.tamu.weaver.auth.annotation.WeaverUser; @@ -50,7 +52,18 @@ public class UserController { @RequestMapping("/credentials") @PreAuthorize("hasRole('ROLE_STUDENT')") - public ApiResponse credentials(@WeaverCredentials Credentials credentials) { + public ApiResponse credentials(@WeaverCredentials Credentials credentials, @WeaverUser User user) { + // User.password is @JsonIgnore'd, so eligibility is computed here; the map is Map. + + Map allCredentials = credentials.getAllCredentials(); + + if (allCredentials == null) { + allCredentials = new HashMap(); + credentials.setAllCredentials(allCredentials); + } + + allCredentials.put("passwordEligible", String.valueOf(PasswordEligibilityRule.isEligible(user))); + return new ApiResponse(SUCCESS, credentials); } diff --git a/src/main/java/org/tdl/vireo/model/User.java b/src/main/java/org/tdl/vireo/model/User.java index d1a5c61ab7..4b4801c870 100644 --- a/src/main/java/org/tdl/vireo/model/User.java +++ b/src/main/java/org/tdl/vireo/model/User.java @@ -28,6 +28,7 @@ import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderColumn; +import javax.persistence.Transient; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; @@ -37,6 +38,7 @@ import org.tdl.vireo.model.listener.UserListener; import org.tdl.vireo.model.response.Views; import org.tdl.vireo.model.validation.UserValidator; +import org.tdl.vireo.utility.PasswordEligibilityRule; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @@ -542,4 +544,13 @@ public String getUsername() { return getEmail(); } + /** + * Whether this Account is eligible for Vireo-managed password operations. Deliberately has no + * {@code @JsonView}, so it serializes only on no-view listing endpoints. + */ + @Transient + public boolean isPasswordEligible() { + return PasswordEligibilityRule.isEligible(password, netid); + } + } diff --git a/src/main/java/org/tdl/vireo/model/validation/ManagedConfigurationValidator.java b/src/main/java/org/tdl/vireo/model/validation/ManagedConfigurationValidator.java index ffaac06478..512abf0df3 100644 --- a/src/main/java/org/tdl/vireo/model/validation/ManagedConfigurationValidator.java +++ b/src/main/java/org/tdl/vireo/model/validation/ManagedConfigurationValidator.java @@ -1,20 +1,33 @@ package org.tdl.vireo.model.validation; +import org.tdl.vireo.config.constant.ConfigurationName; +import org.tdl.vireo.model.ManagedConfiguration; + import edu.tamu.weaver.validation.model.InputValidationType; +import edu.tamu.weaver.validation.model.ValidatingEntity; +import edu.tamu.weaver.validation.results.ValidationResults; import edu.tamu.weaver.validation.validators.BaseModelValidator; import edu.tamu.weaver.validation.validators.InputValidator; public class ManagedConfigurationValidator extends BaseModelValidator { + private static final String APPLICATION_TYPE = "application"; + + private static final String VALUE_PROPERTY = "value"; + + private static final String EXPIRY_VALIDATION_MESSAGE = "Password Reset Link Expiry must be a whole number from 1 through 2147483647"; + + private final InputValidator valueMinimumLength; + public ManagedConfigurationValidator() { String nameProperty = "name"; this.addInputValidator(new InputValidator(InputValidationType.required, "Managed Configuration requires a name", nameProperty, true)); this.addInputValidator(new InputValidator(InputValidationType.minlength, "Managed Configuration name must be at least 2 characters", nameProperty, 2)); this.addInputValidator(new InputValidator(InputValidationType.maxlength, "Managed Configuration name cannot be more than 255 characters", nameProperty, 255)); - String valueProperty = "value"; - this.addInputValidator(new InputValidator(InputValidationType.required, "Managed Configuration requires a value", valueProperty, true)); - this.addInputValidator(new InputValidator(InputValidationType.minlength, "Managed Configuration value must be at least 2 characters", valueProperty, 2)); + this.addInputValidator(new InputValidator(InputValidationType.required, "Managed Configuration requires a value", VALUE_PROPERTY, true)); + valueMinimumLength = new InputValidator(InputValidationType.minlength, "Managed Configuration value must be at least 2 characters", VALUE_PROPERTY, 2); + this.addInputValidator(valueMinimumLength); String typeProperty = "type"; this.addInputValidator(new InputValidator(InputValidationType.required, "Managed Configuration requires a type", typeProperty, true)); @@ -23,4 +36,45 @@ public ManagedConfigurationValidator() { } + @Override + public ValidationResults validate(U model) { + if (!(model instanceof ManagedConfiguration) || !isPasswordResetExpiry((ManagedConfiguration) model)) { + return super.validate(model); + } + + ValidationResults results; + this.removeInputValidator(valueMinimumLength); + + try { + results = super.validate(model); + } finally { + this.addInputValidator(valueMinimumLength); + } + + ManagedConfiguration configuration = (ManagedConfiguration) model; + if (!isPositiveInteger(configuration.getValue())) { + results.setValid(false); + results.addMessage(VALUE_PROPERTY, InputValidationType.pattern.name(), EXPIRY_VALIDATION_MESSAGE); + } + + return results; + } + + private static boolean isPasswordResetExpiry(ManagedConfiguration configuration) { + return ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS.equals(configuration.getName()) + && APPLICATION_TYPE.equals(configuration.getType()); + } + + private static boolean isPositiveInteger(String value) { + if (value == null || !value.matches("[1-9][0-9]*")) { + return false; + } + + try { + return Integer.parseInt(value) > 0; + } catch (NumberFormatException e) { + return false; + } + } + } diff --git a/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java b/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java new file mode 100644 index 0000000000..e0417579d1 --- /dev/null +++ b/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java @@ -0,0 +1,109 @@ +package org.tdl.vireo.service; + +import java.time.Clock; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; + +import javax.mail.MessagingException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.tdl.vireo.model.EmailTemplate; +import org.tdl.vireo.model.User; +import org.tdl.vireo.model.repo.EmailTemplateRepo; +import org.tdl.vireo.utility.TemplateUtility; + +/** + * Sends credential-change notifications. + * + * Notifications are advisory: the change has already been persisted, so a missing template or mail + * failure is logged and swallowed. Reset-initiation mail is not sent here because it must report + * mail failures to the administrator; only the template lookup is shared. + */ +@Service +public class CredentialNotificationService { + + public static final String PASSWORD_RESET_REQUEST_TEMPLATE = "SYSTEM Password Reset Request"; + + public static final String PASSWORD_CHANGED_TEMPLATE = "SYSTEM Password Changed"; + + private static final String PASSWORD_CHANGED_NOTIFICATION = "password-changed notification"; + + private static final String CHANGE_TIME_PARAMETER = "CHANGE_TIME"; + + private static final DateTimeFormatter CHANGE_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'").withZone(ZoneOffset.UTC); + + private static final Logger LOG = LoggerFactory.getLogger(CredentialNotificationService.class); + + @Autowired + private EmailTemplateRepo emailTemplateRepo; + + @Autowired + private TemplateUtility templateUtility; + + @Autowired + private VireoEmailSender emailSender; + + private Clock clock = Clock.systemUTC(); + + /** + * Notifies the holder of an Account that its password changed. Never throws; no password or + * token appears in the log or message body. + */ + public void notifyPasswordChanged(User user) { + if (user == null) { + LOG.warn("No account supplied, skipping the " + PASSWORD_CHANGED_NOTIFICATION + "."); + + return; + } + + String recipient = user.getEmail(); + + if (recipient == null || recipient.trim().isEmpty()) { + LOG.warn("No email address on account '" + user.getId() + "', skipping the " + PASSWORD_CHANGED_NOTIFICATION + "."); + + return; + } + + EmailTemplate emailTemplate = resolveTemplate(PASSWORD_CHANGED_TEMPLATE); + + if (emailTemplate == null) { + LOG.warn("Skipping the " + PASSWORD_CHANGED_NOTIFICATION + " for account '" + recipient + "', because the email template '" + PASSWORD_CHANGED_TEMPLATE + "' is not installed."); + + return; + } + + String content = templateUtility.templateParameters(emailTemplate.getMessage(), new String[][] { { CHANGE_TIME_PARAMETER, formatChangeTime() } }); + + try { + emailSender.sendEmail(recipient, emailTemplate.getSubject(), content); + } catch (MessagingException e) { + LOG.warn("Unable to send the " + PASSWORD_CHANGED_NOTIFICATION + " to account '" + recipient + "', because: " + e.getMessage()); + } + } + + /** + * Resolves an email template by name, preferring a custom row over the system row. + * + * @return The template, or null (logged) when neither exists. + */ + public EmailTemplate resolveTemplate(String name) { + EmailTemplate emailTemplate = emailTemplateRepo.findByNameOverride(name); + + if (emailTemplate == null) { + LOG.warn("No email template found named '" + name + "'."); + + return null; + } + + return emailTemplate; + } + + /** Formats the current time in UTC, labelled as such, for the {@code CHANGE_TIME} parameter. */ + private String formatChangeTime() { + return CHANGE_TIME_FORMAT.format(clock.instant()); + } + +} diff --git a/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java b/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java new file mode 100644 index 0000000000..de42d354d2 --- /dev/null +++ b/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java @@ -0,0 +1,113 @@ +package org.tdl.vireo.service; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.tdl.vireo.config.constant.ConfigurationName; +import org.tdl.vireo.model.repo.ConfigurationRepo; + +/** + * Resolves the password feature settings and reports feature availability. + * + * Settings are read on every call and never cached, so an administrator save takes effect without + * a restart. + */ +@Service +public class PasswordFeatureAvailabilityService { + + public static final int DEFAULT_RESET_EXPIRY_HOURS = 24; + + private static final String APPLICATION_TYPE = "application"; + + private static final Logger LOG = LoggerFactory.getLogger(PasswordFeatureAvailabilityService.class); + + @Autowired + private ConfigurationRepo configurationRepo; + + /** Resolves {@code auth.pass.enabled}; false when absent or unrecognised. */ + public boolean isPasswordLoginEnabled() { + return resolveBoolean(getRawValue(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED), ConfigurationName.APPLICATION_AUTH_PASS_ENABLED); + } + + /** Resolves {@code auth.pass.change.enabled}; false when absent or unrecognised. */ + public boolean isChangeEnabled() { + return resolveBoolean(getRawValue(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED), ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED); + } + + /** Resolves {@code auth.pass.reset.enabled}; false when absent or unrecognised. */ + public boolean isResetEnabled() { + return resolveBoolean(getRawValue(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED), ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED); + } + + /** True only when both {@code auth.pass.enabled} and {@code auth.pass.change.enabled} are true. */ + public boolean isChangeAvailable() { + return isPasswordLoginEnabled() && isChangeEnabled(); + } + + /** True only when both {@code auth.pass.enabled} and {@code auth.pass.reset.enabled} are true. */ + public boolean isResetAvailable() { + return isPasswordLoginEnabled() && isResetEnabled(); + } + + /** + * Resolves {@code auth.pass.reset.expiryHours}. A value that is absent, not an integer, or below + * 1 yields {@link #DEFAULT_RESET_EXPIRY_HOURS}; the stored value is left unchanged. + */ + public int getResetExpiryHours() { + String raw = getRawValue(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS); + + if (raw == null) { + LOG.debug("No value stored for '" + ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS + "', using " + DEFAULT_RESET_EXPIRY_HOURS + "."); + + return DEFAULT_RESET_EXPIRY_HOURS; + } + + int hours; + + try { + hours = Integer.parseInt(raw.trim()); + } catch (NumberFormatException e) { + LOG.warn("Rejected value '" + raw + "' for '" + ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS + "', using " + DEFAULT_RESET_EXPIRY_HOURS + "."); + + return DEFAULT_RESET_EXPIRY_HOURS; + } + + if (hours < 1) { + LOG.warn("Rejected value '" + raw + "' for '" + ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS + "', using " + DEFAULT_RESET_EXPIRY_HOURS + "."); + + return DEFAULT_RESET_EXPIRY_HOURS; + } + + return hours; + } + + /** + * Resolves a raw value as a boolean, ignoring whitespace and case. Absent or unrecognised values + * resolve false (unrecognised ones are logged). Visible for test. + */ + static boolean resolveBoolean(String raw, String settingName) { + if (raw == null) { + LOG.debug("No value stored for '" + settingName + "', treating as false."); + + return false; + } + + String trimmed = raw.trim(); + + if (trimmed.equalsIgnoreCase("true")) { + return true; + } + + if (!trimmed.equalsIgnoreCase("false")) { + LOG.warn("Rejected value '" + raw + "' for '" + settingName + "', treating as false."); + } + + return false; + } + + private String getRawValue(String settingName) { + return configurationRepo.getValueByNameAndType(settingName, APPLICATION_TYPE); + } + +} diff --git a/src/main/java/org/tdl/vireo/service/ResetTokenService.java b/src/main/java/org/tdl/vireo/service/ResetTokenService.java new file mode 100644 index 0000000000..852b11457c --- /dev/null +++ b/src/main/java/org/tdl/vireo/service/ResetTokenService.java @@ -0,0 +1,207 @@ +package org.tdl.vireo.service; + +import java.nio.charset.StandardCharsets; +import java.security.InvalidKeyException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.time.Clock; +import java.time.DateTimeException; +import java.time.Duration; +import java.time.Instant; +import java.util.Base64; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.tdl.vireo.model.User; +import org.tdl.vireo.model.repo.UserRepo; + +/** + * Builds and verifies self-contained, signed password reset tokens. + * + * Nothing about a reset is persisted. The token carries all of its own state in a signed payload, + * built entirely from {@link javax.crypto.Mac} and {@link java.util.Base64} in the JDK (no new + * dependency). + * + *
+ * token         = base64url(payload) + "." + base64url(signature)
+ * payload       = email + "|" + bindingValue + "|" + issuedAtEpochSeconds   (UTF-8 bytes)
+ * signature     = HMAC-SHA256(key = signingSecret, message = base64url(payload) as US-ASCII bytes)
+ * bindingValue  = base64url(HMAC-SHA256(key = signingSecret, message = storedPasswordHash UTF-8 bytes))
+ * 
+ * + * The binding value ties the token to the stored password hash: any stored-password change + * re-salts the hash, so the binding derived at verification time no longer matches, invalidating + * the token (single use plus cross-invalidation of every sibling). + */ +@Service +public class ResetTokenService { + + private static final String HMAC_ALGORITHM = "HmacSHA256"; + + private static final Logger LOG = LoggerFactory.getLogger(ResetTokenService.class); + + @Value("${app.security.secret}") + private String signingSecret; + + @Autowired + private UserRepo userRepo; + + @Autowired + private PasswordFeatureAvailabilityService availabilityService; + + /** Swappable with {@code ReflectionTestUtils.setField} for expiry-boundary tests. */ + private Clock clock = Clock.systemUTC(); + + /** + * Builds a signed reset token for the given Account. + * + * @param user the Account to issue a token for + * @return the encoded token string + */ + public String construct(User user) { + String email = user.getEmail(); + String storedHash = user.getPassword(); + + String bindingValue = deriveBindingValue(storedHash); + + Instant issuedAt = clock.instant(); + long issuedAtEpochSeconds = issuedAt.getEpochSecond(); + + String payload = email + "|" + bindingValue + "|" + issuedAtEpochSeconds; + byte[] payloadBytes = payload.getBytes(StandardCharsets.UTF_8); + + String encodedPayload = base64UrlEncode(payloadBytes); + + byte[] signature = hmacSha256(encodedPayload.getBytes(StandardCharsets.US_ASCII)); + + return encodedPayload + "." + base64UrlEncode(signature); + } + + /** + * Verifies a reset token. Malformed token encoding or content returns an invalid result rather + * than propagating a parsing exception. + * + * The expiry check runs last, so {@link ResetTokenVerification.Status#EXPIRED} is reachable only + * for a genuine unredeemed token whose signature verified and binding still matches. + * + * @param token the encoded token string + * @return the verification outcome + */ + public ResetTokenVerification verify(String token) { + if (token == null || token.trim().isEmpty()) { + return ResetTokenVerification.invalid(); + } + + String[] segments = token.split("\\.", -1); + if (segments.length != 2 || segments[0].isEmpty() || segments[1].isEmpty()) { + return ResetTokenVerification.invalid(); + } + + String encodedPayload = segments[0]; + String encodedSignature = segments[1]; + + byte[] submittedSignature; + try { + submittedSignature = base64UrlDecode(encodedSignature); + } catch (IllegalArgumentException e) { + return ResetTokenVerification.invalid(); + } + + byte[] expectedSignature = hmacSha256(encodedPayload.getBytes(StandardCharsets.US_ASCII)); + if (!MessageDigest.isEqual(submittedSignature, expectedSignature)) { + return ResetTokenVerification.invalid(); + } + + String payload; + try { + byte[] payloadBytes = base64UrlDecode(encodedPayload); + payload = new String(payloadBytes, StandardCharsets.UTF_8); + } catch (IllegalArgumentException e) { + return ResetTokenVerification.invalid(); + } + + int lastPipe = payload.lastIndexOf('|'); + if (lastPipe < 0) { + return ResetTokenVerification.invalid(); + } + int priorPipe = payload.lastIndexOf('|', lastPipe - 1); + if (priorPipe < 0) { + return ResetTokenVerification.invalid(); + } + + String email = payload.substring(0, priorPipe); + String bindingValue = payload.substring(priorPipe + 1, lastPipe); + String issuedAtText = payload.substring(lastPipe + 1); + + Instant issuedAt; + try { + long issuedAtEpochSeconds = Long.parseLong(issuedAtText); + issuedAt = Instant.ofEpochSecond(issuedAtEpochSeconds); + } catch (NumberFormatException | DateTimeException e) { + return ResetTokenVerification.invalid(); + } + + User user = userRepo.findByEmail(email); + if (user == null || user.getPassword() == null) { + return ResetTokenVerification.invalid(); + } + + String currentBinding = deriveBindingValue(user.getPassword()); + if (!MessageDigest.isEqual( + currentBinding.getBytes(StandardCharsets.UTF_8), + bindingValue.getBytes(StandardCharsets.UTF_8))) { + return ResetTokenVerification.invalid(); + } + + int expiryHours = availabilityService.getResetExpiryHours(); + + Duration elapsed = Duration.between(issuedAt, clock.instant()); + if (elapsed.isNegative()) { + return ResetTokenVerification.invalid(); + } + if (elapsed.toHours() >= expiryHours) { + return ResetTokenVerification.expired(); + } + + return ResetTokenVerification.valid(email, issuedAt); + } + + /** + * Derives the binding value for a stored password hash: + * {@code base64url(HMAC-SHA256(signingSecret, storedPasswordHash UTF-8 bytes))}. + * + * @param storedPasswordHash the stored, encoded password + * @return the base64url-encoded binding value + */ + public String deriveBindingValue(String storedPasswordHash) { + byte[] mac = hmacSha256(storedPasswordHash.getBytes(StandardCharsets.UTF_8)); + return base64UrlEncode(mac); + } + + private byte[] hmacSha256(byte[] message) { + try { + Mac mac = Mac.getInstance(HMAC_ALGORITHM); + mac.init(new SecretKeySpec(signingSecret.getBytes(StandardCharsets.UTF_8), HMAC_ALGORITHM)); + return mac.doFinal(message); + } catch (NoSuchAlgorithmException | InvalidKeyException e) { + // HmacSHA256 is guaranteed present on every JVM and the key is non-empty; this is unreachable. + LOG.error("Unable to compute HMAC-SHA256 for reset token", e); + throw new IllegalStateException(e); + } + } + + private static String base64UrlEncode(byte[] bytes) { + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static byte[] base64UrlDecode(String value) { + return Base64.getUrlDecoder().decode(value); + } + +} diff --git a/src/main/java/org/tdl/vireo/service/ResetTokenVerification.java b/src/main/java/org/tdl/vireo/service/ResetTokenVerification.java new file mode 100644 index 0000000000..d649b8138b --- /dev/null +++ b/src/main/java/org/tdl/vireo/service/ResetTokenVerification.java @@ -0,0 +1,71 @@ +package org.tdl.vireo.service; + +import java.time.Instant; + +/** + * Outcome of verifying a password reset token. + * + * Only three statuses exist. A redeemed token and a token made stale by an unrelated change are + * cryptographically indistinguishable, so no third failure status could be populated honestly: + * every non-expiry failure is {@link Status#INVALID}. + * + * The {@link #getEmail()} and {@link #getIssuedAt()} accessors are populated only when the status + * is {@link Status#VALID}; both failure factories leave them null. + */ +public final class ResetTokenVerification { + + /** The three possible verification outcomes. */ + public enum Status { + VALID, + EXPIRED, + INVALID + } + + private final Status status; + + private final String email; + + private final Instant issuedAt; + + private ResetTokenVerification(Status status, String email, Instant issuedAt) { + this.status = status; + this.email = email; + this.issuedAt = issuedAt; + } + + /** + * A successful verification, carrying the email and the issued-at instant read from the token. + */ + public static ResetTokenVerification valid(String email, Instant issuedAt) { + return new ResetTokenVerification(Status.VALID, email, issuedAt); + } + + /** A token whose signature and binding verified but which has aged past its expiry window. */ + public static ResetTokenVerification expired() { + return new ResetTokenVerification(Status.EXPIRED, null, null); + } + + /** Any other failure: malformed, tampered, unknown account, or invalidated by a password change. */ + public static ResetTokenVerification invalid() { + return new ResetTokenVerification(Status.INVALID, null, null); + } + + public Status getStatus() { + return status; + } + + public boolean isValid() { + return status == Status.VALID; + } + + /** The email carried by the token; null unless the status is {@link Status#VALID}. */ + public String getEmail() { + return email; + } + + /** The instant the token was issued; null unless the status is {@link Status#VALID}. */ + public Instant getIssuedAt() { + return issuedAt; + } + +} diff --git a/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java b/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java new file mode 100644 index 0000000000..179bef5d88 --- /dev/null +++ b/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java @@ -0,0 +1,34 @@ +package org.tdl.vireo.utility; + +import org.tdl.vireo.model.User; + +/** + * Classifies an Account as eligible for Vireo-managed password operations. Reads only + * {@code User.password} and {@code User.netid}. + * + * Static and stateless so it works under the {@code @InjectMocks} wiring used by controller tests. + */ +public final class PasswordEligibilityRule { + + private PasswordEligibilityRule() { + } + + /** Eligible only if the password has a non-whitespace character and the netid is null. */ + public static boolean isEligible(User user) { + if (user == null) { + return false; + } + + return isEligible(user.getPassword(), user.getNetid()); + } + + /** Field-level form of {@link #isEligible(User)}. */ + public static boolean isEligible(String password, String netid) { + if (netid != null) { + return false; + } + + return password != null && !password.trim().isEmpty(); + } + +} diff --git a/src/main/java/org/tdl/vireo/utility/PasswordValidator.java b/src/main/java/org/tdl/vireo/utility/PasswordValidator.java new file mode 100644 index 0000000000..61bc1f5201 --- /dev/null +++ b/src/main/java/org/tdl/vireo/utility/PasswordValidator.java @@ -0,0 +1,74 @@ +package org.tdl.vireo.utility; + +/** + * Decides whether a candidate password is acceptable: non-blank with a trimmed length of at least + * {@value #MINIMUM_TRIMMED_LENGTH}, the same rule as {@code AuthController.registration}. + * + * Static and stateless so it works under the {@code @InjectMocks} wiring used by controller tests. + */ +public final class PasswordValidator { + + /** The outcome of a validation; {@code ACCEPTED} is the only accepting value. */ + public enum Result { + ACCEPTED, MISSING, TOO_SHORT, MISMATCH + } + + /** The minimum acceptable trimmed length. */ + public static final int MINIMUM_TRIMMED_LENGTH = 6; + + private PasswordValidator() { + } + + /** Validates a candidate with no confirmation: {@code MISSING}, {@code TOO_SHORT}, or {@code ACCEPTED}. */ + public static Result validate(String candidate) { + if (candidate == null || candidate.trim().length() == 0) { + return Result.MISSING; + } + + if (candidate.trim().length() < MINIMUM_TRIMMED_LENGTH) { + return Result.TOO_SHORT; + } + + return Result.ACCEPTED; + } + + /** + * Validates a candidate against its confirmation, checking {@code MISSING}, {@code MISMATCH}, + * then {@code TOO_SHORT} (the order {@code AuthController.registration} used). The comparison + * is on untrimmed values. + */ + public static Result validate(String candidate, String confirmation) { + if (candidate == null || candidate.trim().length() == 0) { + return Result.MISSING; + } + + if (!candidate.equals(confirmation)) { + return Result.MISMATCH; + } + + if (candidate.trim().length() < MINIMUM_TRIMMED_LENGTH) { + return Result.TOO_SHORT; + } + + return Result.ACCEPTED; + } + + /** + * Returns the original {@code AuthController} message for a rejection, or null for + * {@code ACCEPTED}. The {@code TOO_SHORT} text misstates the rule but is kept verbatim to + * preserve existing responses. + */ + public static String messageFor(Result result) { + switch (result) { + case MISSING: + return "Registration requires a password!"; + case MISMATCH: + return "The passwords do not match!"; + case TOO_SHORT: + return "Password must be greater than 6 characters!"; + default: + return null; + } + } + +} diff --git a/src/main/resources/emails/SYSTEM_Password_Changed.email b/src/main/resources/emails/SYSTEM_Password_Changed.email new file mode 100644 index 0000000000..be60cbb5af --- /dev/null +++ b/src/main/resources/emails/SYSTEM_Password_Changed.email @@ -0,0 +1,14 @@ +# Email sent to a Vireo user after the password on that user's account +# changes, whether the user changed it or a reset link was redeemed. +# +# Parameters: {CHANGE_TIME} is expanded to the time of the change +# +Subject: Vireo Password Changed +The password on your Vireo account was changed on {CHANGE_TIME}. + +If you made this change, no action is needed. + +If you did not make this change, please email +vireo@myuniversity.edu or call us at xxx-555-xxxx right away. + +The Vireo Team diff --git a/src/main/resources/emails/SYSTEM_Password_Reset_Request.email b/src/main/resources/emails/SYSTEM_Password_Reset_Request.email new file mode 100644 index 0000000000..652f1855d8 --- /dev/null +++ b/src/main/resources/emails/SYSTEM_Password_Reset_Request.email @@ -0,0 +1,21 @@ +# Email sent to a Vireo user when an administrator starts a password reset +# for that user's account. +# +# Parameters: {RESET_URL} is expanded to a special URL +# +Subject: Vireo Password Reset +A password reset was started for your Vireo account. To choose a new +password, please click the link below: + + {RESET_URL} + +This link works once and stops working after a limited time. If it no +longer works, ask your Vireo administrator to send a new one. + +If you were not expecting this message, you do not need to do anything. +Your password has not been changed. + +If you need assistance with your account, please email +vireo@myuniversity.edu or call us at xxx-555-xxxx. + +The Vireo Team diff --git a/src/main/resources/settings/SYSTEM_Defaults.json b/src/main/resources/settings/SYSTEM_Defaults.json index beb2f77712..32ed08f143 100644 --- a/src/main/resources/settings/SYSTEM_Defaults.json +++ b/src/main/resources/settings/SYSTEM_Defaults.json @@ -23,6 +23,18 @@ }, { "new_submission_header_text": "Choose Your Organization" + }, + { + "auth.pass.enabled": true + }, + { + "auth.pass.change.enabled": false + }, + { + "auth.pass.reset.enabled": false + }, + { + "auth.pass.reset.expiryHours": 24 } ], "footer": [ diff --git a/src/main/webapp/app/config/apiMapping.js b/src/main/webapp/app/config/apiMapping.js index 99c5f53677..0c99981373 100644 --- a/src/main/webapp/app/config/apiMapping.js +++ b/src/main/webapp/app/config/apiMapping.js @@ -961,6 +961,16 @@ var apiMapping = { 'controller': 'user', 'method': 'page' }, + changePassword: { + 'endpoint': '/private/queue', + 'controller': 'password', + 'method': 'change' + }, + resetPassword: { + 'endpoint': '/private/queue', + 'controller': 'password', + 'method': 'reset' + }, createListen: { 'endpoint': '/channel', 'controller': 'user/create' diff --git a/src/main/webapp/app/config/routes.js b/src/main/webapp/app/config/routes.js index 50e461ea3a..9adc2ee3c0 100644 --- a/src/main/webapp/app/config/routes.js +++ b/src/main/webapp/app/config/routes.js @@ -58,6 +58,9 @@ vireo.config(function ($locationProvider, $routeProvider) { templateUrl: 'views/signup.html', controller: 'LocalAccountSignupController' }). + when('/reset-password', { + templateUrl: 'views/resetPassword.html' + }). when('/login', { templateUrl: 'views/login.html', controller: 'LocalLoginController' diff --git a/src/main/webapp/app/controllers/changePasswordController.js b/src/main/webapp/app/controllers/changePasswordController.js new file mode 100644 index 0000000000..53bba11b17 --- /dev/null +++ b/src/main/webapp/app/controllers/changePasswordController.js @@ -0,0 +1,92 @@ +vireo.controller('ChangePasswordController', function ($controller, $scope, UserRepo) { + + angular.extend(this, $controller('AbstractController', { $scope: $scope })); + + $scope.userRepo = UserRepo; + + $scope.passwordChange = { + currentPassword: '', + newPassword: '', + confirm: '' + }; + + // Feedback shown above the Current Password field. 'type' drives the Bootstrap alert class. + $scope.passwordChangeFeedback = null; + + var GENERIC_SUCCESS = 'Your password has been changed.'; + var GENERIC_FAILURE = 'Your password could not be changed.'; + + // For this REST-backed endpoint WsApi.fetch always resolves (even for an INVALID response) and + // only rejects on a transport error. The ApiResponse arrives as a JSON string in response.body; + // normalize it so success/failure is driven by meta.status, not by resolve vs reject. + var parseResponse = function (response) { + if (response && typeof response.body === 'string') { + try { + return angular.fromJson(response.body); + } catch (e) { + return response; + } + } + + if (response && response.payload) { + return response.payload; + } + + return response; + }; + + var messageFrom = function (apiRes, fallback) { + var message = apiRes && apiRes.meta ? apiRes.meta.message : undefined; + + return typeof message === 'string' && message.length > 0 ? message : fallback; + }; + + // Matches the server's resolution: trim, case-insensitive compare against 'true'. + var isEnabled = function (name) { + var application = $scope.settings && $scope.settings.configurable ? $scope.settings.configurable.application : undefined; + var setting = application ? application[name] : undefined; + var value = setting ? setting.value : undefined; + return typeof value === 'string' && value.trim().toLowerCase() === 'true'; + }; + + // allCredentials is a Map on the server, so compare against the String. + var isEligible = function () { + return !!($scope.user && $scope.user.allCredentials && $scope.user.allCredentials.passwordEligible === 'true'); + }; + + $scope.changePasswordAvailable = function () { + return isEnabled('auth.pass.enabled') && isEnabled('auth.pass.change.enabled') && isEligible(); + }; + + var clear = function () { + $scope.passwordChange.currentPassword = ''; + $scope.passwordChange.newPassword = ''; + $scope.passwordChange.confirm = ''; + }; + + $scope.submitPasswordChange = function () { + // Clear stale feedback so each submit starts fresh. + $scope.passwordChangeFeedback = null; + + return UserRepo.changePassword( + $scope.passwordChange.currentPassword, + $scope.passwordChange.newPassword, + $scope.passwordChange.confirm + ).then(function (response) { + var apiRes = parseResponse(response); + var succeeded = apiRes && apiRes.meta && apiRes.meta.status === 'SUCCESS'; + + if (succeeded) { + $scope.passwordChangeFeedback = { type: 'success', message: messageFrom(apiRes, GENERIC_SUCCESS) }; + } else { + $scope.passwordChangeFeedback = { type: 'danger', message: messageFrom(apiRes, GENERIC_FAILURE) }; + } + + clear(); + }, function (response) { + $scope.passwordChangeFeedback = { type: 'danger', message: messageFrom(parseResponse(response), GENERIC_FAILURE) }; + clear(); + }); + }; + +}); diff --git a/src/main/webapp/app/controllers/resetPasswordController.js b/src/main/webapp/app/controllers/resetPasswordController.js new file mode 100644 index 0000000000..542632504b --- /dev/null +++ b/src/main/webapp/app/controllers/resetPasswordController.js @@ -0,0 +1,36 @@ +vireo.controller('ResetPasswordController', function ($controller, $location, $scope, $window, PasswordResetService, StorageService) { + + angular.extend(this, $controller('AbstractController', { $scope: $scope })); + + // Mirrors weaver's RegistrationController reading the token from /register?token=. + $scope.token = $location.search().token; + + $scope.resetPassword = { + newPassword: '', + confirm: '' + }; + + // RestApi.anonymousPost already routes the ApiResponse meta through AlertService, so the + // expiry-specific and generic failure messages surface without any extra handling here. + $scope.submitResetPassword = function () { + return PasswordResetService.redeem($scope.token, $scope.resetPassword.newPassword, $scope.resetPassword.confirm).then(function (data) { + if (data && data.meta && data.meta.status === 'SUCCESS') { + $scope.resetPassword.newPassword = ''; + $scope.resetPassword.confirm = ''; + + // Set the post-sign-in destination so the user lands on My Profile after signing + // in with the new password, rather than back on this public page. The value is + // consumed as a full browser path (context prefix included), so derive the prefix + // by stripping the Angular route ($location.path()) off the end of the full path + // ($window.location.pathname); this keeps the redirect correct under a context path. + var currentPath = $window.location.pathname; + var contextPath = currentPath.slice(0, currentPath.length - $location.path().length); + + StorageService.set('post_authorize_url', contextPath + '/myprofile'); + + $location.path('/login'); + } + }); + }; + +}); diff --git a/src/main/webapp/app/controllers/settingsController.js b/src/main/webapp/app/controllers/settingsController.js index 461356c4b8..d4c3ff935a 100644 --- a/src/main/webapp/app/controllers/settingsController.js +++ b/src/main/webapp/app/controllers/settingsController.js @@ -82,6 +82,37 @@ vireo.controller("SettingsController", function ($controller, $injector, $scope, "false": "No" }]; + // PASSWORD MANAGEMENT + $scope.changePasswordToggleOptions = [{ + "true": "Enabled" + }, { + "false": "Disabled" + }]; + + $scope.resetPasswordToggleOptions = [{ + "true": "Enabled" + }, { + "false": "Disabled" + }]; + + // Enforce the server's positive Java integer range before saving the setting. + $scope.expiryHoursValidations = { + "value": { + "required": { + "type": "required", + "message": "Password Reset Link Expiry is required", + "property": "value", + "value": true + }, + "pattern": { + "type": "pattern", + "message": "Password Reset Link Expiry must be a whole number from 1 through 2147483647", + "property": "value", + "value": "^(?:[1-9][0-9]{0,8}|1[0-9]{9}|20[0-9]{8}|21[0-3][0-9]{7}|214[0-6][0-9]{6}|2147[0-3][0-9]{5}|21474[0-7][0-9]{4}|214748[0-2][0-9]{3}|2147483[0-5][0-9]{2}|21474836[0-3][0-9]|214748364[0-7])$" + } + } + }; + var userSettingsValidations = { "displayName": { "minlength": { diff --git a/src/main/webapp/app/controllers/userRepoController.js b/src/main/webapp/app/controllers/userRepoController.js index 6ee9acb50b..ec14111008 100644 --- a/src/main/webapp/app/controllers/userRepoController.js +++ b/src/main/webapp/app/controllers/userRepoController.js @@ -1,4 +1,4 @@ -vireo.controller('UserRepoController', function ($controller, $location, $scope, $timeout, TableFactory, User, UserRepo, UserService) { +vireo.controller('UserRepoController', function ($controller, $location, $scope, $timeout, ManagedConfigurationRepo, TableFactory, User, UserRepo, UserService) { angular.extend(this, $controller('AbstractController', {$scope: $scope})); @@ -6,6 +6,10 @@ vireo.controller('UserRepoController', function ($controller, $location, $scope, $scope.userRepo = UserRepo; + // The /users route names no controller, so no SettingsController sits above this one and + // $scope.settings does not exist here; read the application settings directly. + $scope.configurable = ManagedConfigurationRepo.getAll(); + $scope.table = TableFactory.buildTable({ pageNumber: sessionStorage.getItem('users-page') ? sessionStorage.getItem('users-page') : 1, pageSize: sessionStorage.getItem('users-size') ? sessionStorage.getItem('users-size') : 10, @@ -41,6 +45,12 @@ vireo.controller('UserRepoController', function ($controller, $location, $scope, property: 'role', filterable: true, sortable: true + }, + { + gloss: 'Password', + property: 'passwordReset', + filterable: false, + sortable: false }], activeSort: [{ property: 'role', @@ -48,6 +58,29 @@ vireo.controller('UserRepoController', function ($controller, $location, $scope, }] }; + // Matches the server's resolution: trim, case-insensitive compare against 'true'. + var isEnabled = function (name) { + var application = $scope.configurable ? $scope.configurable.application : undefined; + var setting = application ? application[name] : undefined; + var value = setting ? setting.value : undefined; + return typeof value === 'string' && value.trim().toLowerCase() === 'true'; + }; + + $scope.passwordResetAvailable = function () { + return isEnabled('auth.pass.enabled') && isEnabled('auth.pass.reset.enabled'); + }; + + $scope.confirmResetPassword = function (user) { + $scope.userToResetPassword = user; + $scope.openModal('#confirmResetPassword'); + }; + + $scope.resetPassword = function () { + UserRepo.resetPassword($scope.userToResetPassword); + $scope.closeModal(); + $scope.userToResetPassword = null; + }; + $scope.roles = {}; $scope.updateRole = function(user, role) { diff --git a/src/main/webapp/app/repo/userRepo.js b/src/main/webapp/app/repo/userRepo.js index c895dbd854..d8182fd59a 100644 --- a/src/main/webapp/app/repo/userRepo.js +++ b/src/main/webapp/app/repo/userRepo.js @@ -8,6 +8,26 @@ vireo.repo("UserRepo", function UserRepo(User, WsApi) { return WsApi.fetch(endpoint); }; + userRepo.changePassword = function (currentPassword, newPassword, confirm) { + var endpoint = angular.extend({}, userRepo.mapping.changePassword, { + data: { + currentPassword: currentPassword, + newPassword: newPassword, + confirm: confirm + } + }); + + return WsApi.fetch(endpoint); + }; + + userRepo.resetPassword = function (user) { + var endpoint = angular.extend({}, userRepo.mapping.resetPassword, { + data: { email: user.email } + }); + + return WsApi.fetch(endpoint); + }; + userRepo.getAssignableUsers = function(page, size, name) { var assignable = []; diff --git a/src/main/webapp/app/services/passwordResetService.js b/src/main/webapp/app/services/passwordResetService.js new file mode 100644 index 0000000000..19a10d7b41 --- /dev/null +++ b/src/main/webapp/app/services/passwordResetService.js @@ -0,0 +1,17 @@ +// Redemption happens before sign-in, and the weaver User model (node_modules/@wvr/core) has no +// Vireo override, so this anonymous call needs its own Vireo-side service. +vireo.service('PasswordResetService', function (RestApi) { + + var PasswordResetService = this; + + PasswordResetService.redeem = function (token, newPassword, confirm) { + return RestApi.anonymousPost({ + controller: 'password', + method: 'reset/redeem', + data: { token: token, newPassword: newPassword, confirm: confirm } + }); + }; + + return PasswordResetService; + +}); diff --git a/src/main/webapp/app/views/admin/settings/application.html b/src/main/webapp/app/views/admin/settings/application.html index 3e7b9266d7..d99f4736ce 100644 --- a/src/main/webapp/app/views/admin/settings/application.html +++ b/src/main/webapp/app/views/admin/settings/application.html @@ -8,6 +8,7 @@

APPLICATION SETTINGS

CUSTOM ACTIONS CHECKLIST DEPOSIT LOCATIONS WHO HAS ACCESS + PASSWORD MANAGEMENT LOOK AND FEEL EMAIL TEMPLATES FOOTER LINKS diff --git a/src/main/webapp/app/views/admin/settings/application/passwordManagement.html b/src/main/webapp/app/views/admin/settings/application/passwordManagement.html new file mode 100644 index 0000000000..eb57433f47 --- /dev/null +++ b/src/main/webapp/app/views/admin/settings/application/passwordManagement.html @@ -0,0 +1,45 @@ +
+ +
+ +
+ + + + + + + +
+ +
+ +
+ +
+ + + + +
+ +
+ +
diff --git a/src/main/webapp/app/views/modals/users/confirmResetPassword.html b/src/main/webapp/app/views/modals/users/confirmResetPassword.html new file mode 100644 index 0000000000..41fd1dc0cb --- /dev/null +++ b/src/main/webapp/app/views/modals/users/confirmResetPassword.html @@ -0,0 +1,15 @@ + + + + + diff --git a/src/main/webapp/app/views/myprofile.html b/src/main/webapp/app/views/myprofile.html index 886d9343aa..88253babca 100644 --- a/src/main/webapp/app/views/myprofile.html +++ b/src/main/webapp/app/views/myprofile.html @@ -240,6 +240,61 @@

Preferences

+ +
+
+ +

Change Password

+ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +
+
+
+ +
+ +
+
+ diff --git a/src/main/webapp/app/views/resetPassword.html b/src/main/webapp/app/views/resetPassword.html new file mode 100644 index 0000000000..cfc81a5dbb --- /dev/null +++ b/src/main/webapp/app/views/resetPassword.html @@ -0,0 +1,41 @@ +
+ +
+ +

Reset Password

+
+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +
+
+ +
+ +
+ +
+ +
diff --git a/src/main/webapp/app/views/users.html b/src/main/webapp/app/views/users.html index 45d611d50d..502e14d136 100644 --- a/src/main/webapp/app/views/users.html +++ b/src/main/webapp/app/views/users.html @@ -15,6 +15,9 @@ + + + @@ -23,4 +26,10 @@ + + + diff --git a/src/test/java/org/tdl/vireo/ApplicationInitializationTest.java b/src/test/java/org/tdl/vireo/ApplicationInitializationTest.java index eeb5a53292..83c073fe7c 100644 --- a/src/test/java/org/tdl/vireo/ApplicationInitializationTest.java +++ b/src/test/java/org/tdl/vireo/ApplicationInitializationTest.java @@ -78,7 +78,7 @@ private void assertInMemorySystemData(boolean isReload) throws ClassNotFoundExce ? "Incorrect number of default setting types after reload" : "Incorrect number of default setting types"); - assertSettingsType(8, "application", isReload); + assertSettingsType(12, "application", isReload); assertSettingsType(4, "footer", isReload); assertSettingsType(2, "orcid", isReload); assertSettingsType(9, "proquest_umi_degree_code", isReload); diff --git a/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java b/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java index 2623b501b8..d1efd57fda 100644 --- a/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java @@ -6,6 +6,9 @@ import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import edu.tamu.weaver.response.ApiResponse; @@ -13,8 +16,12 @@ import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.Random; import java.util.stream.Stream; import javax.crypto.BadPaddingException; import javax.crypto.IllegalBlockSizeException; @@ -36,6 +43,7 @@ import org.tdl.vireo.model.repo.EmailTemplateRepo; import org.tdl.vireo.model.repo.UserRepo; import org.tdl.vireo.service.VireoEmailSender; +import org.tdl.vireo.utility.PasswordValidator; @ActiveProfiles(value = { "test", "isolated-test" }) public class AuthControllerTest extends AbstractControllerTest { @@ -315,4 +323,165 @@ private void setupDataMap() { data.put("userPassword", "userPassword"); data.put("confirm", data.get("userPassword")); } + + // The PasswordValidator retrofit preserves every registration outcome. Additive; existing tests above are unchanged. + + private static final long RETROFIT_GENERATOR_SEED = 20250101L; + + private static final int RETROFIT_RANDOM_CASE_COUNT = 48; + + private static final String REGISTRATION_SUCCESS_MESSAGE = "Registration was successfull. Please login."; + + /** Values crossed with themselves: missing, whitespace-only, the trimmed length 5/6 boundary, and untrimmed pass-through. */ + private static final List RETROFIT_PASSWORD_VALUES = Arrays.asList( + // Absent and whitespace-only. + null, + "", + " ", + "\t", + + // The rejected side of the boundary, and the ordering case. + "12345", + "54321", + "abcde", + + // Trimmed length 5 carried inside a raw length 6 value. + "abcde ", + + // The accepted side of the boundary, across character classes. + "123456", + "abcdef", + "ABCDEF", + " abcdef ", + + // Comfortably above the boundary. + "correct horse battery staple", + "\u00e9bcdef" + ); + + /** Full cross product of the values plus fixed-seed random pairs (equal, perturbed, mixed, null confirm). */ + protected static Stream provideRetrofitPasswordPairs() { + List cases = new ArrayList(); + + for (String password : RETROFIT_PASSWORD_VALUES) { + for (String confirm : RETROFIT_PASSWORD_VALUES) { + cases.add(Arguments.of(password, confirm)); + } + } + + Random random = new Random(RETROFIT_GENERATOR_SEED); + + for (int i = 0; i < RETROFIT_RANDOM_CASE_COUNT; i++) { + String password = RETROFIT_PASSWORD_VALUES.get(random.nextInt(RETROFIT_PASSWORD_VALUES.size())); + + String confirm; + + switch (random.nextInt(4)) { + case 0: + confirm = password; + break; + case 1: + confirm = perturbRetrofitValue(password, random); + break; + case 2: + confirm = RETROFIT_PASSWORD_VALUES.get(random.nextInt(RETROFIT_PASSWORD_VALUES.size())); + break; + default: + confirm = null; + break; + } + + cases.add(Arguments.of(password, confirm)); + } + + return cases.stream(); + } + + /** Alters one character so the result never equals the input. */ + private static String perturbRetrofitValue(String value, Random random) { + if (value == null || value.length() == 0) { + return "x"; + } + + char[] characters = value.toCharArray(); + + int position = random.nextInt(characters.length); + + characters[position] = characters[position] == 'x' ? 'y' : 'x'; + + return new String(characters); + } + + /** Transcription of the pre-retrofit inline rule; deliberately not a call to PasswordValidator, so it is an independent oracle. */ + private static String preRetrofitRejectionMessage(String password, String confirm) { + if (password == null || password.trim().length() == 0) { + return "Registration requires a password!"; + } + + if (!password.equals(confirm)) { + return "The passwords do not match!"; + } + + if (password.trim().length() < 6) { + return "Password must be greater than 6 characters!"; + } + + return null; + } + + /** The retrofitted handler gives the same status and message as the pre-retrofit rule, and an accepted password reaches the encoder untrimmed. */ + @ParameterizedTest(name = "[{index}] userPassword=''{0}'' confirm=''{1}''") + @MethodSource("provideRetrofitPasswordPairs") + public void testRegistrationRetrofitPreservesOutcomes(String password, String confirm) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { + String description = "userPassword '" + password + "' with confirm '" + confirm + "'"; + + String expectedMessage = preRetrofitRejectionMessage(password, confirm); + + PasswordValidator.Result result = PasswordValidator.validate(password, confirm); + + // Validator verdict matches the pre-retrofit rule. + assertEquals( + Boolean.valueOf(expectedMessage == null), + Boolean.valueOf(PasswordValidator.Result.ACCEPTED.equals(result)), + "Shared validator verdict for " + description); + + // Same message; messageFor returns null for ACCEPTED. + assertEquals(expectedMessage, PasswordValidator.messageFor(result), "Shared validator message for " + description); + + // Name gate is not under test, so satisfy it; the token lets an accepted candidate proceed. + data.put("firstName", "firstName"); + data.put("lastName", "lastName"); + data.put("token", "token"); + data.put("userPassword", password); + data.put("confirm", confirm); + + if (expectedMessage != null) { + ApiResponse response = authController.registration(data, parameters); + + assertEquals(ApiStatus.ERROR, response.getMeta().getStatus(), "Status for rejected " + description); + assertEquals(expectedMessage, response.getMeta().getMessage(), "Message for rejected " + description); + + // Rejection happens before token validation. + verifyNoInteractions(cryptoService); + verify(vireoUserCredentialsService, never()).createUserFromRegistration(any(), any(), any(), any()); + + return; + } + + // Warning the tokenDaysOld calculation is unsafe and can fail when the token time is less than the current time due to the subtraction. + String[] content = { "" + Instant.now().toEpochMilli(), "e@mail.com" }; + + when(cryptoService.validateGenericToken(anyString(), anyString())).thenReturn(content); + when(cryptoService.encodePassword(anyString())).thenReturn("encoded"); + when(vireoUserCredentialsService.createUserFromRegistration(anyString(), anyString(), anyString(), anyString())).thenReturn(user); + + ApiResponse response = authController.registration(data, parameters); + + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus(), "Status for accepted " + description); + assertEquals(REGISTRATION_SUCCESS_MESSAGE, response.getMeta().getMessage(), "Message for accepted " + description); + assertEquals(user, response.getPayload().get("User"), "Account returned for accepted " + description); + + // Reaches the encoder as submitted, padding included. + verify(cryptoService).encodePassword(password); + } } diff --git a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java new file mode 100644 index 0000000000..c4875f1d96 --- /dev/null +++ b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java @@ -0,0 +1,1366 @@ +package org.tdl.vireo.controller; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Method; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.slf4j.LoggerFactory; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import javax.mail.MessagingException; + +import org.tdl.vireo.config.constant.ConfigurationName; +import org.tdl.vireo.model.EmailTemplate; +import org.tdl.vireo.model.Role; +import org.tdl.vireo.model.User; +import org.tdl.vireo.model.repo.ConfigurationRepo; +import org.tdl.vireo.model.repo.UserRepo; +import org.tdl.vireo.service.CredentialNotificationService; +import org.tdl.vireo.service.PasswordFeatureAvailabilityService; +import org.tdl.vireo.service.ResetTokenService; +import org.tdl.vireo.service.ResetTokenVerification; +import org.tdl.vireo.service.VireoEmailSender; +import org.tdl.vireo.utility.PasswordValidator; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import edu.tamu.weaver.response.ApiResponse; +import edu.tamu.weaver.response.ApiStatus; +import edu.tamu.weaver.validation.results.ValidationResults; +import edu.tamu.weaver.validation.utility.ValidationUtility; + +/** + * Tests for {@code /password/change}, {@code /password/reset} and {@code /password/reset/redeem}. + * + * BCrypt is real only where a case succeeds; other cases use a cheap prefix-based fake hash. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +public class PasswordControllerTest extends AbstractControllerTest { + + private static final String APPLICATION_TYPE = "application"; + + private static final String CURRENT_PASSWORD = "currentpassword"; + + private static final String NEW_PASSWORD = "newpassword"; + + private static final String TOKEN = "tok.eyJ0b2tlbiI6Im5ldmVyLWxlYWstbWUifQ"; + + /** The sentinel standing for the stored hash of {@link #CURRENT_PASSWORD}. */ + private static final String HASHED_STORED_PASSWORD = "HASHED_STORED_PASSWORD"; + + /** A genuine BCrypt hash of {@link #CURRENT_PASSWORD}, computed once for the class. */ + private static final String REAL_HASH = new BCryptPasswordEncoder().encode(CURRENT_PASSWORD); + + private static final String FAKE_PREFIX = "fake-hash:"; + + private static final String FAKE_HASH = FAKE_PREFIX + CURRENT_PASSWORD; + + /** Raw password-login and {@code auth.pass.change.enabled} setting pairs, including near-miss spellings. */ + private static final String[][] AVAILABILITY_PAIRS = { + { "true", "true" }, + { " TRUE ", "True" }, + { "true", "false" }, + { "false", "true" }, + { "false", "false" }, + { null, "true" }, + { "true", null }, + { "yes", "true" }, + { "true", "1" }, + { "", "true" }, + { "true", " " }, + { "truex", "true" } + }; + + /** Stored-password shape paired with netid: the eligible shape, then each ineligible one. */ + private static final String[][] ELIGIBILITY_SHAPES = { + { HASHED_STORED_PASSWORD, null }, + { HASHED_STORED_PASSWORD, "netid1" }, + { HASHED_STORED_PASSWORD, "" }, + { "", null }, + { " ", null } + }; + + /** The supplied current password: the matching value, then each non-matching shape. */ + private static final String[] SUPPLIED_CURRENT_PASSWORDS = { + CURRENT_PASSWORD, + "notthecurrentpassword", + "", + " currentpassword ", + "CURRENTPASSWORD" + }; + + /** Candidate and confirmation pairs, including the length 5/6 boundary. */ + private static final String[][] CANDIDATE_PAIRS = { + { NEW_PASSWORD, NEW_PASSWORD }, + { "abcdef", "abcdef" }, + { "abcde", "abcde" }, + { NEW_PASSWORD, "newpasswordx" }, + { null, null }, + { NEW_PASSWORD, null }, + { " ", " " }, + { " padded ", " padded " } + }; + + /** Body keys that must be ignored; the authenticated principal is the only target. */ + private static final String[] FOREIGN_IDENTIFIER_KEYS = { + "email", "username", "userId", "id", "user", "netid", "targetEmail", "account", "principal" + }; + + /** Identifier value shapes, paired with the key names in rotation. */ + private static final String[] FOREIGN_IDENTIFIER_VALUES = { + "foreign@institution.edu", "manager@institution.edu", "email1", "2", "1", "99999", null, "", " ", "netid1", "foreign@institution.edu ", "EMAIL1" + }; + + /** Secret shapes used as the new password in one case and as a wrong current password in another. */ + private static final String[] SECRET_SHAPES = { "plainsecret", " spaced secret ", "p@ss|word.{x}", "Ünïcödé-sëcret", "0123456789abcdef", "UPPER-lower-123" }; + + /** Client-asserted body entries; the server must ignore them and re-derive availability and eligibility. */ + private static final List> CLIENT_CLAIM_BODIES = Arrays.asList( + new HashMap(), + claim("passwordEligible", "true"), + claim("changePasswordAvailable", "true"), + claim("eligible", "true"), + claim(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, "true"), + claim(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, "true"), + claim("force", "true"), + claim("netid", null) + ); + + private static Map claim(String key, String value) { + Map body = new HashMap<>(); + body.put(key, value); + + return body; + } + + @Mock + private ConfigurationRepo configurationRepo; + + @Mock + private UserRepo userRepo; + + @Mock + private CredentialNotificationService credentialNotificationService; + + @Mock + private ResetTokenService resetTokenService; + + @Mock + private VireoEmailSender emailSender; + + @InjectMocks + private PasswordController passwordController; + + private PasswordFeatureAvailabilityService availabilityService; + + private User user1; + + private String storedPassword; + + @BeforeEach + public void setup() { + availabilityService = new PasswordFeatureAvailabilityService(); + + ReflectionTestUtils.setField(availabilityService, "configurationRepo", configurationRepo); + ReflectionTestUtils.setField(passwordController, "availabilityService", availabilityService); + + user1 = new User("email1", "firstname1", "lastname1", Role.ROLE_STUDENT); + user1.setId(1L); + + storedPassword = FAKE_HASH; + + user1.setPassword(storedPassword); + user1.setNetid(null); + } + + @Test + public void testChangePasswordRejectsACurrentPasswordMismatch() { + stubSettings("true", "true"); + stubFakeCrypto(); + + ApiResponse response = passwordController.changePassword(user1, request("notthecurrentpassword", NEW_PASSWORD, NEW_PASSWORD)); + + assertRejected(response); + + Object payload = response.getPayload().get("ValidationResults"); + + assertNotNull(payload, "a current-password mismatch reports an authentication failure through ValidationResults"); + assertTrue(payload instanceof ValidationResults); + assertTrue(((ValidationResults) payload).getMessages().containsKey(ValidationUtility.BUSINESS_MESSAGE_KEY), "the failure rides under the business message key, matching AuthController.login"); + } + + @Test + public void testChangePasswordRejectsACandidateTheValidatorRejects() { + List rejectedCandidates = Arrays.asList( + new String[] { null, null }, + new String[] { " ", " " }, + new String[] { "short", "short" }, + new String[] { NEW_PASSWORD, "newpasswordx" } + ); + + for (String[] candidate : rejectedCandidates) { + setup(); + + stubSettings("true", "true"); + stubFakeCrypto(); + + ApiResponse response = passwordController.changePassword(user1, request(CURRENT_PASSWORD, candidate[0], candidate[1])); + + assertRejected(response); + + assertEquals(PasswordValidator.messageFor(PasswordValidator.validate(candidate[0], candidate[1])), response.getMeta().getMessage(), "the rejection carries the shared validator message for the cause"); + } + } + + @Test + public void testChangePasswordRequiresTheStudentRole() throws Exception { + // Spring Security rejects under-privileged callers before the handler runs. + Method handler = PasswordController.class.getMethod("changePassword", User.class, Map.class); + + PreAuthorize preAuthorize = handler.getAnnotation(PreAuthorize.class); + + assertNotNull(preAuthorize, "the handler must carry a @PreAuthorize expression"); + assertEquals("hasRole('ROLE_STUDENT')", preAuthorize.value()); + + RequestMapping requestMapping = handler.getAnnotation(RequestMapping.class); + + assertNotNull(requestMapping); + assertEquals("/change", requestMapping.value()[0]); + assertEquals(RequestMethod.POST, requestMapping.method()[0]); + } + + // The password is replaced only when availability, eligibility, current-password match and + // candidate validity all hold. Otherwise nothing is written, only the principal is ever + // written, and no password or token leaks into the response or log. Lookups by email, netid + // and id return a foreign Account so a handler honoring body identifiers would be caught. + @ParameterizedTest(name = "[{index}] {8}") + @MethodSource("provideChangeCases") + public void changeEnforcesItsGatesTargetsThePrincipalAndLeaksNothing(String passwordLoginRaw, String changeRaw, String storedShape, String netid, String currentSupplied, String newPassword, String confirm, Map extraFields, String label) throws Exception { + // Expectation derived independently of the handler's evaluation order. + boolean hashed = HASHED_STORED_PASSWORD.equals(storedShape); + boolean available = resolvesTrue(passwordLoginRaw) && resolvesTrue(changeRaw); + boolean eligible = netid == null && storedShape != null && !storedShape.trim().isEmpty(); + boolean currentMatches = eligible && hashed && CURRENT_PASSWORD.equals(currentSupplied); + boolean candidateAccepted = PasswordValidator.validate(newPassword, confirm) == PasswordValidator.Result.ACCEPTED; + boolean succeeds = available && eligible && currentMatches && candidateAccepted; + + stubSettings(passwordLoginRaw, changeRaw); + + if (succeeds) { + stubRealCrypto(); + } else { + stubFakeCrypto(); + } + + storedPassword = hashed ? (succeeds ? REAL_HASH : FAKE_HASH) : storedShape; + + user1.setPassword(storedPassword); + user1.setNetid(netid); + + User foreignUser = new User("foreign@institution.edu", "firstname2", "lastname2", Role.ROLE_STUDENT); + foreignUser.setId(2L); + foreignUser.setPassword("foreign-stored-password"); + + lenient().when(userRepo.findByEmail(anyString())).thenReturn(foreignUser); + lenient().when(userRepo.findByNetid(anyString())).thenReturn(foreignUser); + lenient().when(userRepo.findById(any(Long.class))).thenReturn(Optional.of(foreignUser)); + lenient().when(userRepo.update(any(User.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + Map data = request(currentSupplied, newPassword, confirm); + data.put("token", TOKEN); + data.put("resetToken", TOKEN); + data.putAll(extraFields); + + List log = new ArrayList<>(); + ApiResponse response = capturingLog(log, () -> passwordController.changePassword(user1, data)); + + if (succeeds) { + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus(), label); + + assertFalse(storedPassword.equals(user1.getPassword()), "the stored password must have been replaced: " + label); + assertTrue(passwordEncoder.matches(newPassword, user1.getPassword()), "the replaced password must verify against the submitted new password: " + label); + assertFalse(passwordEncoder.matches(CURRENT_PASSWORD, user1.getPassword()), "the replaced password must not verify against the previous password: " + label); + + // Only the principal is written or notified. + verify(userRepo).update(user1); + verifyNoMoreInteractions(userRepo); + + verify(credentialNotificationService).notifyPasswordChanged(user1); + verifyNoMoreInteractions(credentialNotificationService); + } else { + assertRejected(response); + + // A rejection encodes nothing and sends no email. + verify(cryptoService, never()).encodePassword(anyString()); + verifyNoInteractions(mockEmailService); + } + + assertEquals("foreign-stored-password", foreignUser.getPassword(), "the Account named by the body must be left unchanged: " + label); + + assertNoSecretLeaked(response, log, label, currentSupplied, newPassword, confirm, TOKEN, storedPassword, user1.getPassword()); + } + + /** + * Cases as (passwordLoginRaw, changeRaw, storedShape, netid, current, candidate, confirm, extraFields, label). + * Each block varies one dimension while the others stay on a succeeding shape. + */ + private static Stream provideChangeCases() { + List cases = new ArrayList<>(); + + for (String[] availability : AVAILABILITY_PAIRS) { + addCase(cases, "availability " + availability[0] + "/" + availability[1], availability[0], availability[1], HASHED_STORED_PASSWORD, null, CURRENT_PASSWORD, NEW_PASSWORD, NEW_PASSWORD); + } + + for (String[] eligibility : ELIGIBILITY_SHAPES) { + addCase(cases, "eligibility " + eligibility[0] + "/" + eligibility[1], "true", "true", eligibility[0], eligibility[1], CURRENT_PASSWORD, NEW_PASSWORD, NEW_PASSWORD); + } + + for (String supplied : SUPPLIED_CURRENT_PASSWORDS) { + addCase(cases, "current password '" + supplied + "'", "true", "true", HASHED_STORED_PASSWORD, null, supplied, NEW_PASSWORD, NEW_PASSWORD); + } + + for (String[] candidate : CANDIDATE_PAIRS) { + addCase(cases, "candidate '" + candidate[0] + "'/'" + candidate[1] + "'", "true", "true", HASHED_STORED_PASSWORD, null, CURRENT_PASSWORD, candidate[0], candidate[1]); + } + + for (String[] availability : AVAILABILITY_PAIRS) { + if (resolvesTrue(availability[0]) && resolvesTrue(availability[1])) { + continue; + } + + for (String[] eligibility : ELIGIBILITY_SHAPES) { + if (eligibility[1] == null && HASHED_STORED_PASSWORD.equals(eligibility[0])) { + continue; + } + + addCase(cases, "both gates failing " + availability[0] + "/" + availability[1] + " " + eligibility[0] + "/" + eligibility[1], availability[0], availability[1], eligibility[0], eligibility[1], CURRENT_PASSWORD, NEW_PASSWORD, NEW_PASSWORD); + } + } + + for (int i = 0; i < FOREIGN_IDENTIFIER_KEYS.length; i++) { + Map foreign = new HashMap<>(); + foreign.put(FOREIGN_IDENTIFIER_KEYS[i], FOREIGN_IDENTIFIER_VALUES[i % FOREIGN_IDENTIFIER_VALUES.length]); + + cases.add(Arguments.of("true", "true", HASHED_STORED_PASSWORD, null, CURRENT_PASSWORD, NEW_PASSWORD, NEW_PASSWORD, foreign, "foreign " + foreign)); + } + + Map allForeign = new HashMap<>(); + + for (int i = 0; i < FOREIGN_IDENTIFIER_KEYS.length; i++) { + allForeign.put(FOREIGN_IDENTIFIER_KEYS[i], FOREIGN_IDENTIFIER_VALUES[(i + 3) % FOREIGN_IDENTIFIER_VALUES.length]); + } + + cases.add(Arguments.of("true", "true", HASHED_STORED_PASSWORD, null, CURRENT_PASSWORD, NEW_PASSWORD, NEW_PASSWORD, allForeign, "foreign every key " + allForeign)); + + for (String secret : SECRET_SHAPES) { + addCase(cases, "secret as new password '" + secret + "'", "true", "true", HASHED_STORED_PASSWORD, null, CURRENT_PASSWORD, secret, secret); + addCase(cases, "secret as wrong current password '" + secret + "'", "true", "true", HASHED_STORED_PASSWORD, null, secret, NEW_PASSWORD, NEW_PASSWORD); + } + + return cases.stream(); + } + + private static void addCase(List cases, String label, String passwordLoginRaw, String changeRaw, String storedShape, String netid, String current, String newPassword, String confirm) { + Map claims = CLIENT_CLAIM_BODIES.get(cases.size() % CLIENT_CLAIM_BODIES.size()); + + cases.add(Arguments.of(passwordLoginRaw, changeRaw, storedShape, netid, current, newPassword, confirm, claims, label + " claims=" + claims)); + } + + /** No secret may appear in the serialized response, its message, its payload, or the log. */ + private void assertNoSecretLeaked(ApiResponse response, List log, String label, String... secrets) throws Exception { + List artefacts = new ArrayList<>(log); + + artefacts.add(new ObjectMapper().writeValueAsString(response)); + artefacts.add(String.valueOf(response.getMeta().getMessage())); + artefacts.add(String.valueOf(response.getPayload())); + + for (String secret : secrets) { + if (secret == null || secret.trim().isEmpty()) { + continue; + } + + for (String artefact : artefacts) { + assertFalse(artefact.contains(secret), "No password or token value may appear in the response or the log, found '" + secret + "' in: " + artefact + " (" + label + ")"); + assertFalse(artefact.contains(secret.trim()), "No password or token value may appear in the response or the log, found '" + secret.trim() + "' in: " + artefact + " (" + label + ")"); + } + } + } + + /** Runs the handler with the logger at ALL (test config pins ERROR, rejections log at DEBUG) and collects log lines. */ + private ApiResponse capturingLog(List lines, java.util.function.Supplier call) { + Logger controllerLogger = (Logger) LoggerFactory.getLogger(PasswordController.class); + Level originalLevel = controllerLogger.getLevel(); + ListAppender appender = new ListAppender<>(); + + appender.start(); + + controllerLogger.setLevel(Level.ALL); + controllerLogger.setAdditive(false); + controllerLogger.addAppender(appender); + + try { + return call.get(); + } finally { + controllerLogger.detachAppender(appender); + controllerLogger.setAdditive(true); + controllerLogger.setLevel(originalLevel); + + appender.stop(); + + for (ILoggingEvent event : appender.list) { + lines.add(event.getFormattedMessage()); + } + } + } + + /** Restated here rather than calling the service, so a service defect is not inherited. */ + private static boolean resolvesTrue(String raw) { + return raw != null && raw.trim().equalsIgnoreCase("true"); + } + + /** A rejection is INVALID, leaves the password unchanged, and writes and notifies nothing. */ + private void assertRejected(ApiResponse response) { + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus()); + assertEquals(storedPassword, user1.getPassword(), "the stored password must be left unchanged"); + + verifyNoInteractions(userRepo); + verifyNoInteractions(credentialNotificationService); + } + + private Map request(String currentPassword, String newPassword, String confirm) { + Map data = new HashMap<>(); + + data.put("currentPassword", currentPassword); + data.put("newPassword", newPassword); + data.put("confirm", confirm); + + return data; + } + + /** Lenient because the conjunction short-circuits on the password-login setting. */ + private void stubSettings(String passwordLoginEnabled, String changeEnabled) { + lenient().when(configurationRepo.getValueByNameAndType(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, APPLICATION_TYPE)).thenReturn(passwordLoginEnabled); + lenient().when(configurationRepo.getValueByNameAndType(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, APPLICATION_TYPE)).thenReturn(changeEnabled); + } + + /** Routes the mocked {@code CryptoService} onto the real encoder; used only for succeeding cases. */ + private void stubRealCrypto() { + lenient().when(cryptoService.validatePassword(any(), any())).thenAnswer(invocation -> invocation.getArgument(0) != null && passwordEncoder.matches(invocation.getArgument(0), invocation.getArgument(1))); + lenient().when(cryptoService.encodePassword(anyString())).thenAnswer(invocation -> passwordEncoder.encode(invocation.getArgument(0))); + } + + /** Cheap hash stand-in: matches exactly when stored is the prefix plus the supplied value. */ + private void stubFakeCrypto() { + lenient().when(cryptoService.validatePassword(any(), any())).thenAnswer(invocation -> invocation.getArgument(0) != null && (FAKE_PREFIX + invocation.getArgument(0)).equals(invocation.getArgument(1))); + lenient().when(cryptoService.encodePassword(anyString())).thenAnswer(invocation -> FAKE_PREFIX + invocation.getArgument(0)); + } + + // ----------------------------------------------------------------------------------------- + // POST /password/reset: enforcement and authorization. Each rejection pins INVALID, no token + // constructed, no email sent, and an unchanged stored password. + // ----------------------------------------------------------------------------------------- + + private static final String RESET_EMAIL = "email1"; + + @Test + public void testInitiateResetRequiresTheManagerRole() throws Exception { + // Spring Security rejects under-privileged callers before the handler runs, so the role + // check is enforced at the annotation level independently of what the client rendered. + Method handler = PasswordController.class.getMethod("initiateReset", Map.class); + + PreAuthorize preAuthorize = handler.getAnnotation(PreAuthorize.class); + + assertNotNull(preAuthorize, "the handler must carry a @PreAuthorize expression"); + assertEquals("hasRole('ROLE_MANAGER')", preAuthorize.value()); + + RequestMapping requestMapping = handler.getAnnotation(RequestMapping.class); + + assertNotNull(requestMapping); + assertEquals("/reset", requestMapping.value()[0]); + assertEquals(RequestMethod.POST, requestMapping.method()[0]); + } + + @Test + public void testInitiateResetRejectsAnIneligibleAccount() { + // Availability holds; the target Account exists but is ineligible (it has a netid), so no + // reset token is constructed and no email is sent. + stubResetSettings("true", "true"); + + user1.setNetid("netid1"); + String unchanged = user1.getPassword(); + + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + + ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + + assertResetRejected(response, ApiStatus.INVALID); + assertEquals(unchanged, user1.getPassword(), "an ineligible account's stored password must be left unchanged"); + } + + @Test + public void testInitiateResetRejectsWhenNoAccountForTheSuppliedEmail() { + // Availability holds; no Account exists for the supplied email, which is ineligible, so no + // reset token is constructed and no email is sent. There is no Account to write. + stubResetSettings("true", "true"); + + lenient().when(userRepo.findByEmail(anyString())).thenReturn(null); + + ApiResponse response = passwordController.initiateReset(resetRequest("absent@institution.edu")); + + assertResetRejected(response, ApiStatus.INVALID); + + // No Account existed, so nothing was written: only the read happened. + verify(userRepo).findByEmail("absent@institution.edu"); + verifyNoMoreInteractions(userRepo); + } + + @Test + public void testInitiateResetRejectsWhenPasswordLoginDisabled() { + // auth.pass.enabled false short-circuits isResetAvailable before any lookup, so no reset + // token is constructed and no email is sent. + stubResetSettings("false", "true"); + + user1.setNetid(null); + String unchanged = user1.getPassword(); + + lenient().when(userRepo.findByEmail(anyString())).thenReturn(user1); + + ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + + assertResetRejected(response, ApiStatus.INVALID); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged"); + + // The availability gate rejects before any Account lookup. + verifyNoInteractions(userRepo); + } + + @Test + public void testInitiateResetRejectsWhenResetDisabled() { + // auth.pass.reset.enabled false makes isResetAvailable false, so no reset token is + // constructed and no email is sent. + stubResetSettings("true", "false"); + + user1.setNetid(null); + String unchanged = user1.getPassword(); + + lenient().when(userRepo.findByEmail(anyString())).thenReturn(user1); + + ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + + assertResetRejected(response, ApiStatus.INVALID); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged"); + + // The availability gate rejects before any Account lookup. + verifyNoInteractions(userRepo); + } + + /** A reset rejection pins the given status, constructs no token, and sends no email. */ + private void assertResetRejected(ApiResponse response, ApiStatus expected) { + assertEquals(expected, response.getMeta().getStatus()); + + verify(resetTokenService, never()).construct(any()); + verifyNoInteractions(emailSender); + verifyNoInteractions(credentialNotificationService); + } + + private Map resetRequest(String email) { + Map data = new HashMap<>(); + + data.put("email", email); + + return data; + } + + /** Lenient because the reset conjunction short-circuits on the password-login setting. */ + private void stubResetSettings(String passwordLoginEnabled, String resetEnabled) { + lenient().when(configurationRepo.getValueByNameAndType(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, APPLICATION_TYPE)).thenReturn(passwordLoginEnabled); + lenient().when(configurationRepo.getValueByNameAndType(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, APPLICATION_TYPE)).thenReturn(resetEnabled); + } + + // ----------------------------------------------------------------------------------------- + // POST /password/reset beyond the gates: missing template (ERROR naming it), mail failure + // (ERROR), and a successful send (SUCCESS). The stored password is never written. + // ----------------------------------------------------------------------------------------- + + private static final String RESET_SUBJECT = "Reset your Vireo password"; + + private static final String RESET_MESSAGE = "Follow {RESET_URL} to reset your password."; + + private static final String RESET_TOKEN = "resettoken.payload"; + + @Test + public void testInitiateResetReportsAnErrorWhenTheTemplateIsMissing() { + // Availability and eligibility hold, but the reset-request template is not installed, so + // resolveTemplate (backed by findByNameOverride) returns null. The handler reports ERROR + // naming the absent template, sends no email, and leaves the stored password untouched. + stubResetSettings("true", "true"); + + user1.setNetid(null); + String unchanged = user1.getPassword(); + + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + when(credentialNotificationService.resolveTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE)).thenReturn(null); + + ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + + assertEquals(ApiStatus.ERROR, response.getMeta().getStatus()); + assertTrue(response.getMeta().getMessage().contains(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE), "the error message must name the absent template"); + + // No token was constructed and no email was sent. + verify(resetTokenService, never()).construct(any()); + verifyNoInteractions(emailSender); + + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged when the template is missing"); + } + + @Test + public void testInitiateResetReportsAnErrorWhenTheSendFails() throws Exception { + // Availability, eligibility and template resolution all hold, but the send raises a + // MessagingException. The handler converts it to ERROR and leaves the stored password + // untouched: the reset path never writes the password. + stubResetSettings("true", "true"); + + user1.setNetid(null); + String unchanged = user1.getPassword(); + + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + when(credentialNotificationService.resolveTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE)).thenReturn(new EmailTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE, RESET_SUBJECT, RESET_MESSAGE)); + when(resetTokenService.construct(user1)).thenReturn(RESET_TOKEN); + lenient().when(templateUtility.templateParameters(any(String.class), any(String[][].class))).thenReturn(RESET_MESSAGE); + + MessagingException mailFailure = new MessagingException("transport failure"); + doThrow(mailFailure).when(emailSender).sendEmail(anyString(), anyString(), anyString()); + + Logger controllerLogger = (Logger) LoggerFactory.getLogger(PasswordController.class); + Level originalLevel = controllerLogger.getLevel(); + boolean originalAdditive = controllerLogger.isAdditive(); + ListAppender appender = new ListAppender<>(); + ApiResponse response; + + appender.start(); + controllerLogger.setLevel(Level.ALL); + controllerLogger.setAdditive(false); + controllerLogger.addAppender(appender); + + try { + response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + } finally { + controllerLogger.detachAppender(appender); + controllerLogger.setAdditive(originalAdditive); + controllerLogger.setLevel(originalLevel); + appender.stop(); + } + + assertEquals(ApiStatus.ERROR, response.getMeta().getStatus()); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged when the send fails"); + + assertEquals(1, appender.list.size(), "the mail failure must produce one controller log event"); + ILoggingEvent event = appender.list.get(0); + assertEquals(Level.WARN, event.getLevel(), "the mail failure must be visible at the production log level"); + assertEquals("Unable to send a password reset email.", event.getFormattedMessage()); + + List logLines = Arrays.asList(event.getFormattedMessage()); + assertNoSecretLeaked(response, logLines, "reset mail failure", RESET_EMAIL, user1.getEmail(), CURRENT_PASSWORD, unchanged, RESET_TOKEN); + } + + @Test + public void testInitiateResetSendsToTheRecipientOnSuccess() throws MessagingException { + // Availability, eligibility and template resolution all hold and the send succeeds, so the + // handler reports SUCCESS and the email targets the account's own email address. + stubResetSettings("true", "true"); + + user1.setNetid(null); + + when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + when(credentialNotificationService.resolveTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE)).thenReturn(new EmailTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE, RESET_SUBJECT, RESET_MESSAGE)); + when(resetTokenService.construct(user1)).thenReturn(RESET_TOKEN); + when(templateUtility.templateParameters(any(String.class), any(String[][].class))).thenReturn(RESET_MESSAGE); + + ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus()); + + // The response message is generic and names no recipient, keeping the recipient address out of the payload. + assertEquals("A password reset link has been sent.", response.getMeta().getMessage()); + + // The send itself targets the recipient's own email address and carries the resolved subject. + verify(emailSender).sendEmail(eq(user1.getEmail()), eq(RESET_SUBJECT), anyString()); + } + + // ----------------------------------------------------------------------------------------- + // Initiation has no side effects: it constructs a token and sends mail but never writes the + // stored password. Cases are enumerated email/hash shapes plus a fixed-seed Random. + // ----------------------------------------------------------------------------------------- + + static Stream provideResetNoSideEffectCases() { + List emails = new ArrayList<>(Arrays.asList( + "email1", + "student@institution.edu", + "a@b.co", + "UPPER.Case@Institution.EDU")); + + // Eligible stored-hash shapes only: the reset arm is driven for eligible Accounts. + List storedHashes = new ArrayList<>(Arrays.asList( + FAKE_HASH, + "HASHED_STORED_PASSWORD", + "$2a$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ012345", + "plainhash")); + + List cases = new ArrayList<>(); + for (String email : emails) { + for (String hash : storedHashes) { + cases.add(Arguments.of(email, hash)); + } + } + + java.util.Random random = new java.util.Random(20250101L); + while (cases.size() < 100) { + String email = "user" + random.nextInt(100000) + "@institution.edu"; + String hash = "$2a$10$" + random.nextLong(); + cases.add(Arguments.of(email, hash)); + } + + return cases.stream(); + } + + @ParameterizedTest(name = "[{index}] reset no side effects {0}") + @MethodSource("provideResetNoSideEffectCases") + public void initiateResetConstructsTokenAndSendsMailButWritesNoPassword(String email, String storedHash) throws MessagingException { + setup(); + + // Availability and eligibility hold, and the template resolves and the send succeeds, so + // the full happy path runs: a token is constructed and mail is sent. + stubResetSettings("true", "true"); + + user1.setEmail(email); + user1.setNetid(null); + user1.setPassword(storedHash); + + String hashBefore = user1.getPassword(); + + when(userRepo.findByEmail(email)).thenReturn(user1); + when(credentialNotificationService.resolveTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE)).thenReturn(new EmailTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE, RESET_SUBJECT, RESET_MESSAGE)); + when(resetTokenService.construct(user1)).thenReturn(RESET_TOKEN); + when(templateUtility.templateParameters(any(String.class), any(String[][].class))).thenReturn(RESET_MESSAGE); + + ApiResponse response = passwordController.initiateReset(resetRequest(email)); + + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus(), "eligible initiation succeeds for " + email); + + // Requirement 7.5: a token is still constructed and mail is still sent. + verify(resetTokenService).construct(user1); + verify(emailSender).sendEmail(eq(user1.getEmail()), eq(RESET_SUBJECT), anyString()); + + // No side effect on the stored password: the initiation path never writes the Account. + verify(userRepo, never()).update(any(User.class)); + verify(userRepo, never()).save(any(User.class)); + + // The stored password hash is byte-identical before and after initiation. + assertEquals(hashBefore, user1.getPassword(), "the stored password hash must be unchanged by initiation for " + email); + assertTrue(storedHash.equals(user1.getPassword()), "the stored password hash must be byte-identical to the original for " + email); + } + + // ----------------------------------------------------------------------------------------- + // Initiation is gated on auth.pass.enabled, auth.pass.reset.enabled and eligibility together; + // every failing combination constructs no token, sends no email and writes nothing. + // ----------------------------------------------------------------------------------------- + + @ParameterizedTest(name = "[{index}] {3}") + @MethodSource("provideResetEnforcementCases") + public void resetEnforcesItsGatesIndependentlyOfTheClient(String passwordLoginRaw, String resetRaw, String[] eligibilityShape, String label) throws MessagingException { + setup(); + + boolean available = resolvesTrue(passwordLoginRaw) && resolvesTrue(resetRaw); + boolean eligible = eligibilityShape[1] == null && eligibilityShape[0] != null && !eligibilityShape[0].trim().isEmpty(); + boolean succeeds = available && eligible; + + stubResetSettings(passwordLoginRaw, resetRaw); + + user1.setPassword(eligibilityShape[0]); + user1.setNetid(eligibilityShape[1]); + + String unchanged = user1.getPassword(); + + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + lenient().when(credentialNotificationService.resolveTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE)) + .thenReturn(new EmailTemplate(CredentialNotificationService.PASSWORD_RESET_REQUEST_TEMPLATE, RESET_SUBJECT, RESET_MESSAGE)); + lenient().when(resetTokenService.construct(user1)).thenReturn(RESET_TOKEN); + lenient().when(templateUtility.templateParameters(any(String.class), any(String[][].class))).thenReturn(RESET_MESSAGE); + + ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + + if (succeeds) { + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus(), label); + + verify(resetTokenService).construct(user1); + verify(emailSender).sendEmail(eq(user1.getEmail()), eq(RESET_SUBJECT), anyString()); + } else { + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus(), label); + + verify(resetTokenService, never()).construct(any()); + verifyNoInteractions(emailSender); + } + + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged: " + label); + } + + /** + * Cases as (passwordLoginRaw, resetRaw, eligibilityShape, label): availability varied alone + * against an eligible shape, eligibility varied alone against an available pair, and every + * combination where both an availability pair and an eligibility shape fail together. + */ + private static Stream provideResetEnforcementCases() { + List cases = new ArrayList<>(); + + for (String[] availability : AVAILABILITY_PAIRS) { + cases.add(Arguments.of(availability[0], availability[1], new String[] { HASHED_STORED_PASSWORD, null }, "availability " + availability[0] + "/" + availability[1])); + } + + for (String[] eligibility : ELIGIBILITY_SHAPES) { + cases.add(Arguments.of("true", "true", eligibility, "eligibility " + eligibility[0] + "/" + eligibility[1])); + } + + for (String[] availability : AVAILABILITY_PAIRS) { + if (resolvesTrue(availability[0]) && resolvesTrue(availability[1])) { + continue; + } + + for (String[] eligibility : ELIGIBILITY_SHAPES) { + if (eligibility[1] == null && HASHED_STORED_PASSWORD.equals(eligibility[0])) { + continue; + } + + cases.add(Arguments.of(availability[0], availability[1], eligibility, "both gates failing " + availability[0] + "/" + availability[1] + " " + eligibility[0] + "/" + eligibility[1])); + } + } + + return cases.stream(); + } + + // ----------------------------------------------------------------------------------------- + // POST /password/reset/redeem: enforcement. Each rejection cause - either setting off, each + // token failure class, an ineligible Account - pins INVALID, an unchanged password, and no + // notification. + // ----------------------------------------------------------------------------------------- + + private static final String REDEEM_NEW_PASSWORD = "brandnewpassword"; + + @Test + public void testRedeemResetRejectsWhenPasswordLoginDisabled() { + // auth.pass.enabled false short-circuits isResetAvailable before any token verification. + stubResetSettings("false", "true"); + + String unchanged = user1.getPassword(); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, REDEEM_NEW_PASSWORD, REDEEM_NEW_PASSWORD)); + + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus()); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged"); + + // The availability gate rejects before the token is even read. + verifyNoInteractions(resetTokenService); + verifyNoInteractions(userRepo); + verifyNoInteractions(credentialNotificationService); + } + + @Test + public void testRedeemResetRejectsWhenResetDisabled() { + // auth.pass.reset.enabled false makes isResetAvailable false. + stubResetSettings("true", "false"); + + String unchanged = user1.getPassword(); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, REDEEM_NEW_PASSWORD, REDEEM_NEW_PASSWORD)); + + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus()); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged"); + + verifyNoInteractions(resetTokenService); + verifyNoInteractions(userRepo); + verifyNoInteractions(credentialNotificationService); + } + + @Test + public void testRedeemResetRejectsAnExpiredToken() { + // Availability holds, but the token aged past its expiry window, so the response carries + // the expiry-specific instruction rather than the generic message. + stubResetSettings("true", "true"); + + String unchanged = user1.getPassword(); + + when(resetTokenService.verify(TOKEN)).thenReturn(ResetTokenVerification.expired()); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, REDEEM_NEW_PASSWORD, REDEEM_NEW_PASSWORD)); + + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus()); + assertTrue(response.getMeta().getMessage().toLowerCase().contains("expired"), "an expired token must report the expiry-specific message"); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged"); + + // No Account is even looked up once the token fails verification. + verifyNoInteractions(userRepo); + verifyNoInteractions(credentialNotificationService); + } + + @Test + public void testRedeemResetRejectsAnInvalidToken() { + // Availability holds, but the token is malformed, tampered, unknown, or stale from an + // unrelated password change: every one of those causes reports the same generic message. + stubResetSettings("true", "true"); + + String unchanged = user1.getPassword(); + + when(resetTokenService.verify(TOKEN)).thenReturn(ResetTokenVerification.invalid()); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, REDEEM_NEW_PASSWORD, REDEEM_NEW_PASSWORD)); + + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus()); + assertEquals("This password reset link is no longer valid.", response.getMeta().getMessage()); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged"); + + verifyNoInteractions(userRepo); + verifyNoInteractions(credentialNotificationService); + } + + @Test + public void testRedeemResetRejectsAnIneligibleAccount() { + // The token itself verifies, but the Account it names carries a netid and so is ineligible. + stubResetSettings("true", "true"); + + user1.setNetid("netid1"); + String unchanged = user1.getPassword(); + + when(resetTokenService.verify(TOKEN)).thenReturn(ResetTokenVerification.valid(RESET_EMAIL, Instant.now())); + when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, REDEEM_NEW_PASSWORD, REDEEM_NEW_PASSWORD)); + + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus()); + assertEquals(unchanged, user1.getPassword(), "an ineligible account's stored password must be left unchanged"); + + verify(userRepo, never()).update(any(User.class)); + verifyNoInteractions(credentialNotificationService); + } + + private Map redeemRequest(String token, String newPassword, String confirm) { + Map data = new HashMap<>(); + + data.put("token", token); + data.put("newPassword", newPassword); + data.put("confirm", confirm); + + return data; + } + + // ----------------------------------------------------------------------------------------- + // Redemption replaces the stored password only when availability, token verification, + // eligibility and candidate validity all hold. Each dimension is varied against an + // otherwise-succeeding baseline. + // ----------------------------------------------------------------------------------------- + + @ParameterizedTest(name = "[{index}] {6}") + @MethodSource("provideRedemptionConjunctionCases") + public void redeemResetSucceedsExactlyUnderItsConjunction(String passwordLoginRaw, String resetRaw, ResetTokenVerification.Status tokenStatus, String[] eligibilityShape, String newPassword, String confirm, String label) { + setup(); + + boolean available = resolvesTrue(passwordLoginRaw) && resolvesTrue(resetRaw); + boolean tokenValid = tokenStatus == ResetTokenVerification.Status.VALID; + boolean eligible = eligibilityShape[1] == null && eligibilityShape[0] != null && !eligibilityShape[0].trim().isEmpty(); + boolean candidateAccepted = PasswordValidator.validate(newPassword, confirm) == PasswordValidator.Result.ACCEPTED; + boolean succeeds = available && tokenValid && eligible && candidateAccepted; + + stubResetSettings(passwordLoginRaw, resetRaw); + + if (succeeds) { + stubRealCrypto(); + } else { + stubFakeCrypto(); + } + + user1.setPassword(eligibilityShape[0]); + user1.setNetid(eligibilityShape[1]); + + String unchanged = user1.getPassword(); + + ResetTokenVerification verification; + if (tokenValid) { + verification = ResetTokenVerification.valid(RESET_EMAIL, Instant.now()); + } else if (tokenStatus == ResetTokenVerification.Status.EXPIRED) { + verification = ResetTokenVerification.expired(); + } else { + verification = ResetTokenVerification.invalid(); + } + + lenient().when(resetTokenService.verify(TOKEN)).thenReturn(verification); + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + lenient().when(userRepo.update(any(User.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, newPassword, confirm)); + + if (succeeds) { + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus(), label); + + assertFalse(unchanged.equals(user1.getPassword()), "the stored password must have been replaced: " + label); + assertTrue(passwordEncoder.matches(newPassword, user1.getPassword()), "the replaced password must verify against the submitted new password: " + label); + + verify(userRepo).update(user1); + verify(credentialNotificationService).notifyPasswordChanged(user1); + } else { + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus(), label); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged: " + label); + + verify(userRepo, never()).update(any(User.class)); + verifyNoInteractions(credentialNotificationService); + } + } + + /** + * Cases as (passwordLoginRaw, resetRaw, tokenStatus, eligibilityShape, newPassword, confirm, + * label). Each block varies one dimension while the others stay on a succeeding shape. + */ + private static Stream provideRedemptionConjunctionCases() { + List cases = new ArrayList<>(); + + for (String[] availability : AVAILABILITY_PAIRS) { + cases.add(Arguments.of(availability[0], availability[1], ResetTokenVerification.Status.VALID, new String[] { HASHED_STORED_PASSWORD, null }, NEW_PASSWORD, NEW_PASSWORD, + "availability " + availability[0] + "/" + availability[1])); + } + + for (ResetTokenVerification.Status status : ResetTokenVerification.Status.values()) { + cases.add(Arguments.of("true", "true", status, new String[] { HASHED_STORED_PASSWORD, null }, NEW_PASSWORD, NEW_PASSWORD, + "token status " + status)); + } + + for (String[] eligibility : ELIGIBILITY_SHAPES) { + cases.add(Arguments.of("true", "true", ResetTokenVerification.Status.VALID, eligibility, NEW_PASSWORD, NEW_PASSWORD, + "eligibility " + eligibility[0] + "/" + eligibility[1])); + } + + for (String[] candidate : CANDIDATE_PAIRS) { + cases.add(Arguments.of("true", "true", ResetTokenVerification.Status.VALID, new String[] { HASHED_STORED_PASSWORD, null }, candidate[0], candidate[1], + "candidate '" + candidate[0] + "'/'" + candidate[1] + "'")); + } + + return cases.stream(); + } + + // ----------------------------------------------------------------------------------------- + // A rejected candidate leaves the token usable. The real ResetTokenService is wired in here + // so the token's continued validity is genuinely exercised; after the rejection the same + // token redeems successfully. + // ----------------------------------------------------------------------------------------- + + @ParameterizedTest(name = "[{index}] rejected candidate ''{0}''/''{1}'' leaves the token usable") + @MethodSource("provideRejectedCandidatesForTokenUsability") + public void aRejectedCandidateLeavesTheTokenUsable(String rejectedNewPassword, String rejectedConfirm) { + setup(); + + stubResetSettings("true", "true"); + stubRealCrypto(); + + ResetTokenService realResetTokenService = new ResetTokenService(); + ReflectionTestUtils.setField(realResetTokenService, "signingSecret", SECRET_VALUE); + ReflectionTestUtils.setField(realResetTokenService, "userRepo", userRepo); + ReflectionTestUtils.setField(realResetTokenService, "availabilityService", availabilityService); + ReflectionTestUtils.setField(passwordController, "resetTokenService", realResetTokenService); + + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + lenient().when(userRepo.update(any(User.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + String token = realResetTokenService.construct(user1); + + // The rejected submission is turned away and leaves nothing for the token's binding to react to. + ApiResponse rejectedResponse = passwordController.redeemReset(redeemRequest(token, rejectedNewPassword, rejectedConfirm)); + + assertEquals(ApiStatus.INVALID, rejectedResponse.getMeta().getStatus()); + assertEquals(FAKE_HASH, user1.getPassword(), "a rejected candidate must leave the stored password unchanged"); + + verify(userRepo, never()).update(any(User.class)); + + // The same token still redeems successfully afterward: the earlier rejection left it intact. + ApiResponse successResponse = passwordController.redeemReset(redeemRequest(token, NEW_PASSWORD, NEW_PASSWORD)); + + assertEquals(ApiStatus.SUCCESS, successResponse.getMeta().getStatus(), "the token must still be usable after an earlier rejected candidate"); + assertTrue(passwordEncoder.matches(NEW_PASSWORD, user1.getPassword()), "the stored password must now verify against the submitted new password"); + + verify(userRepo).update(user1); + verify(credentialNotificationService).notifyPasswordChanged(user1); + } + + private static Stream provideRejectedCandidatesForTokenUsability() { + return Stream.of( + Arguments.of(null, null), + Arguments.of(" ", " "), + Arguments.of("short", "short"), + Arguments.of(NEW_PASSWORD, "newpasswordx")); + } + + // ----------------------------------------------------------------------------------------- + // A successful redemption carries no payload, so no token or credential rides along and the + // caller is left to sign in (unlike AuthController.login, whose payload is a JWT). + // ----------------------------------------------------------------------------------------- + + @Test + public void testRedeemResetSuccessCarriesNoTokenAndNoCredential() throws Exception { + stubResetSettings("true", "true"); + stubRealCrypto(); + + user1.setNetid(null); + + when(resetTokenService.verify(TOKEN)).thenReturn(ResetTokenVerification.valid(RESET_EMAIL, Instant.now())); + when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + when(userRepo.update(any(User.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, NEW_PASSWORD, NEW_PASSWORD)); + + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus()); + + // No payload rides along at all, so there is nothing a client could read as a token or a + // credential. + assertTrue(response.getPayload() == null || response.getPayload().isEmpty(), "a successful redemption must carry no payload, so neither a token nor a credential can ride along"); + + assertNoSecretLeaked(response, new ArrayList<>(), "successful redemption", TOKEN, NEW_PASSWORD); + } + + // ----------------------------------------------------------------------------------------- + // Redemption is gated on auth.pass.enabled, auth.pass.reset.enabled and eligibility together; + // the token verifies throughout, so only those gates are under test here. + // ----------------------------------------------------------------------------------------- + + @ParameterizedTest(name = "[{index}] {3}") + @MethodSource("provideRedeemEnforcementCases") + public void redeemEnforcesItsGatesIndependentlyOfTheClient(String passwordLoginRaw, String resetRaw, String[] eligibilityShape, String label) { + setup(); + + boolean available = resolvesTrue(passwordLoginRaw) && resolvesTrue(resetRaw); + boolean eligible = eligibilityShape[1] == null && eligibilityShape[0] != null && !eligibilityShape[0].trim().isEmpty(); + boolean succeeds = available && eligible; + + stubResetSettings(passwordLoginRaw, resetRaw); + stubRealCrypto(); + + user1.setPassword(eligibilityShape[0]); + user1.setNetid(eligibilityShape[1]); + + String unchanged = user1.getPassword(); + + lenient().when(resetTokenService.verify(TOKEN)).thenReturn(ResetTokenVerification.valid(RESET_EMAIL, Instant.now())); + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + lenient().when(userRepo.update(any(User.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + ApiResponse response = passwordController.redeemReset(redeemRequest(TOKEN, NEW_PASSWORD, NEW_PASSWORD)); + + if (succeeds) { + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus(), label); + + verify(userRepo).update(user1); + verify(credentialNotificationService).notifyPasswordChanged(user1); + } else { + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus(), label); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged: " + label); + + verify(userRepo, never()).update(any(User.class)); + verifyNoInteractions(credentialNotificationService); + } + } + + /** + * Cases as (passwordLoginRaw, resetRaw, eligibilityShape, label): availability varied alone + * against an eligible shape, eligibility varied alone against an available pair, and every + * combination where both an availability pair and an eligibility shape fail together. + */ + private static Stream provideRedeemEnforcementCases() { + List cases = new ArrayList<>(); + + for (String[] availability : AVAILABILITY_PAIRS) { + cases.add(Arguments.of(availability[0], availability[1], new String[] { HASHED_STORED_PASSWORD, null }, "availability " + availability[0] + "/" + availability[1])); + } + + for (String[] eligibility : ELIGIBILITY_SHAPES) { + cases.add(Arguments.of("true", "true", eligibility, "eligibility " + eligibility[0] + "/" + eligibility[1])); + } + + for (String[] availability : AVAILABILITY_PAIRS) { + if (resolvesTrue(availability[0]) && resolvesTrue(availability[1])) { + continue; + } + + for (String[] eligibility : ELIGIBILITY_SHAPES) { + if (eligibility[1] == null && HASHED_STORED_PASSWORD.equals(eligibility[0])) { + continue; + } + + cases.add(Arguments.of(availability[0], availability[1], eligibility, "both gates failing " + availability[0] + "/" + availability[1] + " " + eligibility[0] + "/" + eligibility[1])); + } + } + + return cases.stream(); + } + + // ----------------------------------------------------------------------------------------- + // Failure message partition: every non-expiry failure (malformed, tampered, unknown account, + // stale after a password change, backward clock) reports the identical generic message, and + // a genuine expiry reports a different one. Overall status is INVALID for all of them, so only + // the message distinguishes. The real ResetTokenService produces each cause. + // ----------------------------------------------------------------------------------------- + + private static final String GENERIC_INVALID_MESSAGE = "This password reset link is no longer valid."; + + @Test + public void testRedeemResetReportsTheSameGenericMessageForEveryNonExpiryCause() { + stubResetSettings("true", "true"); + + ResetTokenService realResetTokenService = new ResetTokenService(); + ReflectionTestUtils.setField(realResetTokenService, "signingSecret", SECRET_VALUE); + ReflectionTestUtils.setField(realResetTokenService, "userRepo", userRepo); + ReflectionTestUtils.setField(realResetTokenService, "availabilityService", availabilityService); + + // A fixed base clock keeps every offset below deterministic. A system clock let a token + // built at an hour offset land on either side of the whole-hour expiry boundary depending + // on the wall-clock moment the test ran, which made this test intermittently fail. + Clock baseClock = Clock.fixed(Instant.ofEpochSecond(1_700_000_000L), ZoneOffset.UTC); + ReflectionTestUtils.setField(realResetTokenService, "clock", baseClock); + ReflectionTestUtils.setField(passwordController, "resetTokenService", realResetTokenService); + + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + + List genericMessages = new ArrayList<>(); + + // Cause 1: a malformed token, carrying no "." separator at all. + genericMessages.add(redeemAndGetMessage("not-a-valid-token")); + + // Cause 2: a tampered signature. + String validToken = realResetTokenService.construct(user1); + genericMessages.add(redeemAndGetMessage(tamper(validToken))); + + // Cause 3: an unknown account - no User resolves for the token's email. + User ghost = new User("nobody@institution.edu", "firstname3", "lastname3", Role.ROLE_STUDENT); + ghost.setPassword(FAKE_HASH); + lenient().when(userRepo.findByEmail("nobody@institution.edu")).thenReturn(null); + String ghostToken = realResetTokenService.construct(ghost); + genericMessages.add(redeemAndGetMessage(ghostToken)); + + // Cause 4: a token invalidated by an unrelated password change; BCrypt re-salts on every + // encode, so even an equal-value change would invalidate it. + String staleToken = realResetTokenService.construct(user1); + String originalPassword = user1.getPassword(); + user1.setPassword(new BCryptPasswordEncoder().encode(CURRENT_PASSWORD)); + genericMessages.add(redeemAndGetMessage(staleToken)); + user1.setPassword(originalPassword); + + // Cause 5: a backward clock step, so the elapsed time since issuance is negative. + ReflectionTestUtils.setField(realResetTokenService, "clock", Clock.offset(baseClock, Duration.ofHours(1))); + String futureToken = realResetTokenService.construct(user1); + ReflectionTestUtils.setField(realResetTokenService, "clock", baseClock); + genericMessages.add(redeemAndGetMessage(futureToken)); + + for (String message : genericMessages) { + assertEquals(GENERIC_INVALID_MESSAGE, message, "every non-expiry cause must report the identical generic message"); + } + + // A genuine expiry reports a different, expiry-specific message. + ReflectionTestUtils.setField(realResetTokenService, "clock", Clock.offset(baseClock, Duration.ofHours(-25))); + String expiringToken = realResetTokenService.construct(user1); + ReflectionTestUtils.setField(realResetTokenService, "clock", baseClock); + + String expiredMessage = redeemAndGetMessage(expiringToken); + + assertFalse(GENERIC_INVALID_MESSAGE.equals(expiredMessage), "an expired token must not report the generic message"); + assertTrue(expiredMessage.toLowerCase().contains("expired"), "an expired token must report the expiry-specific message"); + } + + /** Redeems with a fixed, valid-shaped candidate so only the token's own verification governs + * the outcome, and returns the message so the caller can compare it against other causes. */ + private String redeemAndGetMessage(String token) { + ApiResponse response = passwordController.redeemReset(redeemRequest(token, NEW_PASSWORD, NEW_PASSWORD)); + + assertEquals(ApiStatus.INVALID, response.getMeta().getStatus()); + + return response.getMeta().getMessage(); + } + + /** Flips the token's final character to a different, still-valid base64url character. */ + private static String tamper(String token) { + char last = token.charAt(token.length() - 1); + char replacement = last == 'A' ? 'B' : 'A'; + + return token.substring(0, token.length() - 1) + replacement; + } + + // ----------------------------------------------------------------------------------------- + // Leak containment: no response or log line from redemption may contain the email, the token, + // or the stored hash (before or after), whatever the outcome. Reuses the conjunction cases. + // ----------------------------------------------------------------------------------------- + + @ParameterizedTest(name = "[{index}] leak containment {6}") + @MethodSource("provideRedemptionConjunctionCases") + public void redeemResetLeaksNoSecretUnderAnyOutcome(String passwordLoginRaw, String resetRaw, ResetTokenVerification.Status tokenStatus, String[] eligibilityShape, String newPassword, String confirm, String label) throws Exception { + setup(); + + stubResetSettings(passwordLoginRaw, resetRaw); + stubRealCrypto(); + + user1.setPassword(eligibilityShape[0]); + user1.setNetid(eligibilityShape[1]); + + String storedBefore = user1.getPassword(); + + ResetTokenVerification verification; + if (tokenStatus == ResetTokenVerification.Status.VALID) { + verification = ResetTokenVerification.valid(RESET_EMAIL, Instant.now()); + } else if (tokenStatus == ResetTokenVerification.Status.EXPIRED) { + verification = ResetTokenVerification.expired(); + } else { + verification = ResetTokenVerification.invalid(); + } + + lenient().when(resetTokenService.verify(TOKEN)).thenReturn(verification); + lenient().when(userRepo.findByEmail(RESET_EMAIL)).thenReturn(user1); + lenient().when(userRepo.update(any(User.class))).thenAnswer(invocation -> invocation.getArgument(0)); + + List log = new ArrayList<>(); + ApiResponse response = capturingLog(log, () -> passwordController.redeemReset(redeemRequest(TOKEN, newPassword, confirm))); + + assertNoSecretLeaked(response, log, label, TOKEN, RESET_EMAIL, storedBefore, user1.getPassword(), newPassword, confirm); + } + +} diff --git a/src/test/java/org/tdl/vireo/controller/UserControllerTest.java b/src/test/java/org/tdl/vireo/controller/UserControllerTest.java index e6e60b937a..362ce68af1 100644 --- a/src/test/java/org/tdl/vireo/controller/UserControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/UserControllerTest.java @@ -1,6 +1,9 @@ package org.tdl.vireo.controller; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.ArgumentMatchers.anyString; @@ -31,6 +34,11 @@ import org.tdl.vireo.model.User; import org.tdl.vireo.model.repo.UserRepo; import org.tdl.vireo.model.request.FilteredPageRequest; +import org.tdl.vireo.model.response.Views; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; import edu.tamu.weaver.auth.model.Credentials; import edu.tamu.weaver.response.ApiResponse; @@ -80,7 +88,7 @@ public void setup() { @Test public void testCredentials() { - ApiResponse response = userController.credentials(credentials1); + ApiResponse response = userController.credentials(credentials1, user1); assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus()); @@ -89,6 +97,112 @@ public void testCredentials() { assertEquals(credentials1, got); } + @Test + public void testCredentialsCarriesPasswordEligibleTrue() { + user1.setPassword("encodedpassword"); + user1.setNetid(null); + + ApiResponse response = userController.credentials(credentials1, user1); + + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus()); + + Credentials got = (Credentials) response.getPayload().get("Credentials"); + + // The map is Map, so the value is the String "true", not a JSON boolean. + assertEquals("true", got.getAllCredentials().get("passwordEligible")); + } + + @Test + public void testCredentialsCarriesPasswordEligibleFalse() { + user1.setPassword("encodedpassword"); + user1.setNetid("netid1"); + + ApiResponse response = userController.credentials(credentials1, user1); + + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus()); + + Credentials got = (Credentials) response.getPayload().get("Credentials"); + + assertEquals("false", got.getAllCredentials().get("passwordEligible")); + } + + @Test + public void testCredentialsPasswordEligibleIsAlwaysAStringValue() { + user1.setPassword(" "); + user1.setNetid(null); + + ApiResponse response = userController.credentials(credentials1, user1); + + Credentials got = (Credentials) response.getPayload().get("Credentials"); + Object value = got.getAllCredentials().get("passwordEligible"); + + assertTrue(value instanceof String, "passwordEligible must ride in the map as a String"); + assertEquals("false", value, "a whitespace-only password is ineligible"); + } + + @Test + public void testCredentialsGuardsNullAllCredentials() { + // The no-arg Credentials constructor leaves allCredentials null, so the handler must create the map. + credentials1.setAllCredentials(null); + + user1.setPassword("encodedpassword"); + user1.setNetid(null); + + ApiResponse response = userController.credentials(credentials1, user1); + + assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus()); + + Credentials got = (Credentials) response.getPayload().get("Credentials"); + + assertNotNull(got.getAllCredentials(), "the handler must set a map when none is present"); + assertEquals("true", got.getAllCredentials().get("passwordEligible")); + } + + @Test + public void testPasswordEligibleSerializesWithNoActiveView() throws Exception { + // Un-annotated properties serialize only with no active view (default-view-inclusion is off). + user1.setPassword("encodedpassword"); + user1.setNetid(null); + + JsonNode payload = viewAwareMapper().readTree(viewAwareMapper().writeValueAsString(user1)); + + assertTrue(payload.has("passwordEligible"), "passwordEligible must serialize with no view active"); + assertTrue(payload.get("passwordEligible").asBoolean(), "an eligible Account serializes true"); + } + + @Test + public void testPasswordEligibleIsAbsentUnderAnActiveView() throws Exception { + user1.setPassword("encodedpassword"); + user1.setNetid(null); + + ObjectMapper mapper = viewAwareMapper(); + + for (Class view : Arrays.asList(Views.SubmissionList.class, Views.Partial.class, Views.SubmissionIndividual.class, Views.SubmissionIndividualActionLogs.class)) { + JsonNode payload = mapper.readTree(mapper.writerWithView(view).writeValueAsString(user1)); + + assertFalse(payload.has("passwordEligible"), "passwordEligible must be absent under the active view " + view.getSimpleName()); + } + } + + @Test + public void testPasswordEligibleSerializesFalseForAnIneligibleAccount() throws Exception { + user1.setPassword("encodedpassword"); + user1.setNetid("netid1"); + + ObjectMapper mapper = viewAwareMapper(); + JsonNode payload = mapper.readTree(mapper.writeValueAsString(user1)); + + assertTrue(payload.has("passwordEligible")); + assertFalse(payload.get("passwordEligible").asBoolean(), "an Account carrying a netid serializes false"); + } + + /** Mapper matching application.yml (default-view-inclusion off); the inherited objectMapper is a shared spy. */ + private ObjectMapper viewAwareMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); + return mapper; + } + @Test public void testAllUsers() { when(userRepo.findAll()).thenReturn(users); diff --git a/src/test/java/org/tdl/vireo/model/ManagedConfigurationTest.java b/src/test/java/org/tdl/vireo/model/ManagedConfigurationTest.java index e545adbef4..41a17ff2f0 100644 --- a/src/test/java/org/tdl/vireo/model/ManagedConfigurationTest.java +++ b/src/test/java/org/tdl/vireo/model/ManagedConfigurationTest.java @@ -1,8 +1,18 @@ package org.tdl.vireo.model; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.InjectMocks; +import org.tdl.vireo.config.constant.ConfigurationName; + +import edu.tamu.weaver.validation.results.ValidationResults; public class ManagedConfigurationTest extends AbstractModelTest { @@ -30,4 +40,52 @@ private static Stream getParameterStream() { ); } + protected static Stream provideValidationParameters() { + return Stream.of( + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "1", "application", true), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "9", "application", true), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "24", "application", true), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, String.valueOf(Integer.MAX_VALUE), "application", true), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, null, "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, " ", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "0", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "-1", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "1.5", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "one", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "2147483648", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "1", "other", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, "1", "application", false), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, "10", "application", true) + ); + } + + @ParameterizedTest + @MethodSource("provideValidationParameters") + public void validatesPasswordResetExpiryWithoutWeakeningOtherSettings(String name, String value, + String type, boolean expectedValid) { + ManagedConfiguration configuration = new ManagedConfiguration(name, value, type); + + ValidationResults results = configuration.validate(configuration); + + assertEquals(expectedValid, results.isValid()); + if (!expectedValid) { + assertTrue(results.getMessages().containsKey("value")); + } + } + + @Test + public void expiryExceptionDoesNotAlterGenericValidation() { + ManagedConfiguration configuration = new ManagedConfiguration( + ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "1", "application"); + + assertTrue(configuration.validate(configuration).isValid()); + + configuration.setName(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED); + + ValidationResults results = configuration.validate(configuration); + assertEquals(false, results.isValid()); + assertTrue(results.getMessages().containsKey("value")); + } + } diff --git a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java new file mode 100644 index 0000000000..84f7521d7f --- /dev/null +++ b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java @@ -0,0 +1,618 @@ +package org.tdl.vireo.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Stream; + +import javax.mail.MessagingException; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.util.ReflectionTestUtils; +import org.tdl.vireo.config.constant.ConfigurationName; +import org.tdl.vireo.model.EmailTemplate; +import org.tdl.vireo.model.User; +import org.tdl.vireo.model.repo.ConfigurationRepo; +import org.tdl.vireo.model.repo.EmailTemplateRepo; +import org.tdl.vireo.utility.PasswordEligibilityRule; +import org.tdl.vireo.utility.TemplateUtility; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; + +/** + * Tests for the password-changed notification: failure handling, always-on dispatch, template + * content and leak containment. Logs are captured with a Logback {@link ListAppender}. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +@ExtendWith(MockitoExtension.class) +public class CredentialNotificationServiceTest { + + private static final String TEST_EMAIL = "aggieJack@tamu.edu"; + + private static final String TEST_PASSWORD = "sup3rS3cr3tPlaintextPassword"; + + private static final String TEST_TOKEN = "eyJ0b2tlbiI6ICJuZXZlci1sb2ctbWUifQ.c2lnbmF0dXJl"; + + private static final String TEMPLATE_SUBJECT = "Your password has changed"; + + private static final String TEMPLATE_MESSAGE = "Your password changed at {CHANGE_TIME}."; + + private static final String RENDERED_MESSAGE = "Your password changed at 2024-05-06 07:08:09 UTC."; + + private static final String NOTIFICATION_KIND = "password-changed notification"; + + @Mock + private EmailTemplateRepo emailTemplateRepo; + + @Mock + private TemplateUtility templateUtility; + + @Mock + private VireoEmailSender emailSender; + + // The service has no field of either type below, so they are never injected; gating on them would fail the always-on test. + @Mock + private ConfigurationRepo configurationRepo; + + @Mock + private PasswordFeatureAvailabilityService passwordFeatureAvailabilityService; + + @InjectMocks + private CredentialNotificationService credentialNotificationService; + + private Logger serviceLogger; + + private Level originalLevel; + + private ListAppender logAppender; + + private User user; + + @BeforeEach + public void setup() { + ReflectionTestUtils.setField(credentialNotificationService, "clock", Clock.fixed(Instant.parse("2024-05-06T07:08:09Z"), ZoneOffset.UTC)); + + user = new User(); + + user.setEmail(TEST_EMAIL); + user.setPassword(TEST_PASSWORD); + + logAppender = new ListAppender(); + + logAppender.start(); + + serviceLogger = (Logger) LoggerFactory.getLogger(CredentialNotificationService.class); + + // The test configuration pins org.tdl.vireo at ERROR; enable WARN for this logger only. + originalLevel = serviceLogger.getLevel(); + + serviceLogger.setLevel(Level.WARN); + serviceLogger.addAppender(logAppender); + } + + @AfterEach + public void teardown() { + serviceLogger.detachAppender(logAppender); + serviceLogger.setLevel(originalLevel); + + logAppender.stop(); + } + + /** An absent template is logged by name and skipped, with no send and no exception. */ + @Test + public void testNotifyPasswordChangedWithAbsentTemplate() { + when(emailTemplateRepo.findByNameOverride(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE)).thenReturn(null); + + credentialNotificationService.notifyPasswordChanged(user); + + verifyNoInteractions(emailSender); + verifyNoInteractions(templateUtility); + + String log = capturedLog(); + + assertTrue(log.contains(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE), "The absence of the email template must be logged naming the template, got: " + log); + assertTrue(log.contains(NOTIFICATION_KIND), "The skipped notification must be logged naming the notification, got: " + log); + + assertNoSensitiveValueLogged(log); + } + + /** {@code resolveTemplate} returns null and logs when no template is installed. */ + @Test + public void testResolveTemplateWithAbsentTemplate() { + when(emailTemplateRepo.findByNameOverride(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE)).thenReturn(null); + + assertNull(credentialNotificationService.resolveTemplate(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE), "An absent email template must resolve to null."); + + assertTrue(capturedLog().contains(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE), "The absence of the email template must be logged naming the template."); + } + + /** A mail failure is logged with the account email and does not propagate. */ + @Test + public void testNotifyPasswordChangedWithMailFailure() throws MessagingException { + when(emailTemplateRepo.findByNameOverride(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE)).thenReturn(new EmailTemplate(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE, TEMPLATE_SUBJECT, TEMPLATE_MESSAGE)); + + when(templateUtility.templateParameters(anyString(), any(String[][].class))).thenReturn(RENDERED_MESSAGE); + + doThrow(MessagingException.class).when(emailSender).sendEmail(anyString(), anyString(), anyString()); + + credentialNotificationService.notifyPasswordChanged(user); + + verify(emailSender).sendEmail(TEST_EMAIL, TEMPLATE_SUBJECT, RENDERED_MESSAGE); + + String log = capturedLog(); + + assertTrue(log.contains(TEST_EMAIL), "The mail failure must be logged with the Account identifier, got: " + log); + assertTrue(log.contains(NOTIFICATION_KIND), "The mail failure must be logged naming the notification, got: " + log); + + assertNoSensitiveValueLogged(log); + } + + /** Joins all captured log messages. */ + private String capturedLog() { + List messages = new ArrayList(); + + for (ILoggingEvent event : logAppender.list) { + messages.add(event.getFormattedMessage()); + } + + return String.join("\n", messages); + } + + /** Neither the password nor the token may appear in the log. */ + private void assertNoSensitiveValueLogged(String log) { + assertFalse(log.contains(TEST_PASSWORD), "No password value may appear in the log output, got: " + log); + assertFalse(log.contains(TEST_TOKEN), "No token value may appear in the log output, got: " + log); + } + + // Always-on notification. + + private static final long GENERATOR_SEED = 20250101L; + + private static final int RANDOM_CASE_COUNT = 64; + + private static final String APPLICATION_TYPE = "application"; + + /** Raw setting strings, both resolving and non-resolving. */ + private static final List RAW_SETTING_VALUES = Arrays.asList(null, "", " ", "true", "TRUE", " true ", "false", "False", "0", "1", "yes", "no", "junk"); + + private static final List RAW_EXPIRY_SETTING_VALUES = Arrays.asList(null, "", "0", "-1", "1", "24", "2147483647", "notanumber"); + + /** One account shape: eligibility fields, SSO affiliations and user settings. */ + private static final class AccountShape { + + private final String label; + + private final String email; + + private final String netid; + + private final String password; + + private final Set affiliations; + + private final Map settings; + + private AccountShape(String label, String email, String netid, String password, Set affiliations, Map settings) { + this.label = label; + this.email = email; + this.netid = netid; + this.password = password; + this.affiliations = affiliations; + this.settings = settings; + } + + private User toUser() { + User user = new User(); + + user.setEmail(email); + user.setNetid(netid); + user.setPassword(password); + user.setShibbolethAffiliations(new TreeSet(affiliations)); + user.setSettings(new TreeMap(settings)); + + return user; + } + + @Override + public String toString() { + return label; + } + + } + + private static Set affiliations(String... values) { + return new LinkedHashSet(Arrays.asList(values)); + } + + private static Map settings(String... keysAndValues) { + Map settings = new LinkedHashMap(); + + for (int i = 0; i < keysAndValues.length; i += 2) { + settings.put(keysAndValues[i], keysAndValues[i + 1]); + } + + return settings; + } + + /** The account shapes under test. */ + private static final List ACCOUNT_SHAPES = Arrays.asList( + new AccountShape("eligible", "eligible@tamu.edu", null, TEST_PASSWORD, affiliations(), settings()), + new AccountShape("sso-provisioned", "netid@tamu.edu", "aggieJack", TEST_PASSWORD, affiliations("student", "staff"), settings()), + new AccountShape("sso-no-password", "ssoonly@tamu.edu", "aggieJill", null, affiliations("member"), settings()), + new AccountShape("blank-password", "blank@tamu.edu", null, " ", affiliations(), settings()), + new AccountShape("suppression-flavoured-settings", "flagged@tamu.edu", null, TEST_PASSWORD, affiliations(), settings("notifications", "false", "suppressNotifications", "true", "emailNotifications", "off")), + new AccountShape("preferred-email-elsewhere", "account@tamu.edu", null, TEST_PASSWORD, affiliations("affiliate"), settings("preferedEmail", "somewhere.else@tamu.edu")) + ); + + /** Every account shape crossed with the boolean setting combinations, plus seeded random cases. */ + private static Stream provideAlwaysOnCases() { + List cases = new ArrayList(); + + List booleanValues = Arrays.asList("true", "false"); + + for (AccountShape shape : ACCOUNT_SHAPES) { + for (String enabledRaw : booleanValues) { + for (String changeRaw : booleanValues) { + for (String resetRaw : booleanValues) { + cases.add(Arguments.of(shape, enabledRaw, changeRaw, resetRaw, "24")); + } + } + } + } + + Random random = new Random(GENERATOR_SEED); + + for (int i = 0; i < RANDOM_CASE_COUNT; i++) { + cases.add(Arguments.of( + ACCOUNT_SHAPES.get(random.nextInt(ACCOUNT_SHAPES.size())), + RAW_SETTING_VALUES.get(random.nextInt(RAW_SETTING_VALUES.size())), + RAW_SETTING_VALUES.get(random.nextInt(RAW_SETTING_VALUES.size())), + RAW_SETTING_VALUES.get(random.nextInt(RAW_SETTING_VALUES.size())), + RAW_EXPIRY_SETTING_VALUES.get(random.nextInt(RAW_EXPIRY_SETTING_VALUES.size())) + )); + } + + return cases.stream(); + } + + /** The notification is sent exactly once to the account email for any account shape and any settings. */ + @ParameterizedTest(name = "[{index}] account={0}, enabled={1}, change={2}, reset={3}, expiryHours={4}") + @MethodSource("provideAlwaysOnCases") + public void testPasswordChangedNotificationIsAlwaysOn(AccountShape shape, String enabledRaw, String changeRaw, String resetRaw, String expiryRaw) throws MessagingException { + stubSetting(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, enabledRaw); + stubSetting(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, changeRaw); + stubSetting(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, resetRaw); + stubSetting(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, expiryRaw); + + stubAvailability(resolves(enabledRaw), resolves(changeRaw), resolves(resetRaw)); + + when(emailTemplateRepo.findByNameOverride(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE)).thenReturn(new EmailTemplate(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE, TEMPLATE_SUBJECT, TEMPLATE_MESSAGE)); + + when(templateUtility.templateParameters(anyString(), any(String[][].class))).thenReturn(RENDERED_MESSAGE); + + User target = shape.toUser(); + + credentialNotificationService.notifyPasswordChanged(target); + + assertEquals(PasswordEligibilityRule.isEligible(target), PasswordEligibilityRule.isEligible(shape.password, shape.netid), "The shape's eligibility classification is stable across both rule overloads"); + + verify(emailSender, times(1)).sendEmail(shape.email, TEMPLATE_SUBJECT, RENDERED_MESSAGE); + + verifyNoMoreInteractions(emailSender); + + verifyNoInteractions(configurationRepo); + verifyNoInteractions(passwordFeatureAvailabilityService); + } + + /** The service holds no settings collaborator and no public method takes a suppression flag. */ + @Test + public void testNoSuppressionSwitchExists() { + for (Field field : CredentialNotificationService.class.getDeclaredFields()) { + assertFalse(ConfigurationRepo.class.isAssignableFrom(field.getType()), "The notification service holds no configuration store reference, found field: " + field.getName()); + assertFalse(PasswordFeatureAvailabilityService.class.isAssignableFrom(field.getType()), "The notification service holds no availability service reference, found field: " + field.getName()); + } + + for (Method method : CredentialNotificationService.class.getDeclaredMethods()) { + if (!Modifier.isPublic(method.getModifiers()) || method.isSynthetic()) { + continue; + } + + for (Class parameterType : method.getParameterTypes()) { + assertFalse(boolean.class.equals(parameterType) || Boolean.class.equals(parameterType), "No public method of the notification service takes a flag that could suppress a dispatch, found: " + method.getName()); + } + } + + Method[] declared = CredentialNotificationService.class.getDeclaredMethods(); + + boolean found = false; + + for (Method method : declared) { + if ("notifyPasswordChanged".equals(method.getName())) { + found = true; + + assertEquals(1, method.getParameterCount(), "notifyPasswordChanged takes the target Account and nothing else"); + assertEquals(User.class, method.getParameterTypes()[0], "notifyPasswordChanged takes the target Account and nothing else"); + } + } + + assertTrue(found, "notifyPasswordChanged is declared on the notification service"); + } + + /** Mirrors the availability service's resolution rule so stubs match the real service. */ + private static boolean resolves(String raw) { + return raw != null && raw.trim().equalsIgnoreCase("true"); + } + + /** Stubs a raw setting value on the unwired configuration store. */ + private void stubSetting(String settingName, String rawValue) { + lenient().when(configurationRepo.getValueByNameAndType(eq(settingName), eq(APPLICATION_TYPE))).thenReturn(rawValue); + } + + /** Stubs the availability answers on the unwired availability service. */ + private void stubAvailability(boolean enabled, boolean change, boolean reset) { + lenient().when(passwordFeatureAvailabilityService.isPasswordLoginEnabled()).thenReturn(enabled); + lenient().when(passwordFeatureAvailabilityService.isChangeEnabled()).thenReturn(change); + lenient().when(passwordFeatureAvailabilityService.isResetEnabled()).thenReturn(reset); + lenient().when(passwordFeatureAvailabilityService.isChangeAvailable()).thenReturn(enabled && change); + lenient().when(passwordFeatureAvailabilityService.isResetAvailable()).thenReturn(enabled && reset); + } + + // Packaged SYSTEM_Password_Changed.email assertions, split the way SystemDataLoader splits it. + + private static final String PASSWORD_CHANGED_RESOURCE = "/emails/SYSTEM_Password_Changed.email"; + + private static final String SUPPORT_CONTACT_PHRASE = "vireo@myuniversity.edu or call us at xxx-555-xxxx"; + + private static final String SIGN_OFF = "The Vireo Team"; + + private static final String CHANGE_TIME_PLACEHOLDER = "{CHANGE_TIME}"; + + private static final String RESET_URL_PLACEHOLDER = "{RESET_URL}"; + + /** Shapes a hyperlink could take in a plain-text body. */ + private static final List HYPERLINK_MARKERS = Arrays.asList("http://", "https://", "www.", "mailto:", "href", " placeholders = new LinkedHashSet(); + + Matcher matcher = PLACEHOLDER_PATTERN.matcher(body); + + while (matcher.find()) { + placeholders.add(matcher.group()); + } + + assertEquals(new LinkedHashSet(Arrays.asList(CHANGE_TIME_PLACEHOLDER)), placeholders, "CHANGE_TIME is the only parameter the password-changed template body expands."); + + assertFalse(body.contains(TEST_PASSWORD), "No password value may appear in the template body, got: " + body); + assertFalse(body.toLowerCase().contains("{password"), "No password parameter may appear in the template body, got: " + body); + } + + /** Reads the packaged template from the classpath. */ + private String readPackagedPasswordChangedTemplate() throws IOException { + InputStream stream = CredentialNotificationServiceTest.class.getResourceAsStream(PASSWORD_CHANGED_RESOURCE); + + assertNotNull(stream, "The packaged resource " + PASSWORD_CHANGED_RESOURCE + " is on the classpath."); + + StringBuilder content = new StringBuilder(); + + BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)); + + try { + String line = reader.readLine(); + + while (line != null) { + content.append(line).append("\n"); + + line = reader.readLine(); + } + } finally { + reader.close(); + } + + return content.toString(); + } + + /** Strips comment lines the way {@code SystemDataLoader} does. */ + private String strippedOfComments(String raw) { + return raw.replaceAll("\\s*#.*[\\n\\r]{1}", ""); + } + + /** Extracts the subject the loader would extract. */ + private String packagedSubject(String raw) { + Matcher subjectMatcher = Pattern.compile("\\s*Subject:(.*)[\\n\\r]{1}").matcher(strippedOfComments(raw)); + + assertTrue(subjectMatcher.find(), "The loader can identify the template's subject."); + + return subjectMatcher.group(1).trim(); + } + + /** Extracts the body the loader would extract: everything after the Subject line. */ + private String packagedBody(String raw) { + String data = strippedOfComments(raw); + + int index = data.indexOf("\n"); + + if (index < 0) { + index = data.indexOf("\r"); + } + + assertTrue(index > 0, "The template body follows the Subject line."); + + return data.substring(index); + } + + // Leak containment across the outbound notification artefacts. + + private static final String[] LEAK_SECRET_SHAPES = { "plainsecret", " spaced secret ", "p@ss|word.{x}", "Ünïcödé-sëcret", "0123456789abcdef", "UPPER-lower-123" }; + + private static final String[] LEAK_SCENARIOS = { "sent", "absent-template", "mail-failure" }; + + /** Every scenario crossed with every secret shape, plus 100 seeded random secrets. */ + private static Stream provideLeakContainmentCases() { + List cases = new ArrayList(); + + for (String scenario : LEAK_SCENARIOS) { + for (String shape : LEAK_SECRET_SHAPES) { + cases.add(Arguments.of(scenario, shape)); + } + } + + Random random = new Random(GENERATOR_SEED); + + for (int i = 0; i < 100; i++) { + cases.add(Arguments.of(LEAK_SCENARIOS[random.nextInt(LEAK_SCENARIOS.length)], Long.toHexString(random.nextLong()) + Long.toHexString(random.nextLong()))); + } + + return cases.stream(); + } + + /** The dispatched subject, body and log records contain neither the password nor the token. */ + @ParameterizedTest(name = "[{index}] scenario={0}, base={1}") + @MethodSource("provideLeakContainmentCases") + public void testPasswordChangedNotificationLeakContainment(String scenario, String base) throws Exception { + String password = "pw-" + base; + String token = "tok." + base; + + user.setPassword(password); + user.setSettings(new TreeMap(settings("resetToken", token))); + + // Use the packaged subject and body so the shipped artefact is what is asserted. + String raw = readPackagedPasswordChangedTemplate(); + + if ("absent-template".equals(scenario)) { + when(emailTemplateRepo.findByNameOverride(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE)).thenReturn(null); + } else { + when(emailTemplateRepo.findByNameOverride(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE)).thenReturn(new EmailTemplate(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE, packagedSubject(raw), packagedBody(raw))); + + lenient().when(templateUtility.templateParameters(anyString(), any(String[][].class))).thenAnswer(invocation -> { + String message = invocation.getArgument(0); + String[][] parameters = invocation.getArgument(1); + + for (String[] parameter : parameters) { + message = message.replace("{" + parameter[0] + "}", parameter[1]); + } + + return message; + }); + } + + if ("mail-failure".equals(scenario)) { + doThrow(new MessagingException("transport failure")).when(emailSender).sendEmail(anyString(), anyString(), anyString()); + } + + credentialNotificationService.notifyPasswordChanged(user); + + List artefacts = new ArrayList(); + + artefacts.add(capturedLog()); + + if ("absent-template".equals(scenario)) { + verifyNoInteractions(emailSender); + } else { + ArgumentCaptor subject = ArgumentCaptor.forClass(String.class); + ArgumentCaptor body = ArgumentCaptor.forClass(String.class); + + verify(emailSender).sendEmail(eq(TEST_EMAIL), subject.capture(), body.capture()); + + assertTrue(body.getValue().contains("2024-05-06 07:08:09 UTC"), "The notification states the change time, got: " + body.getValue()); + + artefacts.add(subject.getValue()); + artefacts.add(body.getValue()); + } + + for (String artefact : artefacts) { + for (String secret : Arrays.asList(password, password.trim(), token, token.trim(), base, base.trim())) { + assertFalse(artefact.contains(secret), "No password or token value may appear in an outbound artefact, found '" + secret + "' in: " + artefact); + } + } + } + +} diff --git a/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java b/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java new file mode 100644 index 0000000000..bda86fca1c --- /dev/null +++ b/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java @@ -0,0 +1,412 @@ +package org.tdl.vireo.service; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.context.ActiveProfiles; +import org.tdl.vireo.config.constant.ConfigurationName; +import org.tdl.vireo.model.ManagedConfiguration; +import org.tdl.vireo.model.repo.ConfigurationRepo; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Tests for setting resolution, availability and expiry. Cases are boundary values plus + * fixed-seed random draws, fed through {@link ParameterizedTest}. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +@ExtendWith(MockitoExtension.class) +public class PasswordFeatureAvailabilityServiceTest { + + private static final String APPLICATION_TYPE = "application"; + + private static final long GENERATOR_SEED = 20250101L; + + private static final int RANDOM_CASE_COUNT = 48; + + /** Boundary raw setting strings. */ + private static final List RAW_VALUES = Arrays.asList( + null, + "", + " ", + "\t\n", + "true", + "TRUE", + "True", + " true ", + "\ttrue\n", + "truex", + "rue", + "false", + "False", + " false ", + "1", + "0", + "yes", + "no", + "on" + ); + + @Mock + private ConfigurationRepo configurationRepo; + + @InjectMocks + private PasswordFeatureAvailabilityService passwordFeatureAvailabilityService; + + /** Raw triples (enabled, change, reset); the random cases cover asymmetric change/reset pairings. */ + private static Stream provideRawSettingTriples() { + List cases = new ArrayList(); + + for (String enabledRaw : RAW_VALUES) { + for (String capabilityRaw : RAW_VALUES) { + cases.add(Arguments.of(enabledRaw, capabilityRaw, capabilityRaw)); + } + } + + Random random = new Random(GENERATOR_SEED); + + for (int i = 0; i < RANDOM_CASE_COUNT; i++) { + cases.add(Arguments.of(randomRawValue(random), randomRawValue(random), randomRawValue(random))); + } + + return cases.stream(); + } + + /** Draws a boundary value or a random junk string. */ + private static String randomRawValue(Random random) { + if (random.nextBoolean()) { + return RAW_VALUES.get(random.nextInt(RAW_VALUES.size())); + } + + int length = random.nextInt(8); + + StringBuilder junk = new StringBuilder(); + + for (int i = 0; i < length; i++) { + junk.append((char) ('!' + random.nextInt(90))); + } + + return junk.toString(); + } + + /** Expected resolution: trimmed, case-insensitive {@code "true"}; null is false. */ + private static boolean expectedResolution(String raw) { + return raw != null && raw.trim().equalsIgnoreCase("true"); + } + + @ParameterizedTest(name = "[{index}] enabled={0}, change={1}, reset={2}") + @MethodSource("provideRawSettingTriples") + public void testSettingResolutionAndAvailabilityConjunction(String enabledRaw, String changeRaw, String resetRaw) { + stub(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, enabledRaw); + stub(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, changeRaw); + stub(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, resetRaw); + + boolean expectedEnabled = expectedResolution(enabledRaw); + boolean expectedChange = expectedResolution(changeRaw); + boolean expectedReset = expectedResolution(resetRaw); + + assertEquals(expectedEnabled, passwordFeatureAvailabilityService.isPasswordLoginEnabled(), "Resolution of the Password_Login_Setting"); + assertEquals(expectedChange, passwordFeatureAvailabilityService.isChangeEnabled(), "Resolution of auth.pass.change.enabled"); + assertEquals(expectedReset, passwordFeatureAvailabilityService.isResetEnabled(), "Resolution of auth.pass.reset.enabled"); + + assertEquals(expectedEnabled && expectedChange, passwordFeatureAvailabilityService.isChangeAvailable(), "Availability of self-service password change"); + + assertEquals(expectedEnabled && expectedReset, passwordFeatureAvailabilityService.isResetAvailable(), "Availability of administrator-initiated reset"); + } + + /** An absent login setting makes both capabilities unavailable. */ + @Test + public void testAbsentPasswordLoginSettingLeavesBothCapabilitiesUnavailable() { + stub(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, null); + stub(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, "true"); + stub(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, "true"); + + assertFalse(passwordFeatureAvailabilityService.isChangeAvailable(), "Change is unavailable when the Password_Login_Setting is absent"); + assertFalse(passwordFeatureAvailabilityService.isResetAvailable(), "Reset is unavailable when the Password_Login_Setting is absent"); + } + + /** Boundary raw expiry strings. */ + private static final List RAW_EXPIRY_VALUES = Arrays.asList( + null, + "", + " ", + "\t\n", + "0", + "-1", + "1", + "2", + "24", + String.valueOf(Integer.MAX_VALUE), + "2147483648", + "-2147483648", + "99999999999999999999", + "abc", + "12.5", + "1e3", + "24abc", + " 24 ", + "+24", + "0x18" + ); + + private static final int RANDOM_EXPIRY_CASE_COUNT = 96; + + /** Boundary expiry values plus seeded random draws. */ + private static Stream provideRawExpiryValues() { + List cases = new ArrayList(); + + for (String raw : RAW_EXPIRY_VALUES) { + cases.add(Arguments.of(raw)); + } + + Random random = new Random(GENERATOR_SEED); + + for (int i = 0; i < RANDOM_EXPIRY_CASE_COUNT; i++) { + cases.add(Arguments.of(randomRawExpiryValue(random))); + } + + return cases.stream(); + } + + /** Draws a boundary, a valid, a non-positive or a junk expiry value. */ + private static String randomRawExpiryValue(Random random) { + switch (random.nextInt(4)) { + case 0: + return RAW_EXPIRY_VALUES.get(random.nextInt(RAW_EXPIRY_VALUES.size())); + case 1: + return String.valueOf(1 + random.nextInt(Integer.MAX_VALUE)); + case 2: + return String.valueOf(-random.nextInt(1000)); + default: + int length = 1 + random.nextInt(8); + + StringBuilder junk = new StringBuilder(); + + for (int i = 0; i < length; i++) { + junk.append((char) ('a' + random.nextInt(26))); + } + + return junk.toString(); + } + } + + /** Expected resolution: a trimmed integer of at least 1, otherwise the default of 24. */ + private static int expectedExpiry(String raw) { + if (raw == null) { + return PasswordFeatureAvailabilityService.DEFAULT_RESET_EXPIRY_HOURS; + } + + int parsed; + + try { + parsed = Integer.parseInt(raw.trim()); + } catch (NumberFormatException e) { + return PasswordFeatureAvailabilityService.DEFAULT_RESET_EXPIRY_HOURS; + } + + if (parsed < 1) { + return PasswordFeatureAvailabilityService.DEFAULT_RESET_EXPIRY_HOURS; + } + + return parsed; + } + + /** Expiry resolves per the rule, with a single read and no write-back to the store. */ + @ParameterizedTest(name = "[{index}] expiryHours={0}") + @MethodSource("provideRawExpiryValues") + public void testExpiryValueResolution(String raw) { + stub(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, raw); + + int expected = expectedExpiry(raw); + + assertEquals(expected, passwordFeatureAvailabilityService.getResetExpiryHours(), "Resolution of auth.pass.reset.expiryHours for raw value '" + raw + "'"); + + verify(configurationRepo, times(1)).getValueByNameAndType(eq(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS), eq(APPLICATION_TYPE)); + + verify(configurationRepo, never()).create(anyString(), anyString(), anyString()); + verify(configurationRepo, never()).create(any(ManagedConfiguration.class)); + verify(configurationRepo, never()).save(any(ManagedConfiguration.class)); + verify(configurationRepo, never()).update(any(ManagedConfiguration.class)); + verify(configurationRepo, never()).reset(any(ManagedConfiguration.class)); + verify(configurationRepo, never()).delete(any(ManagedConfiguration.class)); + + verifyNoMoreInteractions(configurationRepo); + } + + private void stub(String settingName, String rawValue) { + lenient().when(configurationRepo.getValueByNameAndType(eq(settingName), eq(APPLICATION_TYPE))).thenReturn(rawValue); + } + + /** Stubs a setting against a mutable holder so the value can change between requests. */ + private void stubDynamic(String settingName, String[] holder) { + lenient().when(configurationRepo.getValueByNameAndType(eq(settingName), eq(APPLICATION_TYPE))).thenAnswer(invocation -> holder[0]); + } + + // Seeding, constant and per-request resolution assertions. + + private static final String SYSTEM_DEFAULTS_RESOURCE = "/settings/SYSTEM_Defaults.json"; + + private static final String SHIBBOLETH_TYPE = "shibboleth"; + + /** The four seeded settings and their expected default values. */ + private static Stream provideSeededDefaults() { + return Stream.of( + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, "true"), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, "false"), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, "false"), + Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "24") + ); + } + + /** Reads the settings seed the way {@code DefaultSettingsService} does. */ + private static JsonNode readSystemDefaults() throws IOException { + try (InputStream stream = PasswordFeatureAvailabilityServiceTest.class.getResourceAsStream(SYSTEM_DEFAULTS_RESOURCE)) { + assertNotNull(stream, "The Default_Settings_Seed resource " + SYSTEM_DEFAULTS_RESOURCE + " is on the classpath"); + + // The seed has a multi-line string value, so tolerate raw control characters as the application does. + ObjectMapper objectMapper = new ObjectMapper(); + + objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); + + return objectMapper.readTree(stream); + } + } + + /** Returns the seeded value for a setting under a type, or null when absent. */ + private static String seededValue(JsonNode defaults, String type, String name) { + JsonNode entries = defaults.get(type); + + if (entries == null || !entries.isArray()) { + return null; + } + + for (JsonNode entry : entries) { + if (entry.has(name)) { + return entry.get(name).asText(); + } + } + + return null; + } + + /** Each setting is seeded under {@code application} only; a wrong type would be invisible to lookups by type. */ + @ParameterizedTest(name = "[{index}] {0} = {1}") + @MethodSource("provideSeededDefaults") + public void testSettingIsSeededUnderTheApplicationKey(String settingName, String expectedValue) throws IOException { + JsonNode defaults = readSystemDefaults(); + + assertEquals(expectedValue, seededValue(defaults, APPLICATION_TYPE, settingName), "Seeded default for '" + settingName + "' under the application key"); + + assertNull(seededValue(defaults, SHIBBOLETH_TYPE, settingName), "'" + settingName + "' is not seeded under the shibboleth key"); + } + + /** The setting names are declared in {@code ConfigurationName}. */ + @Test + public void testConfigurationNameConstants() { + assertEquals("auth.pass.enabled", ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, "The Password_Login_Setting constant"); + assertEquals("auth.pass.change.enabled", ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, "The auth.pass.change.enabled constant"); + assertEquals("auth.pass.reset.enabled", ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, "The auth.pass.reset.enabled constant"); + assertEquals("auth.pass.reset.expiryHours", ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "The auth.pass.reset.expiryHours constant"); + } + + /** Every setting is read on every request; read counts scaling with requests rules out caching. */ + @Test + public void testEverySettingIsResolvedOnEveryRequest() { + stub(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, "true"); + stub(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, "true"); + stub(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, "true"); + stub(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "24"); + + int requests = 5; + + for (int i = 0; i < requests; i++) { + passwordFeatureAvailabilityService.isChangeAvailable(); + passwordFeatureAvailabilityService.isResetAvailable(); + passwordFeatureAvailabilityService.getResetExpiryHours(); + } + + // Both conjunctions read the Password_Login_Setting, so it is read twice per request. + verify(configurationRepo, times(2 * requests)).getValueByNameAndType(eq(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED), eq(APPLICATION_TYPE)); + verify(configurationRepo, times(requests)).getValueByNameAndType(eq(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED), eq(APPLICATION_TYPE)); + verify(configurationRepo, times(requests)).getValueByNameAndType(eq(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED), eq(APPLICATION_TYPE)); + verify(configurationRepo, times(requests)).getValueByNameAndType(eq(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS), eq(APPLICATION_TYPE)); + + verifyNoMoreInteractions(configurationRepo); + } + + /** A changed stored value governs the next request; each boolean is flipped independently. */ + @Test + public void testFlippedStoredValueGovernsTheNextRequest() { + String[] enabled = { "true" }; + String[] change = { "true" }; + String[] reset = { "true" }; + + stubDynamic(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, enabled); + stubDynamic(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED, change); + stubDynamic(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED, reset); + + assertTrue(passwordFeatureAvailabilityService.isChangeAvailable(), "Change is available on the first request"); + assertTrue(passwordFeatureAvailabilityService.isResetAvailable(), "Reset is available on the first request"); + + change[0] = "false"; + + assertFalse(passwordFeatureAvailabilityService.isChangeAvailable(), "The flipped auth.pass.change.enabled governs the second request"); + assertTrue(passwordFeatureAvailabilityService.isResetAvailable(), "Reset is unaffected by the change setting"); + + change[0] = "true"; + reset[0] = "false"; + + assertTrue(passwordFeatureAvailabilityService.isChangeAvailable(), "The restored auth.pass.change.enabled governs the next request"); + assertFalse(passwordFeatureAvailabilityService.isResetAvailable(), "The flipped auth.pass.reset.enabled governs the next request"); + + reset[0] = "true"; + enabled[0] = "false"; + + assertFalse(passwordFeatureAvailabilityService.isChangeAvailable(), "The flipped Password_Login_Setting governs the next request for change"); + assertFalse(passwordFeatureAvailabilityService.isResetAvailable(), "The flipped Password_Login_Setting governs the next request for reset"); + } + + /** A changed expiry value governs the next request. */ + @Test + public void testFlippedExpiryValueGovernsTheNextRequest() { + String[] expiry = { "24" }; + + stubDynamic(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, expiry); + + assertEquals(24, passwordFeatureAvailabilityService.getResetExpiryHours(), "The seeded expiry governs the first request"); + + expiry[0] = "48"; + + assertEquals(48, passwordFeatureAvailabilityService.getResetExpiryHours(), "The flipped expiry governs the second request"); + } + +} diff --git a/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java new file mode 100644 index 0000000000..b1cfd7c23f --- /dev/null +++ b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java @@ -0,0 +1,649 @@ +package org.tdl.vireo.service; + +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Random; +import java.util.stream.Stream; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.util.ReflectionTestUtils; +import org.tdl.vireo.model.Role; +import org.tdl.vireo.model.User; +import org.tdl.vireo.model.repo.UserRepo; + +/** + * Property tests for {@link ResetTokenService}. Cases are enumerated boundary values crossed with a + * fixed-seed {@link Random}, fed through {@link ParameterizedTest}. No property-based testing + * library is used. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +@ExtendWith(MockitoExtension.class) +public class ResetTokenServiceTest { + + private static final String SIGNING_SECRET = "verysecretsecret"; + + private static final long GENERATOR_SEED = 20250101L; + + private static final int DEFAULT_EXPIRY_HOURS = 24; + + @Mock + private UserRepo userRepo; + + @Mock + private PasswordFeatureAvailabilityService availabilityService; + + @Spy + private BCryptPasswordEncoder passwordEncoder; + + @InjectMocks + private ResetTokenService resetTokenService; + + private void inject(Clock clock) { + ReflectionTestUtils.setField(resetTokenService, "signingSecret", SIGNING_SECRET); + ReflectionTestUtils.setField(resetTokenService, "clock", clock); + } + + private static User userWith(String email, String storedHash) { + User user = new User(email, "First", "Last", storedHash, Role.ROLE_STUDENT); + return user; + } + + // --------------------------------------------------------------------- + // Round trip: a constructed token verifies back to its email and issued-at instant. + // --------------------------------------------------------------------- + + static Stream roundTripCases() { + List emails = new ArrayList<>(Arrays.asList( + "student@example.edu", + "a@b.co", + // email containing a literal '|' — the case right-to-left parsing exists for + "weird|pipe@example.edu", + "two|pipes|here@example.edu", + "UPPER.Case@Example.EDU" + )); + + List hashes = new ArrayList<>(Arrays.asList( + "$2a$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ012345", + "plainhash", + "$2a$10$0000000000000000000000.0000000000000000000000000000000" + )); + + // instants: boundary epoch-seconds plus a sub-second-nanos instant that must truncate + List instants = new ArrayList<>(Arrays.asList( + Instant.ofEpochSecond(0), + Instant.ofEpochSecond(1_700_000_000L), + // sub-second nanos: epoch-second precision must truncate to 1_700_000_123 + Instant.ofEpochSecond(1_700_000_123L, 987_654_321L) + )); + + List cases = new ArrayList<>(); + for (String email : emails) { + for (String hash : hashes) { + for (Instant instant : instants) { + cases.add(Arguments.of(email, hash, instant)); + } + } + } + + Random random = new Random(GENERATOR_SEED); + while (cases.size() < 120) { + String email = "user" + random.nextInt(100000) + (random.nextBoolean() ? "|p" : "") + "@example.edu"; + String hash = "$2a$10$" + random.nextLong(); + Instant instant = Instant.ofEpochSecond( + 1_000_000L + (long) (random.nextDouble() * 1_000_000_000L), + random.nextInt(1_000_000_000)); + cases.add(Arguments.of(email, hash, instant)); + } + + return cases.stream(); + } + + @ParameterizedTest + @MethodSource("roundTripCases") + public void roundTripVerifiesValid(String email, String storedHash, Instant issuedAt) { + Clock fixed = Clock.fixed(issuedAt, ZoneOffset.UTC); + inject(fixed); + + User user = userWith(email, storedHash); + when(userRepo.findByEmail(email)).thenReturn(user); + when(availabilityService.getResetExpiryHours()).thenReturn(DEFAULT_EXPIRY_HOURS); + + String token = resetTokenService.construct(user); + ResetTokenVerification result = resetTokenService.verify(token); + + assertEquals(ResetTokenVerification.Status.VALID, result.getStatus(), + "round-tripped token should verify VALID for email " + email); + assertTrue(result.isValid()); + assertEquals(email, result.getEmail()); + // issued-at carries epoch-second precision only; sub-second nanos must truncate + assertEquals(issuedAt.getEpochSecond(), result.getIssuedAt().getEpochSecond()); + assertEquals(Instant.ofEpochSecond(issuedAt.getEpochSecond()), result.getIssuedAt()); + } + + // Signed epoch values outside Instant's range are malformed and rejected before account lookup. + + static Stream issuedAtBoundaryCases() { + return Stream.of( + Arguments.of(Long.MAX_VALUE, Instant.EPOCH, ResetTokenVerification.Status.INVALID, false, "Long.MAX_VALUE"), + Arguments.of(Long.MIN_VALUE, Instant.EPOCH, ResetTokenVerification.Status.INVALID, false, "Long.MIN_VALUE"), + Arguments.of(Instant.MAX.getEpochSecond() + 1, Instant.EPOCH, ResetTokenVerification.Status.INVALID, false, "above Instant.MAX"), + Arguments.of(Instant.MIN.getEpochSecond() - 1, Instant.EPOCH, ResetTokenVerification.Status.INVALID, false, "below Instant.MIN"), + Arguments.of(Instant.MAX.getEpochSecond(), Instant.MAX, ResetTokenVerification.Status.VALID, true, "Instant.MAX"), + Arguments.of(Instant.MIN.getEpochSecond(), Instant.MIN, ResetTokenVerification.Status.VALID, true, "Instant.MIN") + ); + } + + @ParameterizedTest(name = "[{index}] issued-at {4}") + @MethodSource("issuedAtBoundaryCases") + public void issuedAtMustFitInstantRange(long issuedAtEpochSecond, Instant verificationTime, + ResetTokenVerification.Status expectedStatus, boolean expectAccountLookup, String label) throws Exception { + inject(Clock.fixed(verificationTime, ZoneOffset.UTC)); + + String email = "timestamp@example.edu"; + String storedHash = "stored-password-hash"; + User user = userWith(email, storedHash); + + if (expectAccountLookup) { + when(userRepo.findByEmail(email)).thenReturn(user); + when(availabilityService.getResetExpiryHours()).thenReturn(DEFAULT_EXPIRY_HOURS); + } + + String token = signedTokenWithIssuedAt(email, storedHash, issuedAtEpochSecond); + ResetTokenVerification result = assertDoesNotThrow(() -> resetTokenService.verify(token)); + + assertEquals(expectedStatus, result.getStatus(), label); + + if (expectAccountLookup) { + verify(userRepo).findByEmail(email); + verify(availabilityService).getResetExpiryHours(); + } else { + verify(userRepo, never()).findByEmail(anyString()); + verify(availabilityService, never()).getResetExpiryHours(); + } + } + + private String signedTokenWithIssuedAt(String email, String storedHash, long issuedAtEpochSecond) throws Exception { + String bindingValue = resetTokenService.deriveBindingValue(storedHash); + String payload = email + "|" + bindingValue + "|" + issuedAtEpochSecond; + String encodedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(payload.getBytes(StandardCharsets.UTF_8)); + + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(SIGNING_SECRET.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String encodedSignature = Base64.getUrlEncoder().withoutPadding().encodeToString(mac.doFinal(encodedPayload.getBytes(StandardCharsets.US_ASCII))); + + return encodedPayload + "." + encodedSignature; + } + + // --------------------------------------------------------------------- + // A stored-password change invalidates every earlier token. + // --------------------------------------------------------------------- + + static Stream passwordChangeCases() { + List emails = Arrays.asList( + "change@example.edu", + "pipe|user@example.edu"); + + // The load-bearing case is the EQUAL-VALUE pair: re-encoding the same password value + // yields a different hash (fresh salt), so a token built before the change must fail after. + List oldPasswords = Arrays.asList("CorrectHorse", "password123", "CorrectHorse"); + List newPasswords = Arrays.asList("CorrectHorse", "password123!", "different"); + + List cases = new ArrayList<>(); + Random random = new Random(GENERATOR_SEED); + for (String email : emails) { + for (int i = 0; i < oldPasswords.size(); i++) { + cases.add(Arguments.of(email, oldPasswords.get(i), newPasswords.get(i))); + } + } + while (cases.size() < 100) { + String pw = "pw" + random.nextInt(1_000_000); + boolean equalValue = random.nextBoolean(); + String email = "u" + random.nextInt(100000) + "@example.edu"; + cases.add(Arguments.of(email, pw, equalValue ? pw : pw + "x")); + } + return cases.stream(); + } + + @ParameterizedTest + @MethodSource("passwordChangeCases") + public void storedPasswordChangeInvalidatesToken(String email, String oldPassword, String newPassword) { + Clock fixed = Clock.fixed(Instant.ofEpochSecond(1_700_000_000L), ZoneOffset.UTC); + inject(fixed); + + String oldHash = passwordEncoder.encode(oldPassword); + User userBefore = userWith(email, oldHash); + + when(userRepo.findByEmail(email)).thenReturn(userBefore); + lenient().when(availabilityService.getResetExpiryHours()).thenReturn(DEFAULT_EXPIRY_HOURS); + + String token = resetTokenService.construct(userBefore); + + // Sanity: token verifies before the change. + assertEquals(ResetTokenVerification.Status.VALID, resetTokenService.verify(token).getStatus()); + + // Re-encode (even the SAME value re-salts to a different hash) and swap the stored Account. + String newHash = passwordEncoder.encode(newPassword); + assertNotEquals(oldHash, newHash, "BCrypt re-encoding must produce a different hash"); + User userAfter = userWith(email, newHash); + when(userRepo.findByEmail(email)).thenReturn(userAfter); + + ResetTokenVerification result = resetTokenService.verify(token); + assertEquals(ResetTokenVerification.Status.INVALID, result.getStatus(), + "token built against old hash must be INVALID after the stored password changes"); + } + + // --------------------------------------------------------------------- + // Expiry boundary: VALID in [0, expiryHours), EXPIRED at or beyond, INVALID for negative offsets. + // --------------------------------------------------------------------- + + static Stream expiryCases() { + List expiryHoursValues = Arrays.asList(1, 24, 72); + // offsets expressed as a fraction/multiple relative to the boundary, in whole hours + List hourOffsets = new ArrayList<>(Arrays.asList( + -100L, -24L, -1L, // negative -> INVALID + 0L, // exactly issued -> VALID + 1L, 23L, // within window -> VALID (for larger expiries) + 24L, 25L, 72L, 100L)); // at/after boundary -> EXPIRED (depending on expiry) + + List cases = new ArrayList<>(); + for (Integer expiry : expiryHoursValues) { + for (Long offset : hourOffsets) { + cases.add(Arguments.of(expiry, offset)); + } + } + + Random random = new Random(GENERATOR_SEED); + while (cases.size() < 100) { + int expiry = 1 + random.nextInt(100); + long offset = -50L + random.nextInt(200); + cases.add(Arguments.of(expiry, offset)); + } + return cases.stream(); + } + + @ParameterizedTest + @MethodSource("expiryCases") + public void expiryPartitionHolds(int expiryHours, long hourOffset) { + String email = "expiry@example.edu"; + String hash = "$2a$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ012345"; + + Instant issuedAt = Instant.ofEpochSecond(1_700_000_000L); + + // Construct at issuedAt. + inject(Clock.fixed(issuedAt, ZoneOffset.UTC)); + User user = userWith(email, hash); + when(userRepo.findByEmail(email)).thenReturn(user); + when(availabilityService.getResetExpiryHours()).thenReturn(expiryHours); + + String token = resetTokenService.construct(user); + + // Move the clock to issuedAt + hourOffset hours and verify. + Instant verifyAt = issuedAt.plusSeconds(hourOffset * 3600L); + ReflectionTestUtils.setField(resetTokenService, "clock", Clock.fixed(verifyAt, ZoneOffset.UTC)); + + ResetTokenVerification result = resetTokenService.verify(token); + + ResetTokenVerification.Status expected; + if (hourOffset < 0) { + expected = ResetTokenVerification.Status.INVALID; + } else if (hourOffset < expiryHours) { + expected = ResetTokenVerification.Status.VALID; + } else { + expected = ResetTokenVerification.Status.EXPIRED; + } + + assertEquals(expected, result.getStatus(), + "expiry=" + expiryHours + "h offset=" + hourOffset + "h"); + } + + // --------------------------------------------------------------------- + // Single use and sibling invalidation. The clock stays inside the expiry window throughout, so + // an expiry result cannot be mistaken for the single-use result. + // --------------------------------------------------------------------- + + static Stream singleUseCases() { + List emails = Arrays.asList( + "single@example.edu", + "sib|ling@example.edu"); + List passwords = Arrays.asList("FirstPass", "another-pass", "Zz9"); + List siblingCounts = Arrays.asList(1, 2, 3); + + List cases = new ArrayList<>(); + Random random = new Random(GENERATOR_SEED); + for (String email : emails) { + for (String password : passwords) { + for (Integer siblings : siblingCounts) { + cases.add(Arguments.of(email, password, siblings)); + } + } + } + while (cases.size() < 100) { + cases.add(Arguments.of( + "u" + random.nextInt(100000) + "@example.edu", + "pw" + random.nextInt(1_000_000), + 1 + random.nextInt(4))); + } + return cases.stream(); + } + + @ParameterizedTest + @MethodSource("singleUseCases") + public void singleUseInvalidatesRedeemedAndSiblingTokens(String email, String password, int siblingCount) { + // Keep the clock inside the expiry window the entire time. + Instant issuedAt = Instant.ofEpochSecond(1_700_000_000L); + inject(Clock.fixed(issuedAt, ZoneOffset.UTC)); + + String oldHash = passwordEncoder.encode(password); + User userBefore = userWith(email, oldHash); + when(userRepo.findByEmail(email)).thenReturn(userBefore); + lenient().when(availabilityService.getResetExpiryHours()).thenReturn(DEFAULT_EXPIRY_HOURS); + + // Issue the redeemed token plus a number of sibling tokens, all against the old hash. + String redeemed = resetTokenService.construct(userBefore); + List siblings = new ArrayList<>(); + for (int i = 0; i < siblingCount; i++) { + siblings.add(resetTokenService.construct(userBefore)); + } + + // All verify while the hash is unchanged. + assertEquals(ResetTokenVerification.Status.VALID, resetTokenService.verify(redeemed).getStatus()); + for (String sibling : siblings) { + assertEquals(ResetTokenVerification.Status.VALID, resetTokenService.verify(sibling).getStatus()); + } + + // Redeem: the stored password changes (re-salted). Clock stays in-window. + String newHash = passwordEncoder.encode(password); + User userAfter = userWith(email, newHash); + when(userRepo.findByEmail(email)).thenReturn(userAfter); + + // The redeemed token is now INVALID (single use), not EXPIRED. + assertEquals(ResetTokenVerification.Status.INVALID, resetTokenService.verify(redeemed).getStatus(), + "redeemed token must be single-use INVALID, not EXPIRED"); + + // Every sibling issued against the old hash is also INVALID (cross-invalidation). + for (String sibling : siblings) { + assertEquals(ResetTokenVerification.Status.INVALID, resetTokenService.verify(sibling).getStatus(), + "sibling token must be invalidated by the stored password change"); + } + } + + // --------------------------------------------------------------------- + // Tamper rejection: any mutation to either segment of an otherwise-valid token verifies as + // INVALID. The clock stays inside the expiry window so the untampered baseline verifies VALID. + // --------------------------------------------------------------------- + + /** The base64url alphabet, used to substitute a character for a different-but-valid one. */ + private static final String BASE64URL_ALPHABET = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + + /** Which of the two token segments a mutation targets. */ + private enum Segment { PAYLOAD, SIGNATURE } + + /** The kind of single-character mutation applied to a segment. */ + private enum Mutation { FLIP_BIT, INSERT, DELETE, SUBSTITUTE_BASE64URL } + + static Stream tamperCases() { + List emails = Arrays.asList( + "tamper@example.edu", + "pipe|tamper@example.edu"); + List hashes = Arrays.asList( + "$2a$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ012345", + "plainhash"); + + // Every segment crossed with every mutation kind — both segments the criterion names, + // and both the "decode fails" and "decode succeeds but content changed" paths. + List cases = new ArrayList<>(); + Random random = new Random(GENERATOR_SEED); + for (String email : emails) { + for (String hash : hashes) { + for (Segment segment : Segment.values()) { + for (Mutation mutation : Mutation.values()) { + // A few randomized positions per (segment, mutation) pair to reach >= 100. + for (int i = 0; i < 4; i++) { + cases.add(Arguments.of(email, hash, segment, mutation, random.nextInt(1_000_000))); + } + } + } + } + } + while (cases.size() < 100) { + String email = "u" + random.nextInt(100000) + "@example.edu"; + cases.add(Arguments.of( + email, + "$2a$10$" + random.nextLong(), + Segment.values()[random.nextInt(Segment.values().length)], + Mutation.values()[random.nextInt(Mutation.values().length)], + random.nextInt(1_000_000))); + } + return cases.stream(); + } + + @ParameterizedTest + @MethodSource("tamperCases") + public void tamperedTokenVerifiesInvalid(String email, String storedHash, Segment segment, + Mutation mutation, int positionSeed) { + Instant issuedAt = Instant.ofEpochSecond(1_700_000_000L); + inject(Clock.fixed(issuedAt, ZoneOffset.UTC)); + + User user = userWith(email, storedHash); + when(userRepo.findByEmail(email)).thenReturn(user); + lenient().when(availabilityService.getResetExpiryHours()).thenReturn(DEFAULT_EXPIRY_HOURS); + + String token = resetTokenService.construct(user); + + // Baseline sanity: the untampered token verifies VALID for the same inputs, so a broken + // baseline cannot mask the property. + assertEquals(ResetTokenVerification.Status.VALID, resetTokenService.verify(token).getStatus(), + "untampered baseline token must verify VALID for email " + email); + + String[] parts = token.split("\\.", -1); + String payloadSeg = parts[0]; + String signatureSeg = parts[1]; + + String targetSeg = (segment == Segment.PAYLOAD) ? payloadSeg : signatureSeg; + String mutatedSeg = mutate(targetSeg, mutation, positionSeed); + + String tampered = (segment == Segment.PAYLOAD) + ? mutatedSeg + "." + signatureSeg + : payloadSeg + "." + mutatedSeg; + + // Guard against a no-op mutation accidentally reproducing the original token. + assumeTrue(!tampered.equals(token), "mutation was a no-op; skipping this case"); + + ResetTokenVerification result = resetTokenService.verify(tampered); + assertEquals(ResetTokenVerification.Status.INVALID, result.getStatus(), + "tampered " + segment + " via " + mutation + " must verify INVALID, not " + + result.getStatus()); + } + + /** + * Applies a single-character mutation to a segment. Position is derived from {@code positionSeed} + * so cases are reproducible under the fixed generator seed. + */ + private static String mutate(String segment, Mutation mutation, int positionSeed) { + if (segment.isEmpty()) { + // Degenerate; append a character so the result still differs from the empty input. + return "A"; + } + int index = Math.floorMod(positionSeed, segment.length()); + char[] chars = segment.toCharArray(); + switch (mutation) { + case FLIP_BIT: + // XOR a low bit — may or may not leave a valid base64url character, exercising the + // "decode fails" path as well as the "signature mismatch on a decodable string" path. + chars[index] = (char) (chars[index] ^ 0x01); + return new String(chars); + case INSERT: + return segment.substring(0, index) + 'A' + segment.substring(index); + case DELETE: + if (segment.length() == 1) { + // Deleting the only character yields an empty segment; append instead so the + // tampered token remains a two-segment, non-empty structure that still differs. + return segment + "A"; + } + return segment.substring(0, index) + segment.substring(index + 1); + case SUBSTITUTE_BASE64URL: + // Swap for a DIFFERENT valid base64url character, keeping the segment decodable so + // the content-changed-but-still-decodes path is exercised. + char original = chars[index]; + char replacement = original; + int offset = 1 + Math.floorMod(positionSeed, BASE64URL_ALPHABET.length() - 1); + int originalPos = BASE64URL_ALPHABET.indexOf(original); + if (originalPos < 0) { + // Original is not an alphabet character (e.g. padding); just pick 'A' vs 'B'. + replacement = (original == 'A') ? 'B' : 'A'; + } else { + replacement = BASE64URL_ALPHABET.charAt( + (originalPos + offset) % BASE64URL_ALPHABET.length()); + } + chars[index] = replacement; + return new String(chars); + default: + throw new IllegalStateException("unhandled mutation " + mutation); + } + } + + // --------------------------------------------------------------------- + // verify has no side effects: across a construct-and-verify cycle the only repository + // interaction is the read-only findByEmail, and the stored hash is byte-identical afterwards. + // All three outcomes (VALID, EXPIRED, INVALID) are exercised so none can hide a write. + // --------------------------------------------------------------------- + + /** Which verification outcome a case is engineered to produce, so the whole partition is covered. */ + private enum VerifyOutcome { VALID, EXPIRED, INVALID } + + static Stream noSideEffectCases() { + List emails = new ArrayList<>(Arrays.asList( + "noeffect@example.edu", + "a@b.co", + "pipe|user@example.edu", + "UPPER.Case@Example.EDU")); + + List hashes = new ArrayList<>(Arrays.asList( + "$2a$10$abcdefghijklmnopqrstuuABCDEFGHIJKLMNOPQRSTUVWXYZ012345", + "plainhash", + "$2a$10$0000000000000000000000.0000000000000000000000000000000")); + + List expiryHoursValues = Arrays.asList(1, 24, 72); + + List cases = new ArrayList<>(); + for (String email : emails) { + for (String hash : hashes) { + for (Integer expiry : expiryHoursValues) { + for (VerifyOutcome outcome : VerifyOutcome.values()) { + cases.add(Arguments.of(email, hash, expiry, outcome)); + } + } + } + } + + Random random = new Random(GENERATOR_SEED); + while (cases.size() < 120) { + String email = "user" + random.nextInt(100000) + (random.nextBoolean() ? "|p" : "") + "@example.edu"; + String hash = "$2a$10$" + random.nextLong(); + int expiry = 1 + random.nextInt(100); + VerifyOutcome outcome = VerifyOutcome.values()[random.nextInt(VerifyOutcome.values().length)]; + cases.add(Arguments.of(email, hash, expiry, outcome)); + } + + return cases.stream(); + } + + @ParameterizedTest + @MethodSource("noSideEffectCases") + public void verifyWritesNoAccountAndReadsNoPersistedTokenState(String email, String storedHash, + int expiryHours, VerifyOutcome outcome) { + Instant issuedAt = Instant.ofEpochSecond(1_700_000_000L); + inject(Clock.fixed(issuedAt, ZoneOffset.UTC)); + + User user = userWith(email, storedHash); + // Lenient: the INVALID arm feeds a structurally broken token that short-circuits before the + // email lookup, so this stub is unused for those cases. + lenient().when(userRepo.findByEmail(email)).thenReturn(user); + lenient().when(availabilityService.getResetExpiryHours()).thenReturn(expiryHours); + + // Construct against the live Account, then engineer the chosen verification outcome. + String token = resetTokenService.construct(user); + + String tokenToVerify; + switch (outcome) { + case VALID: + // Verify well inside the window; the clock stays at issuedAt. + tokenToVerify = token; + break; + case EXPIRED: + // Advance the clock to or beyond the expiry boundary; the token itself is untouched. + ReflectionTestUtils.setField(resetTokenService, "clock", + Clock.fixed(issuedAt.plusSeconds((long) expiryHours * 3600L), ZoneOffset.UTC)); + tokenToVerify = token; + break; + case INVALID: + default: + // A structurally broken token forces the INVALID path without touching the Account. + tokenToVerify = "not-a-valid-token"; + break; + } + + // Record the stored hash by identity and value, so any in-place mutation would be caught. + String hashBefore = user.getPassword(); + + ResetTokenVerification result = resetTokenService.verify(tokenToVerify); + + // The engineered outcome actually occurred, so each arm of the partition is genuinely exercised. + ResetTokenVerification.Status expected; + switch (outcome) { + case VALID: + expected = ResetTokenVerification.Status.VALID; + break; + case EXPIRED: + expected = ResetTokenVerification.Status.EXPIRED; + break; + case INVALID: + default: + expected = ResetTokenVerification.Status.INVALID; + break; + } + assertEquals(expected, result.getStatus(), "engineered outcome for " + outcome + " / " + email); + + // The Account is never written: verify reads persisted state at most, never mutates it. + verify(userRepo, never()).update(any(User.class)); + verify(userRepo, never()).save(any(User.class)); + + // The stored password hash is byte-identical before and after a verify call. + assertEquals(hashBefore, user.getPassword(), + "the stored password hash must be unchanged across a verify call for " + email); + assertTrue(storedHash.equals(user.getPassword()), + "the stored password hash must be byte-identical to the original for " + email); + } + +} diff --git a/src/test/java/org/tdl/vireo/service/SystemDataLoaderTest.java b/src/test/java/org/tdl/vireo/service/SystemDataLoaderTest.java index 93a0dd7d8f..d54f7c73cb 100644 --- a/src/test/java/org/tdl/vireo/service/SystemDataLoaderTest.java +++ b/src/test/java/org/tdl/vireo/service/SystemDataLoaderTest.java @@ -190,7 +190,8 @@ private void assertInputType(boolean isReload) { } private void assertEmailTemplate(boolean isReload) { - assertEquals(19, emailTemplateRepo.count(), + // 19 pre-existing templates plus SYSTEM Password Reset Request and SYSTEM Password Changed. + assertEquals(21, emailTemplateRepo.count(), isReload ? "Incorrect number of emailTemplate found after reload" : "Incorrect number of emailTemplate found"); diff --git a/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java b/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java new file mode 100644 index 0000000000..a4546094cd --- /dev/null +++ b/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java @@ -0,0 +1,171 @@ +package org.tdl.vireo.utility; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.test.context.ActiveProfiles; +import org.tdl.vireo.model.User; + +/** + * Tests the eligibility predicate over the cross product of stored password, netid and affiliations. + * The rule is static and stateless, so no Spring context is started. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +public class PasswordEligibilityRuleTest { + + // U+00A0 is included because String.trim only strips characters at or below U+0020, so it counts as non-blank. + private static final List PASSWORDS = Arrays.asList( + // Absent and blank. + null, + "", + " ", + " ", + "\t\n", + "\r\n ", + + // Non-blank. + "$2a$10$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123", + "x", + "abc", + " padded ", + "\t spaced \n", + "\u00a0" + ); + + // Blank netids matter: any non-null netid is ineligible, and updateUserByCredentials can store an empty one. + private static final List NETIDS = Arrays.asList( + // The only eligible netid. + null, + + // Non-null, so ineligible. + "", + " ", + "\t", + "jdoe1", + "JDOE1", + "a-very-long-institutional-net-identifier-0123456789-0123456789" + ); + + // Varied while the expected result stays fixed; the User constructor installs a TreeSet, so no null elements. + private static final List> AFFILIATIONS = Arrays.asList( + null, + affiliations(), + affiliations("student"), + affiliations("staff", "student"), + affiliations("alum", "faculty", "member", "staff", "student") + ); + + private static Set affiliations(String... values) { + Set set = new TreeSet(); + + set.addAll(Arrays.asList(values)); + + return set; + } + + // The full cross product, since eligibility is an "exactly when" over the combination. + private static Stream providePasswordNetidAndAffiliationCombinations() { + List cases = new ArrayList(); + + for (String password : PASSWORDS) { + for (String netid : NETIDS) { + for (Set affiliation : AFFILIATIONS) { + cases.add(Arguments.of(password, netid, affiliation)); + } + } + } + + return cases.stream(); + } + + // Affiliations are deliberately not a parameter. + private static boolean expectedEligible(String password, String netid) { + return netid == null && password != null && password.trim().length() > 0; + } + + private static User accountOf(String password, String netid, Set affiliation) { + User user = new User(); + + user.setPassword(password); + user.setNetid(netid); + user.setShibbolethAffiliations(affiliation); + + return user; + } + + // Eligible exactly when the password is non-blank and the netid is null; both overloads are checked against the independent predicate. + @ParameterizedTest(name = "[{index}] password=''{0}'' netid=''{1}'' affiliations={2}") + @MethodSource("providePasswordNetidAndAffiliationCombinations") + public void testEligibilityPredicate(String password, String netid, Set affiliation) { + boolean expected = expectedEligible(password, netid); + + String description = "Eligibility for password '" + password + "', netid '" + netid + "', affiliations " + affiliation; + + assertEquals( + Boolean.valueOf(expected), + Boolean.valueOf(PasswordEligibilityRule.isEligible(accountOf(password, netid, affiliation))), + description + " through the Account form"); + + assertEquals( + Boolean.valueOf(expected), + Boolean.valueOf(PasswordEligibilityRule.isEligible(password, netid)), + description + " through the field-level form"); + + // A repeat evaluation on an equivalent Account classifies the same way. + assertEquals( + Boolean.valueOf(expected), + Boolean.valueOf(PasswordEligibilityRule.isEligible(accountOf(password, netid, affiliation))), + description + " on a repeat evaluation of an equivalent Account"); + } + + // The affiliation parameter is unused; it only keeps the generator shared with the predicate test. + @ParameterizedTest(name = "[{index}] password=''{0}'' netid=''{1}''") + @MethodSource("providePasswordNetidAndAffiliationCombinations") + public void testAffiliationsAreNotConsulted(String password, String netid, Set affiliation) { + // The field-level overload cannot see affiliations, so it is the baseline. + boolean withoutAffiliations = PasswordEligibilityRule.isEligible(password, netid); + + Set observed = new LinkedHashSet(); + + for (Set candidate : AFFILIATIONS) { + boolean actual = PasswordEligibilityRule.isEligible(accountOf(password, netid, candidate)); + + observed.add(Boolean.valueOf(actual)); + + assertEquals( + Boolean.valueOf(withoutAffiliations), + Boolean.valueOf(actual), + "Affiliations " + candidate + " altered the classification for password '" + password + "' and netid '" + netid + "'"); + } + + assertEquals( + 1, + observed.size(), + "Distinct classifications observed across the affiliation shapes for password '" + password + "' and netid '" + netid + "'"); + + // Guards against a rule that is invariant only because it returns a constant. + assertEquals( + Boolean.valueOf(expectedEligible(password, netid)), + Boolean.valueOf(withoutAffiliations), + "Classification for password '" + password + "' and netid '" + netid + "'"); + } + + // A null Account fails closed. + @Test + public void testNullAccountIsIneligible() { + assertFalse(PasswordEligibilityRule.isEligible((User) null), "A null Account classified as eligible"); + } + +} diff --git a/src/test/java/org/tdl/vireo/utility/PasswordValidatorTest.java b/src/test/java/org/tdl/vireo/utility/PasswordValidatorTest.java new file mode 100644 index 0000000000..4185bfdf4c --- /dev/null +++ b/src/test/java/org/tdl/vireo/utility/PasswordValidatorTest.java @@ -0,0 +1,473 @@ +package org.tdl.vireo.utility; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.test.context.ActiveProfiles; +import org.tdl.vireo.utility.PasswordValidator.Result; + +/** + * Tests {@link PasswordValidator} with enumerated boundary values, whitespace padding and a + * fixed-seed {@link Random}. The validator is static, so no Spring context is started. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +public class PasswordValidatorTest { + + private static final long GENERATOR_SEED = 20250101L; + + private static final int RANDOM_CASE_COUNT = 64; + + // Every run trims to nothing, so a run on its own is a missing-password case. + private static final List WHITESPACE_RUNS = Arrays.asList( + "", + " ", + " ", + " ", + "\t", + "\n", + "\r", + " \t\n\r ", + " " + ); + + // Trimmed lengths 5 and 6 are covered across character classes, since only trimmed length may matter. + private static final List CANDIDATE_CORES = Arrays.asList( + // Absent and empty. + null, + "", + + // Below the boundary. + "a", + "ab", + "abc", + "abcd", + + // Trimmed length 5: rejected. + "abcde", + "ABCDE", + "12345", + "!@#$%", + "aB3$x", + "\u00e9\u00e8\u00ea\u00eb\u00ec", + + // Trimmed length 6: accepted. + "abcdef", + "ABCDEF", + "123456", + "!@#$%^", + "aB3$x.", + "\u00e9\u00e8\u00ea\u00eb\u00ec\u00ed", + + // Above the boundary. + "abcdefg", + "1234567890", + "correct horse battery staple", + "\u4e2d\u6587\u5bc6\u7801\u5f88\u5f3a\u5927", + + // Interior whitespace is not trimmed, so these count at full length. + "a b c", + "a b cd", + "a\tb\tc\td" + ); + + // Crosses each core with every padding shape so a trimmed-length rule differs from an untrimmed one. + private static Stream provideCandidates() { + Set candidates = new LinkedHashSet(); + + boolean sawNull = false; + + for (String core : CANDIDATE_CORES) { + if (core == null) { + sawNull = true; + + continue; + } + + candidates.add(core); + + for (String run : WHITESPACE_RUNS) { + candidates.add(run + core); + candidates.add(core + run); + candidates.add(run + core + run); + } + } + + candidates.addAll(WHITESPACE_RUNS); + + Random random = new Random(GENERATOR_SEED); + + for (int i = 0; i < RANDOM_CASE_COUNT; i++) { + candidates.add(randomCandidate(random)); + } + + List cases = new ArrayList(); + + if (sawNull) { + cases.add(Arguments.of((String) null)); + } + + for (String candidate : candidates) { + cases.add(Arguments.of(candidate)); + } + + return cases.stream(); + } + + // Length 0 to 10 so both boundary lengths are reachable, in a random character class with random padding. + private static String randomCandidate(Random random) { + int length = random.nextInt(11); + + StringBuilder core = new StringBuilder(); + + for (int i = 0; i < length; i++) { + switch (random.nextInt(5)) { + case 0: + core.append((char) ('a' + random.nextInt(26))); + break; + case 1: + core.append((char) ('A' + random.nextInt(26))); + break; + case 2: + core.append((char) ('0' + random.nextInt(10))); + break; + case 3: + core.append((char) ('!' + random.nextInt(15))); + break; + default: + core.append((char) (0x00c0 + random.nextInt(60))); + break; + } + } + + String leading = WHITESPACE_RUNS.get(random.nextInt(WHITESPACE_RUNS.size())); + String trailing = WHITESPACE_RUNS.get(random.nextInt(WHITESPACE_RUNS.size())); + + return leading + core.toString() + trailing; + } + + // Independent oracle: trim, then decide on trimmed length alone. + private static Result expectedResult(String candidate) { + if (candidate == null) { + return Result.MISSING; + } + + int trimmedLength = candidate.trim().length(); + + if (trimmedLength == 0) { + return Result.MISSING; + } + + if (trimmedLength < 6) { + return Result.TOO_SHORT; + } + + return Result.ACCEPTED; + } + + // The decision depends on trimmed length alone, and is the same via both overloads and on a repeat call. + @ParameterizedTest(name = "[{index}] candidate=''{0}''") + @MethodSource("provideCandidates") + public void testSharedValidatorDecision(String candidate) { + Result expected = expectedResult(candidate); + + String description = "Decision for candidate '" + candidate + "'"; + + assertEquals(expected, PasswordValidator.validate(candidate), description); + + // Ties the oracle's literal 6 to the declared constant. + assertEquals(6, PasswordValidator.MINIMUM_TRIMMED_LENGTH, "The declared minimum trimmed length"); + + // A matching confirmation adds no rejection cause, so both overloads must agree. + assertEquals(expected, PasswordValidator.validate(candidate, candidate), description + " through the confirming overload"); + + // No reuse-history state, so a repeat call decides the same way. + assertEquals(expected, PasswordValidator.validate(candidate), description + " on a repeat decision"); + } + + // Includes pairs differing only in case, in surrounding whitespace, or in the kind of trailing whitespace. + private static final List CONFIRMATION_VALUES = Arrays.asList( + // Absent and whitespace-only. + null, + "", + " ", + " ", + "\t", + + // Below and at the boundary. + "abcde", + "abcde ", + "abcdef", + + // Case-only differences from "abcdef". + "ABCDEF", + "Abcdef", + "abcdeF", + + // Whitespace-only differences from "abcdef". + " abcdef", + "abcdef ", + " abcdef ", + "abcdef\t", + "\nabcdef", + + // Unrelated accepted values, and a non-ASCII one. + "123456", + "!@#$%^", + "correct horse battery staple", + "\u00e9bcdef" + ); + + // Full cross product of the values, plus seeded random pairs including single-character near-misses. + private static Stream provideConfirmationPairs() { + List cases = new ArrayList(); + + for (String candidate : CONFIRMATION_VALUES) { + for (String confirmation : CONFIRMATION_VALUES) { + cases.add(Arguments.of(candidate, confirmation)); + } + } + + Random random = new Random(GENERATOR_SEED); + + for (int i = 0; i < RANDOM_CASE_COUNT; i++) { + String candidate = randomCandidate(random); + + String confirmation; + + switch (random.nextInt(4)) { + case 0: + // Same raw value, so the accepting side is drawn too. + confirmation = candidate; + break; + case 1: + confirmation = perturb(candidate, random); + break; + case 2: + confirmation = randomCandidate(random); + break; + default: + confirmation = null; + break; + } + + cases.add(Arguments.of(candidate, confirmation)); + } + + return cases.stream(); + } + + // Changes one character, or appends one to an empty value, so the result never equals the input. + private static String perturb(String value, Random random) { + if (value.length() == 0) { + return "x"; + } + + char[] characters = value.toCharArray(); + + int position = random.nextInt(characters.length); + + characters[position] = characters[position] == 'x' ? 'y' : 'x'; + + return new String(characters); + } + + // Independent oracle with the evaluation order: missing, then mismatch, then too short. + private static Result expectedResult(String candidate, String confirmation) { + if (candidate == null || candidate.trim().length() == 0) { + return Result.MISSING; + } + + if (!candidate.equals(confirmation)) { + return Result.MISMATCH; + } + + if (candidate.trim().length() < 6) { + return Result.TOO_SHORT; + } + + return Result.ACCEPTED; + } + + // Mismatch is reported exactly when a present candidate differs from the confirmation on the raw strings, not the trimmed ones. + @ParameterizedTest(name = "[{index}] candidate=''{0}'' confirmation=''{1}''") + @MethodSource("provideConfirmationPairs") + public void testConfirmationMismatch(String candidate, String confirmation) { + Result expected = expectedResult(candidate, confirmation); + + String description = "Decision for candidate '" + candidate + "' and confirmation '" + confirmation + "'"; + + Result actual = PasswordValidator.validate(candidate, confirmation); + + assertEquals(expected, actual, description); + + boolean candidatePresent = candidate != null && candidate.trim().length() > 0; + + assertEquals( + Boolean.valueOf(candidatePresent && !candidate.equals(confirmation)), + Boolean.valueOf(Result.MISMATCH.equals(actual)), + description + " reported as a mismatch"); + + if (Result.MISMATCH.equals(actual)) { + assertEquals("The passwords do not match!", PasswordValidator.messageFor(actual), description + " message"); + } + } + + // Each core has a non-blank trimmed value, with trimmed lengths on both sides of the boundary. + private static final List STORAGE_CORES = Arrays.asList( + // Below the boundary. + "a", + "abc", + "abcde", + "12345", + "!@#$%", + + // At and above the boundary. + "abcdef", + "ABCDEF", + "123456", + "!@#$%^", + "aB3$x.", + "abcdefg", + "correct horse battery staple", + "\u00e9\u00e8\u00ea\u00eb\u00ec\u00ed", + "\u4e2d\u6587\u5bc6\u7801\u5f88\u5f3a" + ); + + // No empty run: each core is also emitted unpadded, so every padded case differs from its trimmed form. + private static final List STORAGE_PADDING = Arrays.asList( + " ", + " ", + "\t", + "\n", + "\r\n", + " \t\n\r ", + " " + ); + + // Each core padded leading, trailing and both sides, plus seeded random padded draws. + private static Stream provideStorageCandidates() { + Set candidates = new LinkedHashSet(); + + for (String core : STORAGE_CORES) { + candidates.add(core); + + for (String padding : STORAGE_PADDING) { + candidates.add(padding + core); + candidates.add(core + padding); + candidates.add(padding + core + padding); + } + } + + Random random = new Random(GENERATOR_SEED); + + for (int i = 0; i < RANDOM_CASE_COUNT; i++) { + String core = STORAGE_CORES.get(random.nextInt(STORAGE_CORES.size())); + + String leading = STORAGE_PADDING.get(random.nextInt(STORAGE_PADDING.size())); + String trailing = STORAGE_PADDING.get(random.nextInt(STORAGE_PADDING.size())); + + candidates.add(leading + core + trailing); + } + + List cases = new ArrayList(); + + for (String candidate : candidates) { + cases.add(Arguments.of(candidate)); + } + + return cases.stream(); + } + + // Records the exact string handed to it; a real BCrypt encoder would only slow each case down. + private static final class RecordingEncoder { + + private String encoded; + + private int invocations; + + private String encode(String raw) { + this.encoded = raw; + this.invocations++; + + return "{encoded}" + raw; + } + + } + + // Validate the pair; on ACCEPTED encode the untrimmed candidate, and store nothing on rejection. + private static Result validateThenStore(String candidate, String confirmation, RecordingEncoder encoder) { + Result result = PasswordValidator.validate(candidate, confirmation); + + if (Result.ACCEPTED.equals(result)) { + encoder.encode(candidate); + } + + return result; + } + + // Acceptance uses the trimmed length, but the encoder receives the untrimmed candidate itself. + @ParameterizedTest(name = "[{index}] candidate=''{0}''") + @MethodSource("provideStorageCandidates") + public void testUntrimmedStorage(String candidate) { + String trimmed = candidate.trim(); + + String description = "Candidate '" + candidate + "'"; + + RecordingEncoder encoder = new RecordingEncoder(); + + Result result = validateThenStore(candidate, candidate, encoder); + + assertEquals( + Boolean.valueOf(trimmed.length() >= PasswordValidator.MINIMUM_TRIMMED_LENGTH), + Boolean.valueOf(Result.ACCEPTED.equals(result)), + description + " accepted on its trimmed length"); + + assertEquals( + PasswordValidator.validate(trimmed, trimmed), + result, + description + " decided as its trimmed form is decided"); + + if (!Result.ACCEPTED.equals(result)) { + assertEquals(0, encoder.invocations, description + " handed to the encoder despite rejection"); + assertNull(encoder.encoded, description + " recorded despite rejection"); + + return; + } + + assertEquals(1, encoder.invocations, description + " encoder invocation count"); + assertSame(candidate, encoder.encoded, description + " handed to the encoder as the submitted instance"); + assertEquals(candidate, encoder.encoded, description + " handed to the encoder untrimmed"); + assertEquals(candidate.length(), encoder.encoded.length(), description + " length preserved into storage"); + + if (!candidate.equals(trimmed)) { + assertTrue(!trimmed.equals(encoder.encoded), description + " stored trimmed rather than untrimmed"); + } + + // The validator must offer no normalised form to store; messageFor is its only String-returning member. + for (Method method : PasswordValidator.class.getDeclaredMethods()) { + if (!Modifier.isPublic(method.getModifiers()) || method.isSynthetic()) { + continue; + } + + if (String.class.equals(method.getReturnType())) { + assertEquals("messageFor", method.getName(), "The only String-returning member of the validator"); + } + } + } + +}