From 4edf6953d37d015622022a64453add3629c73bd0 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Thu, 15 Oct 2026 19:56:07 -0400 Subject: [PATCH 01/20] Add password management foundation and change notification - Add auth.pass.change.enabled, auth.pass.reset.enabled and auth.pass.reset.expiryHours to ConfigurationName, reusing the existing auth.pass.enabled constant as-is. -Seed all four settings under the application key in SYSTEM_Defaults.json. - Add PasswordEligibilityRule, a static predicate over stored password and netid only. - Add PasswordValidator - Add CredentialNotificationService.notifyPasswordChanged - Add the packaged SYSTEM_Password_Changed.email template --- .../vireo/auth/controller/AuthController.java | 18 +- .../config/constant/ConfigurationName.java | 3 + .../tdl/vireo/controller/UserController.java | 17 +- src/main/java/org/tdl/vireo/model/User.java | 17 + .../CredentialNotificationService.java | 141 ++++ .../PasswordFeatureAvailabilityService.java | 161 ++++ .../utility/PasswordEligibilityRule.java | 53 ++ .../tdl/vireo/utility/PasswordValidator.java | 101 +++ .../emails/SYSTEM_Password_Changed.email | 14 + .../resources/settings/SYSTEM_Defaults.json | 12 + .../vireo/ApplicationInitializationTest.java | 2 +- .../vireo/controller/AuthControllerTest.java | 262 +++++++ .../vireo/controller/UserControllerTest.java | 126 +++- .../CredentialNotificationServiceTest.java | 697 ++++++++++++++++++ ...asswordFeatureAvailabilityServiceTest.java | 552 ++++++++++++++ .../utility/PasswordEligibilityRuleTest.java | 292 ++++++++ .../vireo/utility/PasswordValidatorTest.java | 665 +++++++++++++++++ 17 files changed, 3118 insertions(+), 15 deletions(-) create mode 100644 src/main/java/org/tdl/vireo/service/CredentialNotificationService.java create mode 100644 src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java create mode 100644 src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java create mode 100644 src/main/java/org/tdl/vireo/utility/PasswordValidator.java create mode 100644 src/main/resources/emails/SYSTEM_Password_Changed.email create mode 100644 src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java create mode 100644 src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java create mode 100644 src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java create mode 100644 src/test/java/org/tdl/vireo/utility/PasswordValidatorTest.java 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 allCredentials, so the value is the + // String "true" or "false" and never a JSON boolean. + 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..a854d4bc88 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,19 @@ public String getUsername() { return getEmail(); } + /** + * Whether this Account is eligible for Vireo-managed password operations, derived from the + * stored password and netid values at evaluation time. + * + * Carries no {@code @JsonView} annotation deliberately: with default view inclusion disabled, + * an un-annotated property serializes only when no view is active, which confines the flag to + * the no-view listing endpoints. + * + * @return true when this Account is eligible + */ + @Transient + public boolean isPasswordEligible() { + return PasswordEligibilityRule.isEligible(password, netid); + } + } 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..035e33ed78 --- /dev/null +++ b/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java @@ -0,0 +1,141 @@ +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; + +/** + * Dispatch the credential-change notifications. + * + * Every notification this service sends is advisory: the credential change it reports has already + * been persisted by the time the notification is attempted. An absent Email_Template or a mail + * transport failure is therefore recorded in the application log and swallowed, so the completed + * change stands. + * + * Reset-initiation mail is deliberately not sent from this service. That path reports an ERROR + * {@code ApiResponse} to the initiating Administrator on a mail failure, which is the opposite + * failure semantics, so it stays in the controller. Only the nullable template lookup is shared. + * + * Notifications are dispatched from the request thread that persisted the change. No dispatch state + * is retained and no retry is performed. + */ +@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"; + + public static final String EMAIL_CHANGED_TEMPLATE = "SYSTEM Email Address 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(); + + /** + * Notify the holder of an Account that the stored password on that Account has changed. + * + * Never throws. An absent Email_Template or a {@link MessagingException} is recorded in the + * application log, naming the Account and the notification, and swallowed, so the completed + * password change stands. Neither the password value nor any token appears in the log or in the + * message body. + * + * @param user The Account whose password changed. + */ + 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()); + } + } + + /** + * Resolve an Email_Template by name, preferring a custom row over the system row. + * + * The result of {@code findByNameOverride} is tested for null before any {@code getSubject()} + * or {@code getMessage()} call, so a deployment where the row was never installed produces a + * logged skip rather than a {@link NullPointerException}. + * + * Shared with the reset-initiation path, which reports ERROR on a null result while the + * notifications log and continue. + * + * @param name The Email_Template name. + * + * @return The resolved template, or null when neither a custom nor a system row 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; + } + + /** + * Format the time of the change for the {@code CHANGE_TIME} template parameter. + * + * The value is rendered at {@link ZoneOffset#UTC} and labelled as such, so the timestamp is + * unambiguous for a recipient in any timezone. + * + * @return The formatted time of the change. + */ + 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..378da24040 --- /dev/null +++ b/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java @@ -0,0 +1,161 @@ +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; + +/** + * Resolve the password feature configuration settings and report feature availability. + * + * Every accessor resolves its setting through + * {@code configurationRepo.getValueByNameAndType(name, "application")} on each invocation. No + * resolved setting value is held in a field, so an Administrator save applies to every later + * request with no application 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; + + /** + * Resolve the Password_Login_Setting, {@code auth.pass.enabled}. + * + * @return The resolved value, false when absent or unrecognised. + */ + public boolean isPasswordLoginEnabled() { + return resolveBoolean(getRawValue(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED), ConfigurationName.APPLICATION_AUTH_PASS_ENABLED); + } + + /** + * Resolve {@code auth.pass.change.enabled}. + * + * @return The resolved value, false when absent or unrecognised. + */ + public boolean isChangeEnabled() { + return resolveBoolean(getRawValue(ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED), ConfigurationName.APPLICATION_AUTH_PASS_CHANGE_ENABLED); + } + + /** + * Resolve {@code auth.pass.reset.enabled}. + * + * @return The resolved value, false when absent or unrecognised. + */ + public boolean isResetEnabled() { + return resolveBoolean(getRawValue(ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED), ConfigurationName.APPLICATION_AUTH_PASS_RESET_ENABLED); + } + + /** + * Report whether self-service password change is available. + * + * Reads the Password_Login_Setting itself, so wiring login to honor that setting later requires + * no change here. + * + * @return True only when the Password_Login_Setting and {@code auth.pass.change.enabled} both + * resolve to true. + */ + public boolean isChangeAvailable() { + return isPasswordLoginEnabled() && isChangeEnabled(); + } + + /** + * Report whether administrator-initiated reset is available. + * + * Reads the Password_Login_Setting itself, so wiring login to honor that setting later requires + * no change here. + * + * @return True only when the Password_Login_Setting and {@code auth.pass.reset.enabled} both + * resolve to true. + */ + public boolean isResetAvailable() { + return isPasswordLoginEnabled() && isResetEnabled(); + } + + // TODO: isChangeAvailableFor(User) and isResetAvailableFor(User) are added alongside + // PasswordEligibilityRule. + + /** + * Resolve {@code auth.pass.reset.expiryHours}. + * + * A value that does not parse as an integer, or that falls outside 1 to + * {@link Integer#MAX_VALUE} inclusive, yields {@link #DEFAULT_RESET_EXPIRY_HOURS}, leaves the + * stored value unchanged, and is recorded in the application log. + * + * @return The resolved expiry in hours. + */ + 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; + } + + /** + * Resolve a raw configuration value as a boolean, comparing with surrounding whitespace and + * letter case ignored. + * + * An absent value resolves false. A value matching neither true nor false resolves false and is + * recorded in the application log. + * + * Visible for test. + * + * @param raw The raw stored value. + * @param settingName The setting name, for the log message. + * + * @return The resolved value. + */ + 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/utility/PasswordEligibilityRule.java b/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java new file mode 100644 index 0000000000..6454b4134b --- /dev/null +++ b/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java @@ -0,0 +1,53 @@ +package org.tdl.vireo.utility; + +import org.tdl.vireo.model.User; + +/** + * The server-side predicate that classifies an Account as eligible for Vireo-managed password + * operations, or as ineligible. + * + * Static and stateless by design: an injected bean would arrive null under the {@code @InjectMocks} + * wiring every existing controller test uses. + * + * Reads {@code User.password} and {@code User.netid} only, and consults + * {@code User.shibbolethAffiliations} in no part of the classification (Requirement 2 criterion 8). + */ +public final class PasswordEligibilityRule { + + private PasswordEligibilityRule() { + } + + /** + * Requirement 2 criteria 1, 2: eligible if and only if the password holds a non-whitespace + * character and the netid is null. A null {@link User} is ineligible. + * + * @param user the Account to classify, which may be null + * @return true when the Account is an Eligible_Account + */ + public static boolean isEligible(User user) { + if (user == null) { + return false; + } + + return isEligible(user.getPassword(), user.getNetid()); + } + + /** + * Field-level form, so the rule can be evaluated without a {@link User} instance. + * + * Requirement 2 criteria 1, 2, 3: the classification is derived from the supplied stored field + * values at evaluation time, with no administrator tagging and no migration. + * + * @param password the stored password value, which may be null + * @param netid the stored netid value, which may be null + * @return true when the values describe an Eligible_Account + */ + 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..508b9e21d5 --- /dev/null +++ b/src/main/java/org/tdl/vireo/utility/PasswordValidator.java @@ -0,0 +1,101 @@ +package org.tdl.vireo.utility; + +/** + * The single server-side decision on whether a candidate password is acceptable. + * + * Static and stateless by design: an injected bean would arrive null under the {@code @InjectMocks} + * wiring every existing controller test uses. + * + * The acceptance rule is exactly the existing one in {@code AuthController.registration}: non-blank, + * trimmed length {@value #MINIMUM_TRIMMED_LENGTH} or greater. No character-class, reuse-history, or + * expiry constraint is added (Requirement 3 criterion 8). + */ +public final class PasswordValidator { + + /** + * The outcome of a validation. {@code ACCEPTED} is the only accepting value; the other three name + * the rejection cause. + */ + public enum Result { + ACCEPTED, MISSING, TOO_SHORT, MISMATCH + } + + /** + * Requirement 3 criterion 2: the minimum acceptable trimmed length. + */ + public static final int MINIMUM_TRIMMED_LENGTH = 6; + + private PasswordValidator() { + } + + /** + * Requirement 3 criteria 1, 2, 3: a candidate with no confirmation to compare against. Absent or + * blank is {@code MISSING}; a trimmed length below {@link #MINIMUM_TRIMMED_LENGTH} is + * {@code TOO_SHORT}; anything else is {@code ACCEPTED}. + * + * @param candidate the proposed password, which may be null + * @return the decision + */ + 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; + } + + /** + * Requirement 3 criteria 1 through 4. Evaluation order is {@code MISSING}, then {@code MISMATCH}, + * then {@code TOO_SHORT}, matching the existing order in {@code AuthController.registration} so + * the retrofit is outcome-preserving (Requirement 3 criterion 9). + * + * The confirmation comparison is on the untrimmed values, again matching the existing behavior. + * + * @param candidate the proposed password, which may be null + * @param confirmation the repeated password, which may be null + * @return the decision + */ + 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; + } + + /** + * Requirement 3 criteria 7, 9: the existing {@code AuthController} message text, verbatim, for + * each rejection, so the retrofit preserves the response body as well as the {@code ApiStatus}. + * + * The {@code TOO_SHORT} text misdescribes a {@code >= 6} rule. It is preserved anyway: outcome + * preservation is required and the Minimal Change Constraint forbids opportunistic correction. + * + * @param result the decision to describe + * @return the message for a rejection, or null for {@code ACCEPTED} + */ + 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..f3fe38c072 --- /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 etd-support@jhu.edu right +away so we can help you secure your account. + +The Hopkins ETD 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/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..ccc3430451 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,258 @@ private void setupDataMap() { data.put("userPassword", "userPassword"); data.put("confirm", data.get("userPassword")); } + + /* ------------------------------------------------------------------------------------------ + * Property 11: Registration retrofit preserves outcomes. + * + * Validates: Requirements 3.6, 3.7, 3.9 + * + * Everything below is additive. No method above this point is edited, reordered, or + * reformatted: the unchanged methods are the example-based regression evidence for the + * retrofit, and this property generalises the same claim over generated input. + * ------------------------------------------------------------------------------------------ */ + + 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."; + + /** + * The candidate and confirmation values crossed with themselves to form the enumerated cases. + * + * The list is chosen so the cross product contains every shape that can tell the three + * rejection causes apart, in the order {@code AuthController.registration} evaluated them + * before the retrofit: + * + * - Absent and whitespace-only values, which must be reported as a missing password even when + * the confirmation differs — that is what pins missing ahead of mismatch. + * - The trimmed length 5 and trimmed length 6 boundary, explicitly, on both sides, across + * letters and digits: {@code "abcde"} against {@code "abcdef"} and {@code "12345"} against + * {@code "123456"}. + * - {@code "12345"} and {@code "54321"}, the ordering case: the two differ and are both too + * short, so a rule that checked length before the confirmation would report the wrong cause + * while still rejecting. Status alone cannot catch that, which is why the message is asserted + * too. + * - {@code "abcde "}, whose raw length is 6 and trimmed length is 5, so the length check has to + * be applied to the trimmed value; and {@code " abcdef "}, which is accepted on its trimmed + * length and must reach the encoder untrimmed. + */ + 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" + ); + + /** + * Each case is one candidate password and confirmation pair handed to + * {@code AuthController.registration}. + * + * Every enumerated value is crossed with every enumerated value, which yields both the + * accepting and the rejecting side of the claim, then a fixed-seed {@link Random} adds further + * pairs drawn from the same pool — a quarter of them equal pairs, so the accepting path keeps + * being exercised, and a quarter of them single-character perturbations, which is the near-miss + * shape that separates a raw-string comparison from a looser one. + * + * The enumerated cross product alone is 225 cases, comfortably past the hundred-case floor, and + * no property-based testing library is used. + * + * @return The generated cases. + */ + 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(); + } + + /** + * Alter one character of the supplied value, so the result differs from the input in exactly + * one position. A null or empty input becomes a short non-empty value, which still differs. + * + * @param value The value to perturb. + * @param random The fixed-seed source. + * + * @return The perturbed value, which 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); + } + + /** + * The password rule {@code AuthController.registration} carried inline before the retrofit, + * transcribed from the pre-retrofit source: missing first, then mismatch, then too short, with + * the message text of each branch verbatim. + * + * This is deliberately a transcription rather than a call to {@link PasswordValidator}: the + * claim is that the retrofitted handler agrees with the rule it replaced, and an oracle that + * called the replacement would assert nothing. + * + * @param password The candidate password, which may be null. + * @param confirm The confirmation value, which may be null. + * + * @return The pre-retrofit rejection message, or null where the pre-retrofit rule accepted. + */ + 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; + } + + /** + * Property 11: Registration retrofit preserves outcomes. + * + * Validates: Requirements 3.6, 3.7, 3.9 + * + * For any pair of candidate password and confirmation values, {@code AuthController.registration} + * after the retrofit returns the same accept-or-reject outcome, with the same message, that the + * pre-retrofit inline rule produced. + * + * Three things are asserted on every case: + * + * 1. Requirement 3.6: the decision the handler acts on is the shared validator's. The + * validator's verdict and message are checked against the transcribed pre-retrofit rule, so + * the two rules cannot drift apart silently. + * 2. Requirement 3.9: the handler's observable outcome — the {@code ApiStatus} and the response + * message — matches what the pre-retrofit rule produced. Both halves matter: the three + * rejection causes share the {@code ERROR} status, so status alone would not notice a change + * in the evaluation order, and the message is what distinguishes them. + * 3. Requirement 3.7: an accepted candidate reaches the encoder untrimmed, and a rejected one + * reaches nothing at all — no token is validated, no password is encoded, and no Account is + * created. + * + * @param password The candidate password under test. + * @param confirm The confirmation value under test. + */ + @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); + + // Requirement 3.6: the shared validator reaches the same accept-or-reject verdict the + // pre-retrofit inline rule reached. + assertEquals( + Boolean.valueOf(expectedMessage == null), + Boolean.valueOf(PasswordValidator.Result.ACCEPTED.equals(result)), + "Shared validator verdict for " + description); + + // Requirement 3.6: and names the same cause, in the same words. messageFor returns null for + // ACCEPTED, which is the accepting case of the oracle. + assertEquals(expectedMessage, PasswordValidator.messageFor(result), "Shared validator message for " + description); + + // The firstName and lastName gate sits ahead of the password gate and is not under test, so + // it is satisfied on every case; the token is supplied so an accepted candidate can 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); + + // Requirement 3.9: the rejected outcome is preserved, status and message together. + assertEquals(ApiStatus.ERROR, response.getMeta().getStatus(), "Status for rejected " + description); + assertEquals(expectedMessage, response.getMeta().getMessage(), "Message for rejected " + description); + + // Requirement 3.7: the rejection happens at the password gate, ahead of the token + // validation, so nothing downstream of that gate runs. + 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); + + // Requirement 3.9: the accepted outcome is preserved, status and message together. + 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); + + // Requirement 3.7: the accepted candidate reaches the encoder as submitted, padding and + // all, even though the length check that accepted it was applied to the trimmed value. + verify(cryptoService).encodePassword(password); + } } diff --git a/src/test/java/org/tdl/vireo/controller/UserControllerTest.java b/src/test/java/org/tdl/vireo/controller/UserControllerTest.java index e6e60b937a..b0275037b2 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,122 @@ public void testCredentials() { assertEquals(credentials1, got); } + @Test + public void testCredentialsCarriesPasswordEligibleTrue() { + // Requirement 2 criterion 4: an Account with a non-whitespace password and a null netid is eligible. + 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 declared Map, so the value is the String "true", never a JSON boolean. + assertEquals("true", got.getAllCredentials().get("passwordEligible")); + } + + @Test + public void testCredentialsCarriesPasswordEligibleFalse() { + // Requirement 2 criterion 2: a non-null netid makes the Account ineligible. + 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() { + // The entry is never a JSON boolean and never absent, whichever way the rule classifies. + 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() { + // UserControllerTest constructs new Credentials() directly, whose no-argument constructor + // leaves allCredentials null, so the handler has to create and set 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 { + // Requirement 2 criterion 4: User.isPasswordEligible() carries no @JsonView, and with + // default-view-inclusion disabled an un-annotated property serializes only when no view + // is active. That is what confines the flag to the no-view listing endpoints. + 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"); + } + + /** + * A mapper configured the way src/main/resources/application.yml configures the application + * mapper: spring.jackson.mapper.default-view-inclusion is false. The inherited objectMapper + * is a shared @Spy wired into controllers, so it is left alone here. + */ + 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/service/CredentialNotificationServiceTest.java b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java new file mode 100644 index 0000000000..43c75ef935 --- /dev/null +++ b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java @@ -0,0 +1,697 @@ +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.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; + +/** + * Absent-template and mail-failure cases for the password-changed notification. + * + * Validates: Requirements 6.6, 6.7, 14.1, 14.2, 14.4, 14.5, 15.10, 16.11 + * + * Both failure injections assert the same three things the requirements name: no send is attempted + * where none can succeed, the failure is recorded in the application log naming the Account and the + * notification, and no exception escapes, so the already-persisted password change stands. + * + * The log assertion attaches a Logback {@link ListAppender} to the service's own logger, since the + * project carries no existing log-capture helper and no new Maven dependency may be introduced. + */ +@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; + + /** + * Declared for Property 23 only. The service under test holds no field of either type, so + * neither mock is wired into it, and that is precisely the point under assertion: a dispatch + * gated on a Password_Management_Setting or on the Password_Login_Setting would have to reach + * one of these collaborators, which {@code @InjectMocks} would then supply from here. + */ + @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, so the WARN records under assertion + // here are enabled for this logger only, for the duration of the test, and then restored. + originalLevel = serviceLogger.getLevel(); + + serviceLogger.setLevel(Level.WARN); + serviceLogger.addAppender(logAppender); + } + + @AfterEach + public void teardown() { + serviceLogger.detachAppender(logAppender); + serviceLogger.setLevel(originalLevel); + + logAppender.stop(); + } + + /** + * An absent Email_Template produces a logged skip naming the template, no send, and no + * exception. + * + * The null result is what {@code resolveTemplate} is tested against: the notification must not + * reach {@code getSubject()} or {@code getMessage()} on a null row. + */ + @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 rather than throwing when no row 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 transport failure is logged with the Account identifier and the notification, and no + * exception escapes, so the completed password change stands. + */ + @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); + } + + /** + * Join every captured log message, so a single assertion can read across the whole record the + * notification wrote. + * + * @return The 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 a password value nor a token value may appear anywhere in the log output. + * + * @param log The captured log messages. + */ + 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); + } + + /* + * Task 6.4 — Property 23: Credential-change notification is always on, password-changed arm. + * + * The email-change arm is added in task 16, once the detection site on /user/update exists. + */ + + private static final long GENERATOR_SEED = 20250101L; + + private static final int RANDOM_CASE_COUNT = 64; + + private static final String APPLICATION_TYPE = "application"; + + /** + * The raw stored setting strings the generator draws from. Both the resolving and the + * non-resolving shapes are present, since the property holds across the whole domain and not + * merely across the two values an Administrator can select in the Password Management pane. + */ + 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 under test. + * + * The shape carries the two fields the Password_Eligibility_Rule reads, the + * Institutional_SSO affiliations it deliberately ignores, and a user settings map, so a single + * case can describe an Account the rule classifies ineligible, an Account provisioned through + * Institutional_SSO, and an Account carrying user settings that look like a suppression switch. + */ + 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 enumerated Account shapes. Every shape the design's Property 23 input domain names is + * present: an eligible Vireo-managed Account, an Account provisioned through Institutional_SSO, + * an Account with no stored password, an Account whose stored password is whitespace only, an + * Account carrying user settings that read like a suppression switch, and an Account whose + * {@code preferedEmail} setting names a different address. + */ + 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")) + ); + + /** + * Each case is one Account shape crossed with one combination of the four password settings. + * + * The enumerated cross product is every Account shape against every pairing of resolving and + * non-resolving values for {@code auth.pass.enabled}, {@code auth.pass.change.enabled} and + * {@code auth.pass.reset.enabled}; the randomized cases then vary all four settings over the + * wider raw-value domain, including the shapes that resolve to neither true nor false. + * + * @return The generated cases, well over one hundred of them. + */ + 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(); + } + + /** + * Property 23: Credential-change notification is always on. + * + * Validates: Requirements 12.5, 13.5, 13.6 + * + * For any Account shape — including an Account provisioned through Institutional_SSO and an + * Account the Password_Eligibility_Rule classifies ineligible — and for any combination of the + * four password settings, and for any user settings carried on the Account, the password-changed + * notification is dispatched exactly once to the Account_Email. + * + * Requirement 13 criterion 6 is what the two unwired collaborators pin. The dispatch reads no + * configuration value and consults no availability conjunction, so a later change that gated the + * notification on either would draw this test's stubbed values and fail the send assertion. + * + * @param shape The Account shape under test. + * @param enabledRaw The raw stored {@code auth.pass.enabled} value. + * @param changeRaw The raw stored {@code auth.pass.change.enabled} value. + * @param resetRaw The raw stored {@code auth.pass.reset.enabled} value. + * @param expiryRaw The raw stored {@code auth.pass.reset.expiryHours} value. + */ + @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); + + // Requirements 12.5, 13.5: one dispatch, to the Account_Email, for every Account shape and + // every setting combination. The eligibility classification is recomputed here so the case + // list is demonstrably not confined to eligible Accounts. + 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); + + // Requirement 13.6: no configuration setting and no availability conjunction participates + // in the dispatch, so none of them can suppress it. + verifyNoInteractions(configurationRepo); + verifyNoInteractions(passwordFeatureAvailabilityService); + } + + /** + * Requirement 13.6: the service exposes no suppression switch of any kind. + * + * No declared field reaches the configuration store or the availability service, and no public + * method takes a flag a caller could set to skip the notification, so there is no request + * parameter the dispatch could be made to honour. + */ + @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"); + } + + /** + * The resolution rule the availability service applies, recomputed here so a stubbed + * availability answer matches what the real service would have returned for the raw value. + * + * @param raw The raw stored value. + * + * @return The resolved value. + */ + private static boolean resolves(String raw) { + return raw != null && raw.trim().equalsIgnoreCase("true"); + } + + /** + * Stub a raw stored setting value on the unwired configuration store. + * + * @param settingName The setting name. + * @param rawValue The raw stored value. + */ + private void stubSetting(String settingName, String rawValue) { + lenient().when(configurationRepo.getValueByNameAndType(eq(settingName), eq(APPLICATION_TYPE))).thenReturn(rawValue); + } + + /** + * Stub the availability conjunctions on the unwired availability service. + * + * @param enabled The resolved Password_Login_Setting. + * @param change The resolved {@code auth.pass.change.enabled} value. + * @param reset The resolved {@code auth.pass.reset.enabled} value. + */ + 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); + } + + /* + * Task 6.5 — packaged template content assertions for SYSTEM_Password_Changed.email. + * + * These are example assertions over the packaged classpath resource, read and split the same + * way SystemDataLoader.loadSystemEmailTemplate reads and splits it, so what is under assertion + * is the subject and the body an installed row would actually carry. + */ + + private static final String PASSWORD_CHANGED_RESOURCE = "/emails/SYSTEM_Password_Changed.email"; + + private static final String SUPPORT_ADDRESS = "etd-support@jhu.edu"; + + private static final String SIGN_OFF = "The Hopkins ETD Team"; + + private static final String CHANGE_TIME_PLACEHOLDER = "{CHANGE_TIME}"; + + private static final String RESET_URL_PLACEHOLDER = "{RESET_URL}"; + + /** + * Every shape a hyperlink could take in a plain-text template 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."); + + // Requirement 13.2: the body states that the password changed without carrying a value. + 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); + } + + /** + * Read the packaged template resource from the classpath. + * + * @return The raw resource content. + * + * @throws IOException If the packaged resource cannot be read. + */ + 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(); + } + + /** + * Strip the comment lines the way {@code SystemDataLoader} strips them. + * + * @param raw The raw resource content. + * + * @return The content the loader parses. + */ + private String strippedOfComments(String raw) { + return raw.replaceAll("\\s*#.*[\\n\\r]{1}", ""); + } + + /** + * Extract the subject the loader would extract. + * + * @param raw The raw resource content. + * + * @return The template subject. + */ + 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(); + } + + /** + * Extract the body the loader would extract: everything after the Subject line. + * + * @param raw The raw resource content. + * + * @return The template body. + */ + 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); + } + +} 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..756a1dd87d --- /dev/null +++ b/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java @@ -0,0 +1,552 @@ +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; + +/** + * Property 6: Setting resolution and availability conjunction. + * + * Validates: Requirements 1.13, 1.14, 1.16, 1.18, 1.19 + * + * The property is one {@link ParameterizedTest} fed by an {@link MethodSource} generator producing + * well over one hundred cases, built from the enumerated boundary values crossed with one another + * and padded from a fixed-seed {@link Random}. No property-based testing library is used and no new + * Maven dependency is introduced. + */ +@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; + + /** + * The enumerated raw setting strings. Every shape the design's Property 6 input domain names is + * present: null, {@code "true"}, {@code "TRUE"}, {@code " true "}, {@code "False"}, {@code "1"}, + * {@code "yes"}, empty and whitespace-only. + */ + 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; + + /** + * Each case is a triple of raw stored strings for the Password_Login_Setting, + * {@code auth.pass.change.enabled} and {@code auth.pass.reset.enabled}. + * + * The enumerated cross product pins every pairing of the boundary values for the + * Password_Login_Setting against a capability setting; the random cases vary all three + * independently, which is what covers the asymmetric pairings where one capability is enabled + * and the other is not. + * + * @return The generated cases. + */ + 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(); + } + + /** + * Draw either one of the enumerated boundary values or a junk string of random characters. + * + * @param random The fixed-seed source. + * + * @return The drawn raw value. + */ + 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(); + } + + /** + * The independently computed resolution rule: trim, then compare against {@code "true"} with + * letter case ignored. An absent value resolves false. + * + * @param raw The raw stored value. + * + * @return The expected resolved value. + */ + 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); + + // Requirements 1.13, 1.14: resolution is trim plus case-insensitive comparison, and an + // absent or unrecognised value resolves false. + 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"); + + // Requirement 1.18: change is available exactly under its conjunction. + assertEquals(expectedEnabled && expectedChange, passwordFeatureAvailabilityService.isChangeAvailable(), "Availability of self-service password change"); + + // Requirement 1.19: reset is available exactly under its conjunction. + assertEquals(expectedEnabled && expectedReset, passwordFeatureAvailabilityService.isResetAvailable(), "Availability of administrator-initiated reset"); + } + + /** + * Requirement 1.16: an absent Password_Login_Setting leaves both capabilities unavailable, for + * every value of the two capability settings. + */ + @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"); + } + + /** + * The enumerated raw expiry strings. Every boundary the design's Property 7 input domain names + * is present: absent, empty, whitespace-only, the rejected lower neighbours {@code "0"} and + * {@code "-1"}, the accepted lower bound {@code "1"}, the seeded default {@code "24"}, the + * accepted upper bound {@link Integer#MAX_VALUE}, the rejected upper neighbour + * {@code "2147483648"}, non-numeric shapes, and a whitespace-padded valid value. + */ + 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; + + /** + * Each case is one raw stored string for {@code auth.pass.reset.expiryHours}. + * + * The enumerated boundary values are crossed with randomized valid and invalid draws from a + * fixed-seed {@link Random}, giving well over one hundred cases in total. + * + * @return The generated cases. + */ + 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(); + } + + /** + * Draw either an enumerated boundary value, a randomized valid value in 1 to + * {@link Integer#MAX_VALUE}, a randomized rejected integer at or below zero, or a randomized + * non-numeric junk string. + * + * @param random The fixed-seed source. + * + * @return The drawn raw 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(); + } + } + + /** + * The independently computed resolution rule: trim, parse as an integer, and accept only a + * value in 1 to {@link Integer#MAX_VALUE} inclusive. Every other input yields 24. + * + * @param raw The raw stored value. + * + * @return The expected resolved expiry in hours. + */ + 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; + } + + /** + * Property 7: Expiry value resolution. + * + * Validates: Requirements 1.8 + * + * A value parsing as an integer in 1 to {@link Integer#MAX_VALUE} inclusive resolves to itself; + * every other value resolves to 24. On every input, rejected or accepted, the configuration + * store sees the single read and no write whatsoever, so the stored value is left unchanged. + * + * @param raw The raw stored value under test. + */ + @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 + "'"); + + // Requirement 1.8: the stored value is left unchanged. The resolution reads the setting + // once and performs no write-back of the fallback value. + 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); + } + + /** + * Stub a setting against a mutable holder, so the stored value can be flipped between requests + * without re-stubbing. + * + * @param settingName The setting name. + * @param holder The single-element holder carrying the current raw stored value. + */ + private void stubDynamic(String settingName, String[] holder) { + lenient().when(configurationRepo.getValueByNameAndType(eq(settingName), eq(APPLICATION_TYPE))).thenAnswer(invocation -> holder[0]); + } + + /* + * Task 1.6 — 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 the values Requirement 1 criteria 1, 2, 3 and 9 state. + * + * @return The generated cases. + */ + 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") + ); + } + + /** + * Read the Default_Settings_Seed exactly as {@code DefaultSettingsService} reads it. + * + * @return The parsed seed. + * + * @throws IOException If the resource cannot be read. + */ + 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 carries a pre-existing multi-line string value, so raw control characters + // inside a string are tolerated here exactly as the application's reader tolerates + // them. Nothing about the seed file is changed by this test. + ObjectMapper objectMapper = new ObjectMapper(); + + objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); + + return objectMapper.readTree(stream); + } + } + + /** + * Resolve a seeded value the way {@code DefaultSettingsService.init} flattens the seed: the + * entries under a top-level key are single-field objects, read through {@code asText()}. + * + * @param defaults The parsed seed. + * @param type The top-level key, which is the configuration type. + * @param name The setting name. + * + * @return The seeded value, or null when the setting is absent under that type. + */ + 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; + } + + /** + * Requirements 1.1, 1.2, 1.3, 1.9, 1.10, 1.15: each of the four settings is seeded under the + * {@code application} top-level key with the stated value, and under no other type. + * + * Seeding under the wrong type is invisible to {@code getSettingByNameAndType}, which filters + * {@code getSettingsByType(type)}, so the type is asserted and not merely the presence. + * + * @param settingName The setting name under test. + * @param expectedValue The value the requirement states. + * + * @throws IOException If the seed cannot be read. + */ + @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"); + } + + /** + * Requirement 1.4: each Password_Management_Setting is named in {@code ConfigurationName}, and + * the already-declared constant for the Password_Login_Setting is reused unchanged. + */ + @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"); + } + + /** + * Requirement 1.5: every setting is resolved through + * {@code configurationRepo.getValueByNameAndType(name, "application")} within the handling of + * each request, and no resolved value is retained across requests. + * + * A value cached at startup or held in a static field would answer the second and later + * requests with no read at all, so the read count scaling with the request count is what + * separates conformance from a cache. + */ + @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); + } + + /** + * Requirements 1.5, 1.6: a stored value that changes between two requests governs the second + * request, with no application restart. + * + * Each of the three booleans is flipped on its own, so a service that happened to carry one + * value over while re-reading the others cannot pass. + */ + @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"); + } + + /** + * Requirements 1.5, 1.6: the expiry value is likewise resolved per request, so an Administrator + * save of a new expiry governs the next evaluation. + */ + @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/utility/PasswordEligibilityRuleTest.java b/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java new file mode 100644 index 0000000000..840b576ea5 --- /dev/null +++ b/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java @@ -0,0 +1,292 @@ +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; + +/** + * Property 5: Eligibility predicate. + * + * Validates: Requirements 2.1, 2.2, 2.3, 2.8, 16.8 + * + * The property is one {@link ParameterizedTest} fed by an {@link MethodSource} generator producing + * well over one hundred cases, built from the cross product of the enumerated stored + * {@code User.password} values, the enumerated stored {@code User.netid} values, and the enumerated + * {@code User.shibbolethAffiliations} values. No property-based testing library is used and no new + * Maven dependency is introduced. + * + * {@link PasswordEligibilityRule} is static and stateless, so this test starts no Spring context + * and wires no mock. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +public class PasswordEligibilityRuleTest { + + /** + * The enumerated stored password values. + * + * The blank shapes are enumerated separately from the absent one because Requirement 2 + * criterion 2 routes null, empty, and whitespace-only alike to ineligible, and a rule written + * against {@code isEmpty} rather than a trim would separate them. The non-breaking space is + * included deliberately: {@code String.trim} removes characters at or below U+0020 only, so + * U+00A0 is a non-whitespace character under the rule as stated and a password composed of one + * is eligible. + */ + private static final List PASSWORDS = Arrays.asList( + // Absent and blank: ineligible under criterion 2. + null, + "", + " ", + " ", + "\t\n", + "\r\n ", + + // Non-blank: the eligible side of criterion 1, when the netid is null. + "$2a$10$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123", + "x", + "abc", + " padded ", + "\t spaced \n", + "\u00a0" + ); + + /** + * The enumerated stored netid values. + * + * The blank values are load-bearing: criterion 2 states that a non-null netid makes an Account + * ineligible including an empty or whitespace-only netid, which a rule written as a + * blank test rather than a null test would wrongly treat as eligible. The blank netid is + * reachable in practice, because the account-creation branch of + * {@code updateUserByCredentials} sets the netid with no emptiness guard. + */ + private static final List NETIDS = Arrays.asList( + // The only eligible netid under criterion 1. + null, + + // Non-null, so ineligible under criterion 2, blank or not. + "", + " ", + "\t", + "jdoe1", + "JDOE1", + "a-very-long-institutional-net-identifier-0123456789-0123456789" + ); + + /** + * The enumerated {@code User.shibbolethAffiliations} values, varied across the case list while + * the expected result never changes. That invariance is what pins Requirement 2 criterion 8: + * the rule must consult this field in no part of the classification. + * + * The field is a {@code Set}, and the set the {@link User} constructor installs is a + * {@link TreeSet}, which holds no null element, so every element here is non-null. + */ + private static final List> AFFILIATIONS = Arrays.asList( + null, + affiliations(), + affiliations("student"), + affiliations("staff", "student"), + affiliations("alum", "faculty", "member", "staff", "student") + ); + + /** + * Build an affiliation set in the shape the {@link User} constructor installs. + * + * @param values The affiliation values. + * + * @return The set. + */ + private static Set affiliations(String... values) { + Set set = new TreeSet(); + + set.addAll(Arrays.asList(values)); + + return set; + } + + /** + * Each case is one stored password value crossed with one stored netid value crossed with one + * affiliation value. + * + * The full cross product is generated rather than a sample, because the property is an "exactly + * when" over the combination: only the non-blank-password-and-null-netid cells are expected + * eligible, and every other cell is expected ineligible. + * + * @return The generated cases. + */ + 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(); + } + + /** + * The independently computed predicate, written straight from Requirement 2 criterion 1: the + * password holds at least one non-whitespace character and the netid is null. + * + * The affiliation value is deliberately not a parameter of this computation, which is the + * statement of Requirement 2 criterion 8 in code. + * + * @param password The stored password value, which may be null. + * @param netid The stored netid value, which may be null. + * + * @return The expected classification. + */ + private static boolean expectedEligible(String password, String netid) { + return netid == null && password != null && password.trim().length() > 0; + } + + /** + * Construct an Account carrying the supplied stored field values, leaving every other field as + * the constructor set it. + * + * @param password The stored password value. + * @param netid The stored netid value. + * @param affiliation The affiliation value, which may be null. + * + * @return The Account. + */ + 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; + } + + /** + * Property 5: Eligibility predicate. + * + * Validates: Requirements 2.1, 2.2, 2.3, 2.8, 16.8 + * + * The rule returns eligible exactly when the stored password holds at least one non-whitespace + * character and the stored netid is null, and ineligible for every other combination. + * + * The same case drives both overloads, so the field-level form and the Account form cannot + * drift apart, and both are compared against the independently computed predicate rather than + * against each other alone — two forms that agree with each other and disagree with the + * requirement would otherwise pass. + * + * @param password The stored password value under test. + * @param netid The stored netid value under test. + * @param affiliation The affiliation value under test. + */ + @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; + + // Requirements 2.1, 2.2, 2.3: the Account form, classified from the stored fields at + // evaluation time. + assertEquals( + Boolean.valueOf(expected), + Boolean.valueOf(PasswordEligibilityRule.isEligible(accountOf(password, netid, affiliation))), + description + " through the Account form"); + + // Requirements 2.1, 2.2, 2.3: the field-level form, driven by the same case so the two + // forms cannot drift. + assertEquals( + Boolean.valueOf(expected), + Boolean.valueOf(PasswordEligibilityRule.isEligible(password, netid)), + description + " through the field-level form"); + + // Requirement 2.3: no tagging and no migration, so the same stored values classify the same + // way on a repeat evaluation and across two separately constructed Accounts. + assertEquals( + Boolean.valueOf(expected), + Boolean.valueOf(PasswordEligibilityRule.isEligible(accountOf(password, netid, affiliation))), + description + " on a repeat evaluation of an equivalent Account"); + } + + /** + * Property 5, the invariance half, stated as its own assertion rather than left to fall out of + * the case list. + * + * Validates: Requirements 2.8, 16.8 + * + * For one password and netid pair, every enumerated affiliation value is classified, and all of + * the results are asserted equal to one another and equal to the field-level result — which + * cannot see the field at all, because the field is not among its arguments. Varying the field + * while the result is pinned to the value produced without the field is what makes a rule that + * reads {@code User.shibbolethAffiliations} fail. + * + * @param password The stored password value under test. + * @param netid The stored netid value under test. + * @param affiliation Ignored here: this test varies the affiliation itself. The parameter keeps + * the generator shared with the predicate test, so the two cannot drift. + */ + @ParameterizedTest(name = "[{index}] password=''{0}'' netid=''{1}''") + @MethodSource("providePasswordNetidAndAffiliationCombinations") + public void testAffiliationsAreNotConsulted(String password, String netid, Set affiliation) { + // The result computed with no affiliation value in play at all: the field-level overload + // takes the password and the netid only. + 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)); + + // Requirement 2.8: the affiliation value changes nothing, including against the form + // that has no access to it. + assertEquals( + Boolean.valueOf(withoutAffiliations), + Boolean.valueOf(actual), + "Affiliations " + candidate + " altered the classification for password '" + password + "' and netid '" + netid + "'"); + } + + // Requirement 2.8: one distinct result across every affiliation shape — null, empty, + // single-element, and multi-element — so the field is provably not a term of the rule. + assertEquals( + 1, + observed.size(), + "Distinct classifications observed across the affiliation shapes for password '" + password + "' and netid '" + netid + "'"); + + // The classification still tracks the requirement, so the invariance above is not the + // invariance of a rule that returns a constant. + assertEquals( + Boolean.valueOf(expectedEligible(password, netid)), + Boolean.valueOf(withoutAffiliations), + "Classification for password '" + password + "' and netid '" + netid + "'"); + } + + /** + * Property 5, the null-Account case. + * + * Validates: Requirements 2.2 + * + * No Account resolving for the supplied identifier is ineligible, which is the fail-closed + * direction criterion 2 fixes. + */ + @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..95c091d3e4 --- /dev/null +++ b/src/test/java/org/tdl/vireo/utility/PasswordValidatorTest.java @@ -0,0 +1,665 @@ +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; + +/** + * Property 8: Shared validator decision. + * + * Validates: Requirements 3.1, 3.2, 3.3, 3.8 + * + * The property is one {@link ParameterizedTest} fed by an {@link MethodSource} generator producing + * well over one hundred cases, built from the enumerated boundary values — including the trimmed + * length 5 and trimmed length 6 boundary, explicitly, on both sides — crossed with whitespace + * padding shapes and padded from a fixed-seed {@link Random}. No property-based testing library is + * used and no new Maven dependency is introduced. + * + * {@link PasswordValidator} is static and needs no Spring context, so this test starts none. + */ +@ActiveProfiles(value = { "test", "isolated-test" }) +public class PasswordValidatorTest { + + private static final long GENERATOR_SEED = 20250101L; + + private static final int RANDOM_CASE_COUNT = 64; + + /** + * Whitespace runs used both as padding around a candidate and as whole whitespace-only + * candidates. Every one of these trims away to nothing, which is what makes a whitespace-only + * candidate a missing-password case under Requirement 3 criterion 2. + */ + private static final List WHITESPACE_RUNS = Arrays.asList( + "", + " ", + " ", + " ", + "\t", + "\n", + "\r", + " \t\n\r ", + " " + ); + + /** + * The enumerated candidate cores, before any whitespace padding is applied. + * + * The trimmed length 5 and trimmed length 6 boundary is enumerated explicitly across several + * character classes, so the rejected side and the accepted side of the boundary are each pinned + * for letters, digits, symbols, mixed case, and non-ASCII characters. Varying the character + * class while the expected result depends on the trimmed length alone is what pins Requirement + * 3 criterion 8: no character-class constraint exists. + */ + private static final List CANDIDATE_CORES = Arrays.asList( + // Absent and empty. + null, + "", + + // Below the boundary, every length from one to four. + "a", + "ab", + "abc", + "abcd", + + // The rejected side of the boundary: trimmed length 5, across character classes. + "abcde", + "ABCDE", + "12345", + "!@#$%", + "aB3$x", + "\u00e9\u00e8\u00ea\u00eb\u00ec", + + // The accepted side of the boundary: trimmed length 6, across character classes. + "abcdef", + "ABCDEF", + "123456", + "!@#$%^", + "aB3$x.", + "\u00e9\u00e8\u00ea\u00eb\u00ec\u00ed", + + // Comfortably above the boundary. + "abcdefg", + "1234567890", + "correct horse battery staple", + "\u4e2d\u6587\u5bc6\u7801\u5f88\u5f3a\u5927", + + // Interior whitespace, which trimming does not remove, so these clear the boundary on + // their trimmed length. + "a b c", + "a b cd", + "a\tb\tc\td" + ); + + /** + * Each case is one candidate password string. + * + * The enumerated cores are crossed with every whitespace padding shape on each side, which + * produces the pairs that separate a trimmed-length rule from an untrimmed-length one: a + * five-character core padded to eleven characters must still be rejected, and a six-character + * core padded on both sides must still be accepted. + * + * @return The generated cases. + */ + 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); + } + } + + // Whitespace-only candidates, in their own right. + 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(); + } + + /** + * Draw a candidate of a random length drawn from zero through ten — so the boundary lengths + * five and six are both reachable — built from a random character class and wrapped in random + * whitespace padding. + * + * @param random The fixed-seed source. + * + * @return The drawn candidate. + */ + 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; + } + + /** + * The independently computed acceptance rule, written straight from Requirement 3 criteria 1, + * 2 and 3: trim, then decide on the trimmed length alone. + * + * @param candidate The candidate password, which may be null. + * + * @return The expected decision. + */ + 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; + } + + /** + * Property 8: Shared validator decision. + * + * Validates: Requirements 3.1, 3.2, 3.3, 3.8 + * + * The validator reports {@code ACCEPTED} exactly when the candidate holds at least one + * non-whitespace character and the trimmed length is 6 or greater; reports {@code MISSING} when + * the candidate is absent or whitespace-only; and reports {@code TOO_SHORT} when the trimmed + * length is below 6. + * + * The decision is read three ways on every case, so no single reading can carry the property on + * its own: the single-argument overload, the two-argument overload fed a matching confirmation + * — which must agree, since a matching confirmation removes the only cause the two-argument + * form adds — and a repeat call, which must agree with the first because no reuse-history state + * exists (Requirement 3 criterion 8). + * + * @param candidate The candidate password under test. + */ + @ParameterizedTest(name = "[{index}] candidate=''{0}''") + @MethodSource("provideCandidates") + public void testSharedValidatorDecision(String candidate) { + Result expected = expectedResult(candidate); + + String description = "Decision for candidate '" + candidate + "'"; + + // Requirements 3.1, 3.2, 3.3: the decision rests on the trimmed length alone. + assertEquals(expected, PasswordValidator.validate(candidate), description); + + // Requirement 3.8: the minimum is the only constraint, declared as 6, so the expectation + // above and the constant cannot drift apart. + assertEquals(6, PasswordValidator.MINIMUM_TRIMMED_LENGTH, "The declared minimum trimmed length"); + + // Requirement 3.7: a matching confirmation removes the only rejection cause the + // two-argument overload adds, so the two overloads must agree on every candidate. A null + // candidate is MISSING before the comparison is reached either way. + assertEquals(expected, PasswordValidator.validate(candidate, candidate), description + " through the confirming overload"); + + // Requirement 3.8: no reuse-history constraint exists, so the same candidate decided twice + // decides the same way. + assertEquals(expected, PasswordValidator.validate(candidate), description + " on a repeat decision"); + } + + /** + * The enumerated candidate and confirmation values for Property 9, crossed with themselves. + * + * The list is chosen so the cross product contains the pairs that separate a raw-string + * comparison from any looser one: pairs differing only in letter case, pairs differing only in + * leading or trailing whitespace, pairs differing only in the kind of trailing whitespace, and + * the absent and whitespace-only values on either side. + */ + private static final List CONFIRMATION_VALUES = Arrays.asList( + // Absent and whitespace-only, on either side of the pair. + null, + "", + " ", + " ", + "\t", + + // Below and at the boundary, so a mismatch and a too-short cause can both be in play. + "abcde", + "abcde ", + "abcdef", + + // Letter-case-only differences from "abcdef". + "ABCDEF", + "Abcdef", + "abcdeF", + + // Surrounding-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" + ); + + /** + * Each case is one candidate and confirmation pair. + * + * Every enumerated value is crossed with every enumerated value, which yields the equal pairs + * and the differing pairs together — the property is an "exactly when", so both sides have to + * be generated. A fixed-seed {@link Random} then adds pairs drawn from the same value pool, + * including pairs built by perturbing a drawn value in a single character, which is the + * near-miss shape a comparison looser than equality would let through. + * + * @return The generated cases. + */ + 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: + // The same raw value, so the accepting side of the property 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(); + } + + /** + * Alter one character of the supplied value, or append one when the value is empty, so the + * result differs from the input in exactly one position. + * + * @param value The value to perturb. + * @param random The fixed-seed source. + * + * @return The perturbed value, which 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); + } + + /** + * The independently computed decision for a pair, written straight from Requirement 3 criteria + * 1 through 4 in the order the design fixes: missing, then mismatch, then too short. + * + * @param candidate The candidate password, which may be null. + * @param confirmation The confirmation value, which may be null. + * + * @return The expected decision. + */ + 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; + } + + /** + * Property 9: Confirmation mismatch. + * + * Validates: Requirements 3.4 + * + * The validator reports {@code MISMATCH} exactly when the candidate is present and the two raw + * strings differ — including when they differ only in letter case, or only in surrounding + * whitespace. The present qualifier is the evaluation order the design fixes: an absent or + * whitespace-only candidate is {@code MISSING} before the comparison is reached, so the + * mismatch claim is scoped to the candidates that get as far as being compared. + * + * Comparison is on the raw values, not the trimmed ones, which is why a candidate padded with + * whitespace against its unpadded confirmation is a mismatch rather than an acceptance. + * + * @param candidate The candidate password under test. + * @param confirmation The confirmation value under test. + */ + @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); + + // Requirement 3.4: the mismatch cause, in its place in the evaluation order. + assertEquals(expected, actual, description); + + boolean candidatePresent = candidate != null && candidate.trim().length() > 0; + + // Requirement 3.4, as the "exactly when" it is stated as: among the candidates that reach + // the comparison, MISMATCH is reported precisely for the pairs whose raw strings differ. + assertEquals( + Boolean.valueOf(candidatePresent && !candidate.equals(confirmation)), + Boolean.valueOf(Result.MISMATCH.equals(actual)), + description + " reported as a mismatch"); + + // Requirement 3.4: a mismatch is a rejection, and it is reported as the mismatch cause + // rather than folded into another one. + if (Result.MISMATCH.equals(actual)) { + assertEquals("The passwords do not match!", PasswordValidator.messageFor(actual), description + " message"); + } + } + + /** + * The candidate cores used for Property 10, all of them carrying at least one non-whitespace + * character so padding them produces a meaningful untrimmed-against-trimmed distinction. + * + * Both sides of the boundary are present: cores whose trimmed length is below 6, which must be + * rejected however much whitespace surrounds them, and cores whose trimmed length is 6 or + * greater, which must be accepted and stored with their padding intact. + */ + private static final List STORAGE_CORES = Arrays.asList( + // Below the boundary on the trimmed value. + "a", + "abc", + "abcde", + "12345", + "!@#$%", + + // At and above the boundary on the trimmed value. + "abcdef", + "ABCDEF", + "123456", + "!@#$%^", + "aB3$x.", + "abcdefg", + "correct horse battery staple", + "\u00e9\u00e8\u00ea\u00eb\u00ec\u00ed", + "\u4e2d\u6587\u5bc6\u7801\u5f88\u5f3a" + ); + + /** + * The whitespace runs padded around a core for Property 10. The empty run is deliberately + * absent on its own account — it is still reachable, because each core is also emitted + * unpadded — so that every generated padded case genuinely differs from its trimmed form. + */ + private static final List STORAGE_PADDING = Arrays.asList( + " ", + " ", + "\t", + "\n", + "\r\n", + " \t\n\r ", + " " + ); + + /** + * Each case is one candidate password, most of them padded so the untrimmed value and the + * trimmed value differ. + * + * Every core is crossed with every padding run on the leading side, the trailing side, and both + * sides at once, which is what produces the shapes that separate storing the untrimmed value + * from storing the trimmed one. A fixed-seed {@link Random} then adds further padded draws. + * + * @return The generated cases. + */ + 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(); + } + + /** + * A stand-in for the password encoder, recording the exact value it is handed so the stored + * value can be compared against the submitted one by identity as well as by equality. + * + * The encoding itself is irrelevant to this property — the claim is about which string reaches + * the encoder — so a recording stand-in is used rather than a real BCrypt encoder, which would + * add seconds per case for nothing. + */ + private static final class RecordingEncoder { + + private String encoded; + + private int invocations; + + private String encode(String raw) { + this.encoded = raw; + this.invocations++; + + return "{encoded}" + raw; + } + + } + + /** + * The caller shape the design fixes for every accepting path: validate the pair, and on + * {@code ACCEPTED} hand the **untrimmed** candidate to the encoder, with nothing stored on a + * rejection. + * + * @param candidate The candidate password. + * @param confirmation The confirmation value. + * @param encoder The recording stand-in. + * + * @return The validator's decision. + */ + 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; + } + + /** + * Property 10: Untrimmed storage. + * + * Validates: Requirements 3.5 + * + * For any accepted candidate password carrying leading or trailing whitespace, the value handed + * to the password encoder is the untrimmed candidate, while the length check that accepted it + * was applied to the trimmed value. + * + * Three things together make up the claim, and all three are asserted on every case: + * + * 1. The acceptance decision is governed by the trimmed length. A padded candidate is accepted + * exactly when its trimmed length reaches the minimum, so ten spaces around a five-character + * core is still {@code TOO_SHORT} and a six-character core padded on both sides is still + * {@code ACCEPTED}. + * 2. The value that reaches the encoder is the submitted string itself — the same object, not a + * trimmed, stripped, or otherwise normalised copy — so the padding survives into storage. + * 3. The validator offers the caller no normalised form to store in its place. Its only + * String-returning member is {@code messageFor}, so the only value a caller holds after an + * accepting decision is the untrimmed candidate it submitted. That is asserted reflectively, + * because it is a claim about the shape of the API rather than about one call. + * + * @param candidate The candidate password under test. + */ + @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); + + // Requirement 3.5, first half: the length check that decides acceptance is applied to the + // trimmed value, so the decision for a padded candidate matches the decision for its + // trimmed core. + 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)) { + // Nothing is stored on a rejection, so there is no value to make a claim about. + assertEquals(0, encoder.invocations, description + " handed to the encoder despite rejection"); + assertNull(encoder.encoded, description + " recorded despite rejection"); + + return; + } + + // Requirement 3.5, second half: the encoder is handed the untrimmed candidate — the very + // string that was submitted, padding and all. + 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"); + + // The two halves are only distinguishable where the padding is real, so pin the difference + // explicitly wherever it exists: the stored value is not the trimmed value. + if (!candidate.equals(trimmed)) { + assertTrue(!trimmed.equals(encoder.encoded), description + " stored trimmed rather than untrimmed"); + } + + // Requirement 3.5: the validator hands a caller no normalised candidate to store in place of + // the submitted one. 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"); + } + } + } + +} From 8f36cea3842c33d6dbe6c1a58d47733e9f09fc2f Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Fri, 16 Oct 2026 13:58:19 -0400 Subject: [PATCH 02/20] Remove redundant tests in the PasswordControllerTest.java --- .../vireo/controller/PasswordController.java | 121 ++++ .../controller/PasswordControllerTest.java | 566 ++++++++++++++++++ .../CredentialNotificationServiceTest.java | 106 ++++ 3 files changed, 793 insertions(+) create mode 100644 src/main/java/org/tdl/vireo/controller/PasswordController.java create mode 100644 src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java diff --git a/src/main/java/org/tdl/vireo/controller/PasswordController.java b/src/main/java/org/tdl/vireo/controller/PasswordController.java new file mode 100644 index 0000000000..0566044417 --- /dev/null +++ b/src/main/java/org/tdl/vireo/controller/PasswordController.java @@ -0,0 +1,121 @@ +package org.tdl.vireo.controller; + +import static edu.tamu.weaver.response.ApiStatus.INVALID; +import static edu.tamu.weaver.response.ApiStatus.SUCCESS; +import static org.springframework.web.bind.annotation.RequestMethod.POST; + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; +import org.tdl.vireo.model.User; +import org.tdl.vireo.model.repo.UserRepo; +import org.tdl.vireo.service.CredentialNotificationService; +import org.tdl.vireo.service.PasswordFeatureAvailabilityService; +import org.tdl.vireo.utility.PasswordEligibilityRule; +import org.tdl.vireo.utility.PasswordValidator; + +import edu.tamu.weaver.auth.annotation.WeaverUser; +import edu.tamu.weaver.auth.service.CryptoService; +import edu.tamu.weaver.response.ApiResponse; +import edu.tamu.weaver.validation.results.ValidationResults; +import edu.tamu.weaver.validation.utility.ValidationUtility; + +/** + * The Vireo-managed password operations. + * + * A controller of its own, rather than new methods on {@code AuthController}, so the single + * behavior-altering change to that class stays isolated and its existing test suite remains the + * evidence that the change is outcome-preserving. + * + * No response from any handler here carries a password value or a reset token. + */ +@RestController +@RequestMapping("/password") +public class PasswordController { + + private static final Logger LOG = LoggerFactory.getLogger(PasswordController.class); + + @Autowired + private UserRepo userRepo; + + @Autowired + private PasswordFeatureAvailabilityService availabilityService; + + @Autowired + private CredentialNotificationService credentialNotificationService; + + @Autowired + private CryptoService cryptoService; + + /** + * Replace the stored password on the authenticated Account. + * + * The target Account is taken from {@code @WeaverUser} only, so no identifier in the request + * body can redirect the change to another Account. + * + * The gates are evaluated in order — availability, eligibility, current-password verification, + * then candidate validation — and nothing is written when any of them rejects. No rate limiting + * is applied to the current-password verification. + * + * @param user The authenticated Account. + * @param data {@code currentPassword}, {@code newPassword}, and {@code confirm}. + * + * @return SUCCESS once the stored password has been replaced, otherwise INVALID with the reason. + */ + @PreAuthorize("hasRole('ROLE_STUDENT')") + @RequestMapping(value = "/change", method = POST) + public ApiResponse changePassword(@WeaverUser User user, @RequestBody 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); + } + + // The untrimmed value is encoded, so a password holding leading or trailing whitespace is + // stored and later verified with that whitespace intact. + user.setPassword(cryptoService.encodePassword(newPassword)); + + user = userRepo.update(user); + + credentialNotificationService.notifyPasswordChanged(user); + + return new ApiResponse(SUCCESS, "Your password has been changed."); + } + +} 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..47909bfb31 --- /dev/null +++ b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java @@ -0,0 +1,566 @@ +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.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 java.lang.reflect.Method; +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 org.tdl.vireo.config.constant.ConfigurationName; +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.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; + +/** + * Server-side enforcement, targeting and leak-containment assertions for {@code POST /password/change}. + * + * Validates: Requirements 2.5, 2.6, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 6.4, 7.6, 10.6, 13.2, 13.3, 14.4, 16.9 + * + * One parameterized test carries Properties 12 (change arm), 13, 14 and 26 (change arm), because + * they share a single setup: a request against an Account under some availability state. Every case + * pins the same outcomes. The stored password is replaced exactly when the availability conjunction, + * the eligibility rule, the current-password check and the candidate validator all pass. A rejected + * case leaves the stored password byte-identical and produces no write, no notification, no encode + * and no email. Only the authenticated Account is ever written. No password or token value appears + * in the response or the log. + * + * BCrypt is real only where a case succeeds, since that is where the test asserts the persisted + * value verifies against the new password. Every other case uses a cheap prefix-based stand-in for + * the stored hash, which discriminates match from mismatch identically. + */ +@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; + + /** + * The raw Password_Login_Setting and {@code auth.pass.change.enabled} pairs: both on, each arm + * off on its own, both off, the trimmed and mixed-case accepting spellings, absent values, and + * the near-miss strings an administrator might expect to mean true. + */ + 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: accepted, the length 6 and length 5 boundary, mismatched, + * absent, whitespace-only, and an accepted value carrying surrounding whitespace. + */ + private static final String[][] CANDIDATE_PAIRS = { + { NEW_PASSWORD, NEW_PASSWORD }, + { "abcdef", "abcdef" }, + { "abcde", "abcde" }, + { NEW_PASSWORD, "newpasswordx" }, + { null, null }, + { NEW_PASSWORD, null }, + { " ", " " }, + { " padded ", " padded " } + }; + + /** + * Identifier key names an implementation might read out of the request body to pick a target + * Account. None is honored; the authenticated principal is the only source of the 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" }; + + /** + * What a client might assert about its own rendering, carried in the request body. None of it + * is read: the server re-derives availability from the configuration store and eligibility from + * the stored Account fields on every request. + */ + 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; + + @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() { + // Requirement 5 criterion 5: an authentication-failure result, nothing written. + 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() { + // Requirement 5 criterion 6: every rejection cause the shared validator reports. + 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 { + // Requirement 5 criteria 4, 8: the baseline authenticated role, matching + // /user/settings/update. An unauthenticated or under-privileged caller is turned away by + // Spring Security before the handler body runs, which is what this annotation expresses. + 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]); + } + + // Feature: user-password-reset, Property 12 (change arm): For any ineligible Account shape and + // any setting pair that resolves the capability unavailable, a Password_Change_Request is + // rejected, the stored password is left unchanged, and no email is sent. The reset and + // redemption arms join this property in tasks 12 and 13. + // + // Feature: user-password-reset, Property 13: For any combination of availability state, + // Account eligibility shape, current-password match or mismatch, and candidate password + // validity, the stored password is replaced exactly when all four conditions hold; and whenever + // it is replaced, the persisted value verifies against the submitted new password and does not + // verify against the previous password. + // + // Feature: user-password-reset, Property 14: For any Password_Change_Request body carrying + // arbitrary foreign Account identifiers, only the stored password of the authenticated Account + // is written. + // + // Feature: user-password-reset, Property 26 (change arm): For any password value and any token + // value, the /password/change response (status, message, payload) and the log output written + // while handling the request do not carry it. The password-changed notification arm is in + // CredentialNotificationServiceTest; the reset, redemption and email-change arms are added in + // later tasks, each as new scenarios in the case list and new artefacts in the check below. + // + // Validates: Requirements 2.5, 2.6, 5.1, 5.2, 5.3, 5.5, 5.6, 5.7, 6.4, 7.6, 7.8, 7.9, 9.7, 9.8, 10.6, 13.2, 13.3, 14.4 + // + // Every request carries the token entries and the client-asserted entries alongside the three + // honored keys, and the repository lookups by email, netid and id are all stubbed to return a + // foreign Account, so a handler that honored any of them would be observable. + @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 { + // The four conditions of the conjunction, derived from the requirement text rather than + // from the handler, so the expectation is independent of the implementation's 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 authenticated Account was written or notified, and nothing else was looked up. + verify(userRepo).update(user1); + verifyNoMoreInteractions(userRepo); + + verify(credentialNotificationService).notifyPasswordChanged(user1); + verifyNoMoreInteractions(credentialNotificationService); + } else { + assertRejected(response); + + // No credential material is produced on a rejected path, and no email leaves by any route. + 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()); + } + + /** + * The cases for the change arm. Every case is a nine-tuple of the raw Password_Login_Setting + * value, the raw {@code auth.pass.change.enabled} value, the stored-password shape, the netid, + * the supplied current password, the candidate, the confirmation, extra request body entries, + * and a label. + * + * Each block walks one dimension through its boundary values with the others held at a shape + * that succeeds on its own, so each is pinned as individually load-bearing. The both-failing + * block crosses the two server-side gates, so a handler that returned early on one gate and + * skipped the other is still caught. The foreign-identifier block runs accepted requests with + * identifier entries that point at another Account. The secret block runs unusual password + * values through the accepting path and the current-password-mismatch path. Client-asserted + * body entries are rotated across the first blocks. + * + * @return The generated cases. + */ + 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)); + } + + /** + * Neither a password value nor a token value may appear in the serialized response, its + * message, its payload, or any log line written while handling the request. + */ + 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 + ")"); + } + } + } + + /** + * Run the handler with the controller's logger lowered to ALL, since the test configuration + * pins org.tdl.vireo at ERROR and the handler logs its rejections at DEBUG, collecting what it + * writes into {@code lines}. The level is restored afterwards. + */ + 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()); + } + } + } + + /** + * The server's boolean resolution, restated from Requirement 1 criterion 13 rather than called + * through the service, so the property's expectation does not inherit a defect in it. + */ + private static boolean resolvesTrue(String raw) { + return raw != null && raw.trim().equalsIgnoreCase("true"); + } + + /** + * The three outcomes every rejection case pins: INVALID, an unchanged stored password, and no + * notification dispatch. No write reaches the repository either. + */ + 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; + } + + /** + * Stub the two settings the change conjunction reads. 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); + } + + /** + * Route the mocked {@code CryptoService} onto the real encoder, so verification and encoding + * are the genuine operations. Used only where a case succeeds. + */ + 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))); + } + + /** + * A cheap stand-in for hashing: a stored value matches exactly when it is the prefix plus the + * supplied value, so a match and a mismatch are told apart without paying for BCrypt. + */ + 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)); + } + +} diff --git a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java index 43c75ef935..8043b78137 100644 --- a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java @@ -50,6 +50,7 @@ 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; @@ -694,4 +695,109 @@ private String packagedBody(String raw) { return data.substring(index); } + /* + * Task 7.6 — Property 26: Leak containment across every outbound artefact, the + * password-changed-notification arm. + */ + + 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" }; + + /** + * Each case is a scenario and the secret material the Account carries. The enumerated cases + * cross every scenario with every secret shape; the fixed-seed random cases add generated + * secrets, 21 enumerated plus 100 random. + * + * @return The generated cases. + */ + 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(); + } + + /** + * Property 26: Leak containment, password-changed-notification arm. + * + * Validates: Requirements 6.4, 13.2, 13.3, 14.4 + * + * For any password value and token value held by the Account, the dispatched subject and body + * and every log record written by the notification contain neither. + * + * @param scenario The dispatch outcome under test. + * @param base The secret material the Account's password and token are derived from. + */ + @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))); + + // The real packaged subject and body, so the artefact under assertion is the one shipped. + 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); + } + } + } + } From 0bbe46026cde5d11e6049722f7a7cf232dc81d31 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Fri, 16 Oct 2026 15:08:50 -0400 Subject: [PATCH 03/20] Add password management front-end --- src/main/webapp/app/config/apiMapping.js | 5 ++ .../controllers/changePasswordController.js | 44 +++++++++++++++++ .../app/controllers/settingsController.js | 13 +++++ src/main/webapp/app/repo/userRepo.js | 12 +++++ .../app/views/admin/settings/application.html | 1 + .../application/passwordManagement.html | 45 ++++++++++++++++++ src/main/webapp/app/views/myprofile.html | 47 +++++++++++++++++++ 7 files changed, 167 insertions(+) create mode 100644 src/main/webapp/app/controllers/changePasswordController.js create mode 100644 src/main/webapp/app/views/admin/settings/application/passwordManagement.html diff --git a/src/main/webapp/app/config/apiMapping.js b/src/main/webapp/app/config/apiMapping.js index 99c5f53677..fbb872bfc7 100644 --- a/src/main/webapp/app/config/apiMapping.js +++ b/src/main/webapp/app/config/apiMapping.js @@ -961,6 +961,11 @@ var apiMapping = { 'controller': 'user', 'method': 'page' }, + changePassword: { + 'endpoint': '/private/queue', + 'controller': 'password', + 'method': 'change' + }, createListen: { 'endpoint': '/channel', 'controller': 'user/create' diff --git a/src/main/webapp/app/controllers/changePasswordController.js b/src/main/webapp/app/controllers/changePasswordController.js new file mode 100644 index 0000000000..2bb6378ed0 --- /dev/null +++ b/src/main/webapp/app/controllers/changePasswordController.js @@ -0,0 +1,44 @@ +vireo.controller('ChangePasswordController', function ($controller, $scope, UserRepo) { + + angular.extend(this, $controller('AbstractController', { $scope: $scope })); + + $scope.userRepo = UserRepo; + + $scope.passwordChange = { + currentPassword: '', + newPassword: '', + confirm: '' + }; + + // 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 () { + return UserRepo.changePassword( + $scope.passwordChange.currentPassword, + $scope.passwordChange.newPassword, + $scope.passwordChange.confirm + ).then(clear, clear); + }; + +}); diff --git a/src/main/webapp/app/controllers/settingsController.js b/src/main/webapp/app/controllers/settingsController.js index 461356c4b8..a0e44d7839 100644 --- a/src/main/webapp/app/controllers/settingsController.js +++ b/src/main/webapp/app/controllers/settingsController.js @@ -82,6 +82,19 @@ vireo.controller("SettingsController", function ($controller, $injector, $scope, "false": "No" }]; + // PASSWORD MANAGEMENT + $scope.changePasswordToggleOptions = [{ + "true": "Enabled" + }, { + "false": "Disabled" + }]; + + $scope.resetPasswordToggleOptions = [{ + "true": "Enabled" + }, { + "false": "Disabled" + }]; + var userSettingsValidations = { "displayName": { "minlength": { diff --git a/src/main/webapp/app/repo/userRepo.js b/src/main/webapp/app/repo/userRepo.js index c895dbd854..ab591ca51a 100644 --- a/src/main/webapp/app/repo/userRepo.js +++ b/src/main/webapp/app/repo/userRepo.js @@ -8,6 +8,18 @@ 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.getAssignableUsers = function(page, size, name) { var assignable = []; 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..09c51fbd5c --- /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/myprofile.html b/src/main/webapp/app/views/myprofile.html index 886d9343aa..74b1d86e9a 100644 --- a/src/main/webapp/app/views/myprofile.html +++ b/src/main/webapp/app/views/myprofile.html @@ -240,6 +240,53 @@

Preferences

+ +
+
+ +

Change Password

+ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+
+ +
+
+
+ +
+ +
+
+ From 96e168126e35e4efbacc494e0b4f43ddde0a7837 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Fri, 16 Oct 2026 15:55:51 -0400 Subject: [PATCH 04/20] Update documentation --- .../vireo/controller/PasswordController.java | 25 +- .../tdl/vireo/controller/UserController.java | 6 +- src/main/java/org/tdl/vireo/model/User.java | 10 +- .../CredentialNotificationService.java | 48 +--- .../PasswordFeatureAvailabilityService.java | 69 +---- .../utility/PasswordEligibilityRule.java | 29 +- .../tdl/vireo/utility/PasswordValidator.java | 51 +--- .../vireo/controller/AuthControllerTest.java | 115 +------- .../controller/PasswordControllerTest.java | 133 ++------- .../vireo/controller/UserControllerTest.java | 18 +- .../CredentialNotificationServiceTest.java | 251 +++-------------- ...asswordFeatureAvailabilityServiceTest.java | 186 ++----------- .../utility/PasswordEligibilityRuleTest.java | 155 ++--------- .../vireo/utility/PasswordValidatorTest.java | 262 +++--------------- 14 files changed, 193 insertions(+), 1165 deletions(-) diff --git a/src/main/java/org/tdl/vireo/controller/PasswordController.java b/src/main/java/org/tdl/vireo/controller/PasswordController.java index 0566044417..ade626a49c 100644 --- a/src/main/java/org/tdl/vireo/controller/PasswordController.java +++ b/src/main/java/org/tdl/vireo/controller/PasswordController.java @@ -27,13 +27,7 @@ import edu.tamu.weaver.validation.utility.ValidationUtility; /** - * The Vireo-managed password operations. - * - * A controller of its own, rather than new methods on {@code AuthController}, so the single - * behavior-altering change to that class stays isolated and its existing test suite remains the - * evidence that the change is outcome-preserving. - * - * No response from any handler here carries a password value or a reset token. + * Vireo-managed password operations. No response carries a password value or reset token. */ @RestController @RequestMapping("/password") @@ -54,19 +48,11 @@ public class PasswordController { private CryptoService cryptoService; /** - * Replace the stored password on the authenticated Account. + * Replaces the password on the authenticated Account only; nothing in the request body can + * target another Account. Checks run in order (availability, eligibility, current password, + * new password) and nothing is written if any rejects. * - * The target Account is taken from {@code @WeaverUser} only, so no identifier in the request - * body can redirect the change to another Account. - * - * The gates are evaluated in order — availability, eligibility, current-password verification, - * then candidate validation — and nothing is written when any of them rejects. No rate limiting - * is applied to the current-password verification. - * - * @param user The authenticated Account. * @param data {@code currentPassword}, {@code newPassword}, and {@code confirm}. - * - * @return SUCCESS once the stored password has been replaced, otherwise INVALID with the reason. */ @PreAuthorize("hasRole('ROLE_STUDENT')") @RequestMapping(value = "/change", method = POST) @@ -107,8 +93,7 @@ public ApiResponse changePassword(@WeaverUser User user, @RequestBody Map allCredentials, so the value is the - // String "true" or "false" and never a JSON boolean. + // User.password is @JsonIgnore'd, so the server computes eligibility. It rides in allCredentials as the String "true" or "false". + Map allCredentials = credentials.getAllCredentials(); if (allCredentials == null) { diff --git a/src/main/java/org/tdl/vireo/model/User.java b/src/main/java/org/tdl/vireo/model/User.java index a854d4bc88..4b4801c870 100644 --- a/src/main/java/org/tdl/vireo/model/User.java +++ b/src/main/java/org/tdl/vireo/model/User.java @@ -545,14 +545,8 @@ public String getUsername() { } /** - * Whether this Account is eligible for Vireo-managed password operations, derived from the - * stored password and netid values at evaluation time. - * - * Carries no {@code @JsonView} annotation deliberately: with default view inclusion disabled, - * an un-annotated property serializes only when no view is active, which confines the flag to - * the no-view listing endpoints. - * - * @return true when this Account is eligible + * 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() { diff --git a/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java b/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java index 035e33ed78..04c0d5e788 100644 --- a/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java +++ b/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java @@ -16,19 +16,11 @@ import org.tdl.vireo.utility.TemplateUtility; /** - * Dispatch the credential-change notifications. + * Sends credential-change notifications. * - * Every notification this service sends is advisory: the credential change it reports has already - * been persisted by the time the notification is attempted. An absent Email_Template or a mail - * transport failure is therefore recorded in the application log and swallowed, so the completed - * change stands. - * - * Reset-initiation mail is deliberately not sent from this service. That path reports an ERROR - * {@code ApiResponse} to the initiating Administrator on a mail failure, which is the opposite - * failure semantics, so it stays in the controller. Only the nullable template lookup is shared. - * - * Notifications are dispatched from the request thread that persisted the change. No dispatch state - * is retained and no retry is performed. + * 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 { @@ -59,14 +51,8 @@ public class CredentialNotificationService { private Clock clock = Clock.systemUTC(); /** - * Notify the holder of an Account that the stored password on that Account has changed. - * - * Never throws. An absent Email_Template or a {@link MessagingException} is recorded in the - * application log, naming the Account and the notification, and swallowed, so the completed - * password change stands. Neither the password value nor any token appears in the log or in the - * message body. - * - * @param user The Account whose password changed. + * 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) { @@ -101,18 +87,9 @@ public void notifyPasswordChanged(User user) { } /** - * Resolve an Email_Template by name, preferring a custom row over the system row. - * - * The result of {@code findByNameOverride} is tested for null before any {@code getSubject()} - * or {@code getMessage()} call, so a deployment where the row was never installed produces a - * logged skip rather than a {@link NullPointerException}. - * - * Shared with the reset-initiation path, which reports ERROR on a null result while the - * notifications log and continue. + * Resolves an email template by name, preferring a custom row over the system row. * - * @param name The Email_Template name. - * - * @return The resolved template, or null when neither a custom nor a system row exists. + * @return The template, or null (logged) when neither exists. */ public EmailTemplate resolveTemplate(String name) { EmailTemplate emailTemplate = emailTemplateRepo.findByNameOverride(name); @@ -126,14 +103,7 @@ public EmailTemplate resolveTemplate(String name) { return emailTemplate; } - /** - * Format the time of the change for the {@code CHANGE_TIME} template parameter. - * - * The value is rendered at {@link ZoneOffset#UTC} and labelled as such, so the timestamp is - * unambiguous for a recipient in any timezone. - * - * @return The formatted time of the change. - */ + /** 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 index 378da24040..c50d0bc214 100644 --- a/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java +++ b/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java @@ -8,12 +8,10 @@ import org.tdl.vireo.model.repo.ConfigurationRepo; /** - * Resolve the password feature configuration settings and report feature availability. + * Resolves the password feature settings and reports feature availability. * - * Every accessor resolves its setting through - * {@code configurationRepo.getValueByNameAndType(name, "application")} on each invocation. No - * resolved setting value is held in a field, so an Administrator save applies to every later - * request with no application restart. + * Settings are read on every call and never cached, so an administrator save takes effect without + * a restart. */ @Service public class PasswordFeatureAvailabilityService { @@ -27,55 +25,27 @@ public class PasswordFeatureAvailabilityService { @Autowired private ConfigurationRepo configurationRepo; - /** - * Resolve the Password_Login_Setting, {@code auth.pass.enabled}. - * - * @return The resolved value, false when absent or unrecognised. - */ + /** 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); } - /** - * Resolve {@code auth.pass.change.enabled}. - * - * @return The resolved value, false when absent or unrecognised. - */ + /** 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); } - /** - * Resolve {@code auth.pass.reset.enabled}. - * - * @return The resolved value, false when absent or unrecognised. - */ + /** 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); } - /** - * Report whether self-service password change is available. - * - * Reads the Password_Login_Setting itself, so wiring login to honor that setting later requires - * no change here. - * - * @return True only when the Password_Login_Setting and {@code auth.pass.change.enabled} both - * resolve to true. - */ + /** True only when both {@code auth.pass.enabled} and {@code auth.pass.change.enabled} are true. */ public boolean isChangeAvailable() { return isPasswordLoginEnabled() && isChangeEnabled(); } - /** - * Report whether administrator-initiated reset is available. - * - * Reads the Password_Login_Setting itself, so wiring login to honor that setting later requires - * no change here. - * - * @return True only when the Password_Login_Setting and {@code auth.pass.reset.enabled} both - * resolve to true. - */ + /** True only when both {@code auth.pass.enabled} and {@code auth.pass.reset.enabled} are true. */ public boolean isResetAvailable() { return isPasswordLoginEnabled() && isResetEnabled(); } @@ -84,13 +54,8 @@ public boolean isResetAvailable() { // PasswordEligibilityRule. /** - * Resolve {@code auth.pass.reset.expiryHours}. - * - * A value that does not parse as an integer, or that falls outside 1 to - * {@link Integer#MAX_VALUE} inclusive, yields {@link #DEFAULT_RESET_EXPIRY_HOURS}, leaves the - * stored value unchanged, and is recorded in the application log. - * - * @return The resolved expiry in hours. + * 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); @@ -121,18 +86,8 @@ public int getResetExpiryHours() { } /** - * Resolve a raw configuration value as a boolean, comparing with surrounding whitespace and - * letter case ignored. - * - * An absent value resolves false. A value matching neither true nor false resolves false and is - * recorded in the application log. - * - * Visible for test. - * - * @param raw The raw stored value. - * @param settingName The setting name, for the log message. - * - * @return The resolved value. + * 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) { diff --git a/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java b/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java index 6454b4134b..179bef5d88 100644 --- a/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java +++ b/src/main/java/org/tdl/vireo/utility/PasswordEligibilityRule.java @@ -3,27 +3,17 @@ import org.tdl.vireo.model.User; /** - * The server-side predicate that classifies an Account as eligible for Vireo-managed password - * operations, or as ineligible. + * Classifies an Account as eligible for Vireo-managed password operations. Reads only + * {@code User.password} and {@code User.netid}. * - * Static and stateless by design: an injected bean would arrive null under the {@code @InjectMocks} - * wiring every existing controller test uses. - * - * Reads {@code User.password} and {@code User.netid} only, and consults - * {@code User.shibbolethAffiliations} in no part of the classification (Requirement 2 criterion 8). + * Static and stateless so it works under the {@code @InjectMocks} wiring used by controller tests. */ public final class PasswordEligibilityRule { private PasswordEligibilityRule() { } - /** - * Requirement 2 criteria 1, 2: eligible if and only if the password holds a non-whitespace - * character and the netid is null. A null {@link User} is ineligible. - * - * @param user the Account to classify, which may be null - * @return true when the Account is an Eligible_Account - */ + /** 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; @@ -32,16 +22,7 @@ public static boolean isEligible(User user) { return isEligible(user.getPassword(), user.getNetid()); } - /** - * Field-level form, so the rule can be evaluated without a {@link User} instance. - * - * Requirement 2 criteria 1, 2, 3: the classification is derived from the supplied stored field - * values at evaluation time, with no administrator tagging and no migration. - * - * @param password the stored password value, which may be null - * @param netid the stored netid value, which may be null - * @return true when the values describe an Eligible_Account - */ + /** Field-level form of {@link #isEligible(User)}. */ public static boolean isEligible(String password, String netid) { if (netid != null) { return false; diff --git a/src/main/java/org/tdl/vireo/utility/PasswordValidator.java b/src/main/java/org/tdl/vireo/utility/PasswordValidator.java index 508b9e21d5..61bc1f5201 100644 --- a/src/main/java/org/tdl/vireo/utility/PasswordValidator.java +++ b/src/main/java/org/tdl/vireo/utility/PasswordValidator.java @@ -1,41 +1,25 @@ package org.tdl.vireo.utility; /** - * The single server-side decision on whether a candidate password is acceptable. + * 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 by design: an injected bean would arrive null under the {@code @InjectMocks} - * wiring every existing controller test uses. - * - * The acceptance rule is exactly the existing one in {@code AuthController.registration}: non-blank, - * trimmed length {@value #MINIMUM_TRIMMED_LENGTH} or greater. No character-class, reuse-history, or - * expiry constraint is added (Requirement 3 criterion 8). + * 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; the other three name - * the rejection cause. - */ + /** The outcome of a validation; {@code ACCEPTED} is the only accepting value. */ public enum Result { ACCEPTED, MISSING, TOO_SHORT, MISMATCH } - /** - * Requirement 3 criterion 2: the minimum acceptable trimmed length. - */ + /** The minimum acceptable trimmed length. */ public static final int MINIMUM_TRIMMED_LENGTH = 6; private PasswordValidator() { } - /** - * Requirement 3 criteria 1, 2, 3: a candidate with no confirmation to compare against. Absent or - * blank is {@code MISSING}; a trimmed length below {@link #MINIMUM_TRIMMED_LENGTH} is - * {@code TOO_SHORT}; anything else is {@code ACCEPTED}. - * - * @param candidate the proposed password, which may be null - * @return the decision - */ + /** 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; @@ -49,15 +33,9 @@ public static Result validate(String candidate) { } /** - * Requirement 3 criteria 1 through 4. Evaluation order is {@code MISSING}, then {@code MISMATCH}, - * then {@code TOO_SHORT}, matching the existing order in {@code AuthController.registration} so - * the retrofit is outcome-preserving (Requirement 3 criterion 9). - * - * The confirmation comparison is on the untrimmed values, again matching the existing behavior. - * - * @param candidate the proposed password, which may be null - * @param confirmation the repeated password, which may be null - * @return the decision + * 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) { @@ -76,14 +54,9 @@ public static Result validate(String candidate, String confirmation) { } /** - * Requirement 3 criteria 7, 9: the existing {@code AuthController} message text, verbatim, for - * each rejection, so the retrofit preserves the response body as well as the {@code ApiStatus}. - * - * The {@code TOO_SHORT} text misdescribes a {@code >= 6} rule. It is preserved anyway: outcome - * preservation is required and the Minimal Change Constraint forbids opportunistic correction. - * - * @param result the decision to describe - * @return the message for a rejection, or null for {@code 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) { diff --git a/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java b/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java index ccc3430451..8629f2bc97 100644 --- a/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java @@ -324,15 +324,7 @@ private void setupDataMap() { data.put("confirm", data.get("userPassword")); } - /* ------------------------------------------------------------------------------------------ - * Property 11: Registration retrofit preserves outcomes. - * - * Validates: Requirements 3.6, 3.7, 3.9 - * - * Everything below is additive. No method above this point is edited, reordered, or - * reformatted: the unchanged methods are the example-based regression evidence for the - * retrofit, and this property generalises the same claim over generated input. - * ------------------------------------------------------------------------------------------ */ + // Property 11: registration retrofit preserves outcomes. Additive; existing tests above are unchanged. private static final long RETROFIT_GENERATOR_SEED = 20250101L; @@ -340,26 +332,7 @@ private void setupDataMap() { private static final String REGISTRATION_SUCCESS_MESSAGE = "Registration was successfull. Please login."; - /** - * The candidate and confirmation values crossed with themselves to form the enumerated cases. - * - * The list is chosen so the cross product contains every shape that can tell the three - * rejection causes apart, in the order {@code AuthController.registration} evaluated them - * before the retrofit: - * - * - Absent and whitespace-only values, which must be reported as a missing password even when - * the confirmation differs — that is what pins missing ahead of mismatch. - * - The trimmed length 5 and trimmed length 6 boundary, explicitly, on both sides, across - * letters and digits: {@code "abcde"} against {@code "abcdef"} and {@code "12345"} against - * {@code "123456"}. - * - {@code "12345"} and {@code "54321"}, the ordering case: the two differ and are both too - * short, so a rule that checked length before the confirmation would report the wrong cause - * while still rejecting. Status alone cannot catch that, which is why the message is asserted - * too. - * - {@code "abcde "}, whose raw length is 6 and trimmed length is 5, so the length check has to - * be applied to the trimmed value; and {@code " abcdef "}, which is accepted on its trimmed - * length and must reach the encoder untrimmed. - */ + /** 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, @@ -386,21 +359,7 @@ private void setupDataMap() { "\u00e9bcdef" ); - /** - * Each case is one candidate password and confirmation pair handed to - * {@code AuthController.registration}. - * - * Every enumerated value is crossed with every enumerated value, which yields both the - * accepting and the rejecting side of the claim, then a fixed-seed {@link Random} adds further - * pairs drawn from the same pool — a quarter of them equal pairs, so the accepting path keeps - * being exercised, and a quarter of them single-character perturbations, which is the near-miss - * shape that separates a raw-string comparison from a looser one. - * - * The enumerated cross product alone is 225 cases, comfortably past the hundred-case floor, and - * no property-based testing library is used. - * - * @return The generated cases. - */ + /** Full cross product of the values plus fixed-seed random pairs (equal, perturbed, mixed, null confirm). */ protected static Stream provideRetrofitPasswordPairs() { List cases = new ArrayList(); @@ -438,15 +397,7 @@ protected static Stream provideRetrofitPasswordPairs() { return cases.stream(); } - /** - * Alter one character of the supplied value, so the result differs from the input in exactly - * one position. A null or empty input becomes a short non-empty value, which still differs. - * - * @param value The value to perturb. - * @param random The fixed-seed source. - * - * @return The perturbed value, which never equals the input. - */ + /** 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"; @@ -461,20 +412,7 @@ private static String perturbRetrofitValue(String value, Random random) { return new String(characters); } - /** - * The password rule {@code AuthController.registration} carried inline before the retrofit, - * transcribed from the pre-retrofit source: missing first, then mismatch, then too short, with - * the message text of each branch verbatim. - * - * This is deliberately a transcription rather than a call to {@link PasswordValidator}: the - * claim is that the retrofitted handler agrees with the rule it replaced, and an oracle that - * called the replacement would assert nothing. - * - * @param password The candidate password, which may be null. - * @param confirm The confirmation value, which may be null. - * - * @return The pre-retrofit rejection message, or null where the pre-retrofit rule accepted. - */ + /** 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!"; @@ -491,31 +429,7 @@ private static String preRetrofitRejectionMessage(String password, String confir return null; } - /** - * Property 11: Registration retrofit preserves outcomes. - * - * Validates: Requirements 3.6, 3.7, 3.9 - * - * For any pair of candidate password and confirmation values, {@code AuthController.registration} - * after the retrofit returns the same accept-or-reject outcome, with the same message, that the - * pre-retrofit inline rule produced. - * - * Three things are asserted on every case: - * - * 1. Requirement 3.6: the decision the handler acts on is the shared validator's. The - * validator's verdict and message are checked against the transcribed pre-retrofit rule, so - * the two rules cannot drift apart silently. - * 2. Requirement 3.9: the handler's observable outcome — the {@code ApiStatus} and the response - * message — matches what the pre-retrofit rule produced. Both halves matter: the three - * rejection causes share the {@code ERROR} status, so status alone would not notice a change - * in the evaluation order, and the message is what distinguishes them. - * 3. Requirement 3.7: an accepted candidate reaches the encoder untrimmed, and a rejected one - * reaches nothing at all — no token is validated, no password is encoded, and no Account is - * created. - * - * @param password The candidate password under test. - * @param confirm The confirmation value under test. - */ + /** 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 { @@ -525,19 +439,16 @@ public void testRegistrationRetrofitPreservesOutcomes(String password, String co PasswordValidator.Result result = PasswordValidator.validate(password, confirm); - // Requirement 3.6: the shared validator reaches the same accept-or-reject verdict the - // pre-retrofit inline rule reached. + // Validator verdict matches the pre-retrofit rule. assertEquals( Boolean.valueOf(expectedMessage == null), Boolean.valueOf(PasswordValidator.Result.ACCEPTED.equals(result)), "Shared validator verdict for " + description); - // Requirement 3.6: and names the same cause, in the same words. messageFor returns null for - // ACCEPTED, which is the accepting case of the oracle. + // Same message; messageFor returns null for ACCEPTED. assertEquals(expectedMessage, PasswordValidator.messageFor(result), "Shared validator message for " + description); - // The firstName and lastName gate sits ahead of the password gate and is not under test, so - // it is satisfied on every case; the token is supplied so an accepted candidate can proceed. + // 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"); @@ -547,12 +458,10 @@ public void testRegistrationRetrofitPreservesOutcomes(String password, String co if (expectedMessage != null) { ApiResponse response = authController.registration(data, parameters); - // Requirement 3.9: the rejected outcome is preserved, status and message together. assertEquals(ApiStatus.ERROR, response.getMeta().getStatus(), "Status for rejected " + description); assertEquals(expectedMessage, response.getMeta().getMessage(), "Message for rejected " + description); - // Requirement 3.7: the rejection happens at the password gate, ahead of the token - // validation, so nothing downstream of that gate runs. + // Rejection happens before token validation. verifyNoInteractions(cryptoService); verify(vireoUserCredentialsService, never()).createUserFromRegistration(any(), any(), any(), any()); @@ -568,13 +477,11 @@ public void testRegistrationRetrofitPreservesOutcomes(String password, String co ApiResponse response = authController.registration(data, parameters); - // Requirement 3.9: the accepted outcome is preserved, status and message together. 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); - // Requirement 3.7: the accepted candidate reaches the encoder as submitted, padding and - // all, even though the length check that accepted it was applied to the trimmed value. + // 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 index 47909bfb31..55a6cd3c59 100644 --- a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java @@ -57,21 +57,9 @@ import edu.tamu.weaver.validation.utility.ValidationUtility; /** - * Server-side enforcement, targeting and leak-containment assertions for {@code POST /password/change}. + * Tests for {@code POST /password/change}: gating, principal targeting and leak containment. * - * Validates: Requirements 2.5, 2.6, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 6.4, 7.6, 10.6, 13.2, 13.3, 14.4, 16.9 - * - * One parameterized test carries Properties 12 (change arm), 13, 14 and 26 (change arm), because - * they share a single setup: a request against an Account under some availability state. Every case - * pins the same outcomes. The stored password is replaced exactly when the availability conjunction, - * the eligibility rule, the current-password check and the candidate validator all pass. A rejected - * case leaves the stored password byte-identical and produces no write, no notification, no encode - * and no email. Only the authenticated Account is ever written. No password or token value appears - * in the response or the log. - * - * BCrypt is real only where a case succeeds, since that is where the test asserts the persisted - * value verifies against the new password. Every other case uses a cheap prefix-based stand-in for - * the stored hash, which discriminates match from mismatch identically. + * 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 { @@ -94,11 +82,7 @@ public class PasswordControllerTest extends AbstractControllerTest { private static final String FAKE_HASH = FAKE_PREFIX + CURRENT_PASSWORD; - /** - * The raw Password_Login_Setting and {@code auth.pass.change.enabled} pairs: both on, each arm - * off on its own, both off, the trimmed and mixed-case accepting spellings, absent values, and - * the near-miss strings an administrator might expect to mean true. - */ + /** 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" }, @@ -132,10 +116,7 @@ public class PasswordControllerTest extends AbstractControllerTest { "CURRENTPASSWORD" }; - /** - * Candidate and confirmation pairs: accepted, the length 6 and length 5 boundary, mismatched, - * absent, whitespace-only, and an accepted value carrying surrounding whitespace. - */ + /** Candidate and confirmation pairs, including the length 5/6 boundary. */ private static final String[][] CANDIDATE_PAIRS = { { NEW_PASSWORD, NEW_PASSWORD }, { "abcdef", "abcdef" }, @@ -147,10 +128,7 @@ public class PasswordControllerTest extends AbstractControllerTest { { " padded ", " padded " } }; - /** - * Identifier key names an implementation might read out of the request body to pick a target - * Account. None is honored; the authenticated principal is the only source of the target. - */ + /** 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" }; @@ -163,11 +141,7 @@ public class PasswordControllerTest extends AbstractControllerTest { /** 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" }; - /** - * What a client might assert about its own rendering, carried in the request body. None of it - * is read: the server re-derives availability from the configuration store and eligibility from - * the stored Account fields on every request. - */ + /** 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"), @@ -222,7 +196,6 @@ public void setup() { @Test public void testChangePasswordRejectsACurrentPasswordMismatch() { - // Requirement 5 criterion 5: an authentication-failure result, nothing written. stubSettings("true", "true"); stubFakeCrypto(); @@ -239,7 +212,6 @@ public void testChangePasswordRejectsACurrentPasswordMismatch() { @Test public void testChangePasswordRejectsACandidateTheValidatorRejects() { - // Requirement 5 criterion 6: every rejection cause the shared validator reports. List rejectedCandidates = Arrays.asList( new String[] { null, null }, new String[] { " ", " " }, @@ -263,9 +235,7 @@ public void testChangePasswordRejectsACandidateTheValidatorRejects() { @Test public void testChangePasswordRequiresTheStudentRole() throws Exception { - // Requirement 5 criteria 4, 8: the baseline authenticated role, matching - // /user/settings/update. An unauthenticated or under-privileged caller is turned away by - // Spring Security before the handler body runs, which is what this annotation expresses. + // 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); @@ -280,37 +250,14 @@ public void testChangePasswordRequiresTheStudentRole() throws Exception { assertEquals(RequestMethod.POST, requestMapping.method()[0]); } - // Feature: user-password-reset, Property 12 (change arm): For any ineligible Account shape and - // any setting pair that resolves the capability unavailable, a Password_Change_Request is - // rejected, the stored password is left unchanged, and no email is sent. The reset and - // redemption arms join this property in tasks 12 and 13. - // - // Feature: user-password-reset, Property 13: For any combination of availability state, - // Account eligibility shape, current-password match or mismatch, and candidate password - // validity, the stored password is replaced exactly when all four conditions hold; and whenever - // it is replaced, the persisted value verifies against the submitted new password and does not - // verify against the previous password. - // - // Feature: user-password-reset, Property 14: For any Password_Change_Request body carrying - // arbitrary foreign Account identifiers, only the stored password of the authenticated Account - // is written. - // - // Feature: user-password-reset, Property 26 (change arm): For any password value and any token - // value, the /password/change response (status, message, payload) and the log output written - // while handling the request do not carry it. The password-changed notification arm is in - // CredentialNotificationServiceTest; the reset, redemption and email-change arms are added in - // later tasks, each as new scenarios in the case list and new artefacts in the check below. - // - // Validates: Requirements 2.5, 2.6, 5.1, 5.2, 5.3, 5.5, 5.6, 5.7, 6.4, 7.6, 7.8, 7.9, 9.7, 9.8, 10.6, 13.2, 13.3, 14.4 - // - // Every request carries the token entries and the client-asserted entries alongside the three - // honored keys, and the repository lookups by email, netid and id are all stubbed to return a - // foreign Account, so a handler that honored any of them would be observable. + // 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 { - // The four conditions of the conjunction, derived from the requirement text rather than - // from the handler, so the expectation is independent of the implementation's order. + // 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(); @@ -355,7 +302,7 @@ public void changeEnforcesItsGatesTargetsThePrincipalAndLeaksNothing(String pass 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 authenticated Account was written or notified, and nothing else was looked up. + // Only the principal is written or notified. verify(userRepo).update(user1); verifyNoMoreInteractions(userRepo); @@ -364,7 +311,7 @@ public void changeEnforcesItsGatesTargetsThePrincipalAndLeaksNothing(String pass } else { assertRejected(response); - // No credential material is produced on a rejected path, and no email leaves by any route. + // A rejection encodes nothing and sends no email. verify(cryptoService, never()).encodePassword(anyString()); verifyNoInteractions(mockEmailService); } @@ -375,20 +322,8 @@ public void changeEnforcesItsGatesTargetsThePrincipalAndLeaksNothing(String pass } /** - * The cases for the change arm. Every case is a nine-tuple of the raw Password_Login_Setting - * value, the raw {@code auth.pass.change.enabled} value, the stored-password shape, the netid, - * the supplied current password, the candidate, the confirmation, extra request body entries, - * and a label. - * - * Each block walks one dimension through its boundary values with the others held at a shape - * that succeeds on its own, so each is pinned as individually load-bearing. The both-failing - * block crosses the two server-side gates, so a handler that returned early on one gate and - * skipped the other is still caught. The foreign-identifier block runs accepted requests with - * identifier entries that point at another Account. The secret block runs unusual password - * values through the accepting path and the current-password-mismatch path. Client-asserted - * body entries are rotated across the first blocks. - * - * @return The generated cases. + * 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<>(); @@ -452,10 +387,7 @@ private static void addCase(List cases, String label, String password cases.add(Arguments.of(passwordLoginRaw, changeRaw, storedShape, netid, current, newPassword, confirm, claims, label + " claims=" + claims)); } - /** - * Neither a password value nor a token value may appear in the serialized response, its - * message, its payload, or any log line written while handling the request. - */ + /** 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); @@ -475,11 +407,7 @@ private void assertNoSecretLeaked(ApiResponse response, List log, String } } - /** - * Run the handler with the controller's logger lowered to ALL, since the test configuration - * pins org.tdl.vireo at ERROR and the handler logs its rejections at DEBUG, collecting what it - * writes into {@code lines}. The level is restored afterwards. - */ + /** 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(); @@ -506,18 +434,12 @@ private ApiResponse capturingLog(List lines, java.util.function.Supplier } } - /** - * The server's boolean resolution, restated from Requirement 1 criterion 13 rather than called - * through the service, so the property's expectation does not inherit a defect in it. - */ + /** 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"); } - /** - * The three outcomes every rejection case pins: INVALID, an unchanged stored password, and no - * notification dispatch. No write reaches the repository either. - */ + /** 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"); @@ -536,28 +458,19 @@ private Map request(String currentPassword, String newPassword, return data; } - /** - * Stub the two settings the change conjunction reads. Lenient, because the conjunction - * short-circuits on the Password_Login_Setting. - */ + /** 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); } - /** - * Route the mocked {@code CryptoService} onto the real encoder, so verification and encoding - * are the genuine operations. Used only where a case succeeds. - */ + /** 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))); } - /** - * A cheap stand-in for hashing: a stored value matches exactly when it is the prefix plus the - * supplied value, so a match and a mismatch are told apart without paying for BCrypt. - */ + /** 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)); diff --git a/src/test/java/org/tdl/vireo/controller/UserControllerTest.java b/src/test/java/org/tdl/vireo/controller/UserControllerTest.java index b0275037b2..362ce68af1 100644 --- a/src/test/java/org/tdl/vireo/controller/UserControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/UserControllerTest.java @@ -99,7 +99,6 @@ public void testCredentials() { @Test public void testCredentialsCarriesPasswordEligibleTrue() { - // Requirement 2 criterion 4: an Account with a non-whitespace password and a null netid is eligible. user1.setPassword("encodedpassword"); user1.setNetid(null); @@ -109,13 +108,12 @@ public void testCredentialsCarriesPasswordEligibleTrue() { Credentials got = (Credentials) response.getPayload().get("Credentials"); - // The map is declared Map, so the value is the String "true", never a JSON boolean. + // 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() { - // Requirement 2 criterion 2: a non-null netid makes the Account ineligible. user1.setPassword("encodedpassword"); user1.setNetid("netid1"); @@ -130,7 +128,6 @@ public void testCredentialsCarriesPasswordEligibleFalse() { @Test public void testCredentialsPasswordEligibleIsAlwaysAStringValue() { - // The entry is never a JSON boolean and never absent, whichever way the rule classifies. user1.setPassword(" "); user1.setNetid(null); @@ -145,8 +142,7 @@ public void testCredentialsPasswordEligibleIsAlwaysAStringValue() { @Test public void testCredentialsGuardsNullAllCredentials() { - // UserControllerTest constructs new Credentials() directly, whose no-argument constructor - // leaves allCredentials null, so the handler has to create and set the map. + // The no-arg Credentials constructor leaves allCredentials null, so the handler must create the map. credentials1.setAllCredentials(null); user1.setPassword("encodedpassword"); @@ -164,9 +160,7 @@ public void testCredentialsGuardsNullAllCredentials() { @Test public void testPasswordEligibleSerializesWithNoActiveView() throws Exception { - // Requirement 2 criterion 4: User.isPasswordEligible() carries no @JsonView, and with - // default-view-inclusion disabled an un-annotated property serializes only when no view - // is active. That is what confines the flag to the no-view listing endpoints. + // Un-annotated properties serialize only with no active view (default-view-inclusion is off). user1.setPassword("encodedpassword"); user1.setNetid(null); @@ -202,11 +196,7 @@ public void testPasswordEligibleSerializesFalseForAnIneligibleAccount() throws E assertFalse(payload.get("passwordEligible").asBoolean(), "an Account carrying a netid serializes false"); } - /** - * A mapper configured the way src/main/resources/application.yml configures the application - * mapper: spring.jackson.mapper.default-view-inclusion is false. The inherited objectMapper - * is a shared @Spy wired into controllers, so it is left alone here. - */ + /** 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); diff --git a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java index 8043b78137..d1ec25ae02 100644 --- a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java @@ -71,16 +71,8 @@ import ch.qos.logback.core.read.ListAppender; /** - * Absent-template and mail-failure cases for the password-changed notification. - * - * Validates: Requirements 6.6, 6.7, 14.1, 14.2, 14.4, 14.5, 15.10, 16.11 - * - * Both failure injections assert the same three things the requirements name: no send is attempted - * where none can succeed, the failure is recorded in the application log naming the Account and the - * notification, and no exception escapes, so the already-persisted password change stands. - * - * The log assertion attaches a Logback {@link ListAppender} to the service's own logger, since the - * project carries no existing log-capture helper and no new Maven dependency may be introduced. + * 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) @@ -109,12 +101,7 @@ public class CredentialNotificationServiceTest { @Mock private VireoEmailSender emailSender; - /** - * Declared for Property 23 only. The service under test holds no field of either type, so - * neither mock is wired into it, and that is precisely the point under assertion: a dispatch - * gated on a Password_Management_Setting or on the Password_Login_Setting would have to reach - * one of these collaborators, which {@code @InjectMocks} would then supply from here. - */ + // 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; @@ -147,8 +134,7 @@ public void setup() { serviceLogger = (Logger) LoggerFactory.getLogger(CredentialNotificationService.class); - // The test configuration pins org.tdl.vireo at ERROR, so the WARN records under assertion - // here are enabled for this logger only, for the duration of the test, and then restored. + // The test configuration pins org.tdl.vireo at ERROR; enable WARN for this logger only. originalLevel = serviceLogger.getLevel(); serviceLogger.setLevel(Level.WARN); @@ -163,13 +149,7 @@ public void teardown() { logAppender.stop(); } - /** - * An absent Email_Template produces a logged skip naming the template, no send, and no - * exception. - * - * The null result is what {@code resolveTemplate} is tested against: the notification must not - * reach {@code getSubject()} or {@code getMessage()} on a null row. - */ + /** 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); @@ -187,9 +167,7 @@ public void testNotifyPasswordChangedWithAbsentTemplate() { assertNoSensitiveValueLogged(log); } - /** - * {@code resolveTemplate} returns null and logs rather than throwing when no row is installed. - */ + /** {@code resolveTemplate} returns null and logs when no template is installed. */ @Test public void testResolveTemplateWithAbsentTemplate() { when(emailTemplateRepo.findByNameOverride(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE)).thenReturn(null); @@ -199,10 +177,7 @@ public void testResolveTemplateWithAbsentTemplate() { assertTrue(capturedLog().contains(CredentialNotificationService.PASSWORD_CHANGED_TEMPLATE), "The absence of the email template must be logged naming the template."); } - /** - * A mail transport failure is logged with the Account identifier and the notification, and no - * exception escapes, so the completed password change stands. - */ + /** 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)); @@ -223,12 +198,7 @@ public void testNotifyPasswordChangedWithMailFailure() throws MessagingException assertNoSensitiveValueLogged(log); } - /** - * Join every captured log message, so a single assertion can read across the whole record the - * notification wrote. - * - * @return The captured log messages. - */ + /** Joins all captured log messages. */ private String capturedLog() { List messages = new ArrayList(); @@ -239,21 +209,13 @@ private String capturedLog() { return String.join("\n", messages); } - /** - * Neither a password value nor a token value may appear anywhere in the log output. - * - * @param log The captured log 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); } - /* - * Task 6.4 — Property 23: Credential-change notification is always on, password-changed arm. - * - * The email-change arm is added in task 16, once the detection site on /user/update exists. - */ + // Always-on notification (password-changed arm). private static final long GENERATOR_SEED = 20250101L; @@ -261,23 +223,12 @@ private void assertNoSensitiveValueLogged(String log) { private static final String APPLICATION_TYPE = "application"; - /** - * The raw stored setting strings the generator draws from. Both the resolving and the - * non-resolving shapes are present, since the property holds across the whole domain and not - * merely across the two values an Administrator can select in the Password Management pane. - */ + /** 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 under test. - * - * The shape carries the two fields the Password_Eligibility_Rule reads, the - * Institutional_SSO affiliations it deliberately ignores, and a user settings map, so a single - * case can describe an Account the rule classifies ineligible, an Account provisioned through - * Institutional_SSO, and an Account carrying user settings that look like a suppression switch. - */ + /** One account shape: eligibility fields, SSO affiliations and user settings. */ private static final class AccountShape { private final String label; @@ -334,13 +285,7 @@ private static Map settings(String... keysAndValues) { return settings; } - /** - * The enumerated Account shapes. Every shape the design's Property 23 input domain names is - * present: an eligible Vireo-managed Account, an Account provisioned through Institutional_SSO, - * an Account with no stored password, an Account whose stored password is whitespace only, an - * Account carrying user settings that read like a suppression switch, and an Account whose - * {@code preferedEmail} setting names a different address. - */ + /** 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()), @@ -350,16 +295,7 @@ private static Map settings(String... keysAndValues) { new AccountShape("preferred-email-elsewhere", "account@tamu.edu", null, TEST_PASSWORD, affiliations("affiliate"), settings("preferedEmail", "somewhere.else@tamu.edu")) ); - /** - * Each case is one Account shape crossed with one combination of the four password settings. - * - * The enumerated cross product is every Account shape against every pairing of resolving and - * non-resolving values for {@code auth.pass.enabled}, {@code auth.pass.change.enabled} and - * {@code auth.pass.reset.enabled}; the randomized cases then vary all four settings over the - * wider raw-value domain, including the shapes that resolve to neither true nor false. - * - * @return The generated cases, well over one hundred of them. - */ + /** Every account shape crossed with the boolean setting combinations, plus seeded random cases. */ private static Stream provideAlwaysOnCases() { List cases = new ArrayList(); @@ -390,26 +326,7 @@ private static Stream provideAlwaysOnCases() { return cases.stream(); } - /** - * Property 23: Credential-change notification is always on. - * - * Validates: Requirements 12.5, 13.5, 13.6 - * - * For any Account shape — including an Account provisioned through Institutional_SSO and an - * Account the Password_Eligibility_Rule classifies ineligible — and for any combination of the - * four password settings, and for any user settings carried on the Account, the password-changed - * notification is dispatched exactly once to the Account_Email. - * - * Requirement 13 criterion 6 is what the two unwired collaborators pin. The dispatch reads no - * configuration value and consults no availability conjunction, so a later change that gated the - * notification on either would draw this test's stubbed values and fail the send assertion. - * - * @param shape The Account shape under test. - * @param enabledRaw The raw stored {@code auth.pass.enabled} value. - * @param changeRaw The raw stored {@code auth.pass.change.enabled} value. - * @param resetRaw The raw stored {@code auth.pass.reset.enabled} value. - * @param expiryRaw The raw stored {@code auth.pass.reset.expiryHours} value. - */ + /** 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 { @@ -428,28 +345,17 @@ public void testPasswordChangedNotificationIsAlwaysOn(AccountShape shape, String credentialNotificationService.notifyPasswordChanged(target); - // Requirements 12.5, 13.5: one dispatch, to the Account_Email, for every Account shape and - // every setting combination. The eligibility classification is recomputed here so the case - // list is demonstrably not confined to eligible Accounts. 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); - // Requirement 13.6: no configuration setting and no availability conjunction participates - // in the dispatch, so none of them can suppress it. verifyNoInteractions(configurationRepo); verifyNoInteractions(passwordFeatureAvailabilityService); } - /** - * Requirement 13.6: the service exposes no suppression switch of any kind. - * - * No declared field reaches the configuration store or the availability service, and no public - * method takes a flag a caller could set to skip the notification, so there is no request - * parameter the dispatch could be made to honour. - */ + /** The service holds no settings collaborator and no public method takes a suppression flag. */ @Test public void testNoSuppressionSwitchExists() { for (Field field : CredentialNotificationService.class.getDeclaredFields()) { @@ -483,35 +389,17 @@ public void testNoSuppressionSwitchExists() { assertTrue(found, "notifyPasswordChanged is declared on the notification service"); } - /** - * The resolution rule the availability service applies, recomputed here so a stubbed - * availability answer matches what the real service would have returned for the raw value. - * - * @param raw The raw stored value. - * - * @return The resolved value. - */ + /** 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"); } - /** - * Stub a raw stored setting value on the unwired configuration store. - * - * @param settingName The setting name. - * @param rawValue The raw stored value. - */ + /** 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); } - /** - * Stub the availability conjunctions on the unwired availability service. - * - * @param enabled The resolved Password_Login_Setting. - * @param change The resolved {@code auth.pass.change.enabled} value. - * @param reset The resolved {@code auth.pass.reset.enabled} value. - */ + /** 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); @@ -520,13 +408,7 @@ private void stubAvailability(boolean enabled, boolean change, boolean reset) { lenient().when(passwordFeatureAvailabilityService.isResetAvailable()).thenReturn(enabled && reset); } - /* - * Task 6.5 — packaged template content assertions for SYSTEM_Password_Changed.email. - * - * These are example assertions over the packaged classpath resource, read and split the same - * way SystemDataLoader.loadSystemEmailTemplate reads and splits it, so what is under assertion - * is the subject and the body an installed row would actually carry. - */ + // Packaged SYSTEM_Password_Changed.email assertions, split the way SystemDataLoader splits it. private static final String PASSWORD_CHANGED_RESOURCE = "/emails/SYSTEM_Password_Changed.email"; @@ -538,22 +420,13 @@ private void stubAvailability(boolean enabled, boolean change, boolean reset) { private static final String RESET_URL_PLACEHOLDER = "{RESET_URL}"; - /** - * Every shape a hyperlink could take in a plain-text template body. - */ + /** Shapes a hyperlink could take in a plain-text body. */ private static final List HYPERLINK_MARKERS = Arrays.asList("http://", "https://", "www.", "mailto:", "href", "
(Arrays.asList(CHANGE_TIME_PLACEHOLDER)), placeholders, "CHANGE_TIME is the only parameter the password-changed template body expands."); - // Requirement 13.2: the body states that the password changed without carrying a value. 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); } - /** - * Read the packaged template resource from the classpath. - * - * @return The raw resource content. - * - * @throws IOException If the packaged resource cannot be read. - */ + /** Reads the packaged template from the classpath. */ private String readPackagedPasswordChangedTemplate() throws IOException { InputStream stream = CredentialNotificationServiceTest.class.getResourceAsStream(PASSWORD_CHANGED_RESOURCE); @@ -648,24 +500,12 @@ private String readPackagedPasswordChangedTemplate() throws IOException { return content.toString(); } - /** - * Strip the comment lines the way {@code SystemDataLoader} strips them. - * - * @param raw The raw resource content. - * - * @return The content the loader parses. - */ + /** Strips comment lines the way {@code SystemDataLoader} does. */ private String strippedOfComments(String raw) { return raw.replaceAll("\\s*#.*[\\n\\r]{1}", ""); } - /** - * Extract the subject the loader would extract. - * - * @param raw The raw resource content. - * - * @return The template subject. - */ + /** Extracts the subject the loader would extract. */ private String packagedSubject(String raw) { Matcher subjectMatcher = Pattern.compile("\\s*Subject:(.*)[\\n\\r]{1}").matcher(strippedOfComments(raw)); @@ -674,13 +514,7 @@ private String packagedSubject(String raw) { return subjectMatcher.group(1).trim(); } - /** - * Extract the body the loader would extract: everything after the Subject line. - * - * @param raw The raw resource content. - * - * @return The template body. - */ + /** Extracts the body the loader would extract: everything after the Subject line. */ private String packagedBody(String raw) { String data = strippedOfComments(raw); @@ -695,22 +529,13 @@ private String packagedBody(String raw) { return data.substring(index); } - /* - * Task 7.6 — Property 26: Leak containment across every outbound artefact, the - * password-changed-notification arm. - */ + // 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" }; - /** - * Each case is a scenario and the secret material the Account carries. The enumerated cases - * cross every scenario with every secret shape; the fixed-seed random cases add generated - * secrets, 21 enumerated plus 100 random. - * - * @return The generated cases. - */ + /** Every scenario crossed with every secret shape, plus 100 seeded random secrets. */ private static Stream provideLeakContainmentCases() { List cases = new ArrayList(); @@ -729,17 +554,7 @@ private static Stream provideLeakContainmentCases() { return cases.stream(); } - /** - * Property 26: Leak containment, password-changed-notification arm. - * - * Validates: Requirements 6.4, 13.2, 13.3, 14.4 - * - * For any password value and token value held by the Account, the dispatched subject and body - * and every log record written by the notification contain neither. - * - * @param scenario The dispatch outcome under test. - * @param base The secret material the Account's password and token are derived from. - */ + /** 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 { @@ -749,7 +564,7 @@ public void testPasswordChangedNotificationLeakContainment(String scenario, Stri user.setPassword(password); user.setSettings(new TreeMap(settings("resetToken", token))); - // The real packaged subject and body, so the artefact under assertion is the one shipped. + // Use the packaged subject and body so the shipped artefact is what is asserted. String raw = readPackagedPasswordChangedTemplate(); if ("absent-template".equals(scenario)) { diff --git a/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java b/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java index 756a1dd87d..bda86fca1c 100644 --- a/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/PasswordFeatureAvailabilityServiceTest.java @@ -40,14 +40,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; /** - * Property 6: Setting resolution and availability conjunction. - * - * Validates: Requirements 1.13, 1.14, 1.16, 1.18, 1.19 - * - * The property is one {@link ParameterizedTest} fed by an {@link MethodSource} generator producing - * well over one hundred cases, built from the enumerated boundary values crossed with one another - * and padded from a fixed-seed {@link Random}. No property-based testing library is used and no new - * Maven dependency is introduced. + * 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) @@ -59,11 +53,7 @@ public class PasswordFeatureAvailabilityServiceTest { private static final int RANDOM_CASE_COUNT = 48; - /** - * The enumerated raw setting strings. Every shape the design's Property 6 input domain names is - * present: null, {@code "true"}, {@code "TRUE"}, {@code " true "}, {@code "False"}, {@code "1"}, - * {@code "yes"}, empty and whitespace-only. - */ + /** Boundary raw setting strings. */ private static final List RAW_VALUES = Arrays.asList( null, "", @@ -92,17 +82,7 @@ public class PasswordFeatureAvailabilityServiceTest { @InjectMocks private PasswordFeatureAvailabilityService passwordFeatureAvailabilityService; - /** - * Each case is a triple of raw stored strings for the Password_Login_Setting, - * {@code auth.pass.change.enabled} and {@code auth.pass.reset.enabled}. - * - * The enumerated cross product pins every pairing of the boundary values for the - * Password_Login_Setting against a capability setting; the random cases vary all three - * independently, which is what covers the asymmetric pairings where one capability is enabled - * and the other is not. - * - * @return The generated cases. - */ + /** Raw triples (enabled, change, reset); the random cases cover asymmetric change/reset pairings. */ private static Stream provideRawSettingTriples() { List cases = new ArrayList(); @@ -121,13 +101,7 @@ private static Stream provideRawSettingTriples() { return cases.stream(); } - /** - * Draw either one of the enumerated boundary values or a junk string of random characters. - * - * @param random The fixed-seed source. - * - * @return The drawn raw value. - */ + /** 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())); @@ -144,14 +118,7 @@ private static String randomRawValue(Random random) { return junk.toString(); } - /** - * The independently computed resolution rule: trim, then compare against {@code "true"} with - * letter case ignored. An absent value resolves false. - * - * @param raw The raw stored value. - * - * @return The expected resolved value. - */ + /** Expected resolution: trimmed, case-insensitive {@code "true"}; null is false. */ private static boolean expectedResolution(String raw) { return raw != null && raw.trim().equalsIgnoreCase("true"); } @@ -167,23 +134,16 @@ public void testSettingResolutionAndAvailabilityConjunction(String enabledRaw, S boolean expectedChange = expectedResolution(changeRaw); boolean expectedReset = expectedResolution(resetRaw); - // Requirements 1.13, 1.14: resolution is trim plus case-insensitive comparison, and an - // absent or unrecognised value resolves false. 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"); - // Requirement 1.18: change is available exactly under its conjunction. assertEquals(expectedEnabled && expectedChange, passwordFeatureAvailabilityService.isChangeAvailable(), "Availability of self-service password change"); - // Requirement 1.19: reset is available exactly under its conjunction. assertEquals(expectedEnabled && expectedReset, passwordFeatureAvailabilityService.isResetAvailable(), "Availability of administrator-initiated reset"); } - /** - * Requirement 1.16: an absent Password_Login_Setting leaves both capabilities unavailable, for - * every value of the two capability settings. - */ + /** An absent login setting makes both capabilities unavailable. */ @Test public void testAbsentPasswordLoginSettingLeavesBothCapabilitiesUnavailable() { stub(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, null); @@ -194,13 +154,7 @@ public void testAbsentPasswordLoginSettingLeavesBothCapabilitiesUnavailable() { assertFalse(passwordFeatureAvailabilityService.isResetAvailable(), "Reset is unavailable when the Password_Login_Setting is absent"); } - /** - * The enumerated raw expiry strings. Every boundary the design's Property 7 input domain names - * is present: absent, empty, whitespace-only, the rejected lower neighbours {@code "0"} and - * {@code "-1"}, the accepted lower bound {@code "1"}, the seeded default {@code "24"}, the - * accepted upper bound {@link Integer#MAX_VALUE}, the rejected upper neighbour - * {@code "2147483648"}, non-numeric shapes, and a whitespace-padded valid value. - */ + /** Boundary raw expiry strings. */ private static final List RAW_EXPIRY_VALUES = Arrays.asList( null, "", @@ -226,14 +180,7 @@ public void testAbsentPasswordLoginSettingLeavesBothCapabilitiesUnavailable() { private static final int RANDOM_EXPIRY_CASE_COUNT = 96; - /** - * Each case is one raw stored string for {@code auth.pass.reset.expiryHours}. - * - * The enumerated boundary values are crossed with randomized valid and invalid draws from a - * fixed-seed {@link Random}, giving well over one hundred cases in total. - * - * @return The generated cases. - */ + /** Boundary expiry values plus seeded random draws. */ private static Stream provideRawExpiryValues() { List cases = new ArrayList(); @@ -250,15 +197,7 @@ private static Stream provideRawExpiryValues() { return cases.stream(); } - /** - * Draw either an enumerated boundary value, a randomized valid value in 1 to - * {@link Integer#MAX_VALUE}, a randomized rejected integer at or below zero, or a randomized - * non-numeric junk string. - * - * @param random The fixed-seed source. - * - * @return The drawn raw value. - */ + /** 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: @@ -280,14 +219,7 @@ private static String randomRawExpiryValue(Random random) { } } - /** - * The independently computed resolution rule: trim, parse as an integer, and accept only a - * value in 1 to {@link Integer#MAX_VALUE} inclusive. Every other input yields 24. - * - * @param raw The raw stored value. - * - * @return The expected resolved expiry in hours. - */ + /** 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; @@ -308,17 +240,7 @@ private static int expectedExpiry(String raw) { return parsed; } - /** - * Property 7: Expiry value resolution. - * - * Validates: Requirements 1.8 - * - * A value parsing as an integer in 1 to {@link Integer#MAX_VALUE} inclusive resolves to itself; - * every other value resolves to 24. On every input, rejected or accepted, the configuration - * store sees the single read and no write whatsoever, so the stored value is left unchanged. - * - * @param raw The raw stored value under test. - */ + /** 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) { @@ -328,8 +250,6 @@ public void testExpiryValueResolution(String raw) { assertEquals(expected, passwordFeatureAvailabilityService.getResetExpiryHours(), "Resolution of auth.pass.reset.expiryHours for raw value '" + raw + "'"); - // Requirement 1.8: the stored value is left unchanged. The resolution reads the setting - // once and performs no write-back of the fallback value. verify(configurationRepo, times(1)).getValueByNameAndType(eq(ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS), eq(APPLICATION_TYPE)); verify(configurationRepo, never()).create(anyString(), anyString(), anyString()); @@ -346,30 +266,18 @@ private void stub(String settingName, String rawValue) { lenient().when(configurationRepo.getValueByNameAndType(eq(settingName), eq(APPLICATION_TYPE))).thenReturn(rawValue); } - /** - * Stub a setting against a mutable holder, so the stored value can be flipped between requests - * without re-stubbing. - * - * @param settingName The setting name. - * @param holder The single-element holder carrying the current raw stored value. - */ + /** 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]); } - /* - * Task 1.6 — seeding, constant, and per-request resolution assertions. - */ + // 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 the values Requirement 1 criteria 1, 2, 3 and 9 state. - * - * @return The generated cases. - */ + /** The four seeded settings and their expected default values. */ private static Stream provideSeededDefaults() { return Stream.of( Arguments.of(ConfigurationName.APPLICATION_AUTH_PASS_ENABLED, "true"), @@ -379,20 +287,12 @@ private static Stream provideSeededDefaults() { ); } - /** - * Read the Default_Settings_Seed exactly as {@code DefaultSettingsService} reads it. - * - * @return The parsed seed. - * - * @throws IOException If the resource cannot be read. - */ + /** 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 carries a pre-existing multi-line string value, so raw control characters - // inside a string are tolerated here exactly as the application's reader tolerates - // them. Nothing about the seed file is changed by this test. + // 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); @@ -401,16 +301,7 @@ private static JsonNode readSystemDefaults() throws IOException { } } - /** - * Resolve a seeded value the way {@code DefaultSettingsService.init} flattens the seed: the - * entries under a top-level key are single-field objects, read through {@code asText()}. - * - * @param defaults The parsed seed. - * @param type The top-level key, which is the configuration type. - * @param name The setting name. - * - * @return The seeded value, or null when the setting is absent under that type. - */ + /** 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); @@ -427,18 +318,7 @@ private static String seededValue(JsonNode defaults, String type, String name) { return null; } - /** - * Requirements 1.1, 1.2, 1.3, 1.9, 1.10, 1.15: each of the four settings is seeded under the - * {@code application} top-level key with the stated value, and under no other type. - * - * Seeding under the wrong type is invisible to {@code getSettingByNameAndType}, which filters - * {@code getSettingsByType(type)}, so the type is asserted and not merely the presence. - * - * @param settingName The setting name under test. - * @param expectedValue The value the requirement states. - * - * @throws IOException If the seed cannot be read. - */ + /** 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 { @@ -449,10 +329,7 @@ public void testSettingIsSeededUnderTheApplicationKey(String settingName, String assertNull(seededValue(defaults, SHIBBOLETH_TYPE, settingName), "'" + settingName + "' is not seeded under the shibboleth key"); } - /** - * Requirement 1.4: each Password_Management_Setting is named in {@code ConfigurationName}, and - * the already-declared constant for the Password_Login_Setting is reused unchanged. - */ + /** 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"); @@ -461,15 +338,7 @@ public void testConfigurationNameConstants() { assertEquals("auth.pass.reset.expiryHours", ConfigurationName.APPLICATION_AUTH_PASS_RESET_EXPIRY_HOURS, "The auth.pass.reset.expiryHours constant"); } - /** - * Requirement 1.5: every setting is resolved through - * {@code configurationRepo.getValueByNameAndType(name, "application")} within the handling of - * each request, and no resolved value is retained across requests. - * - * A value cached at startup or held in a static field would answer the second and later - * requests with no read at all, so the read count scaling with the request count is what - * separates conformance from a cache. - */ + /** 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"); @@ -494,13 +363,7 @@ public void testEverySettingIsResolvedOnEveryRequest() { verifyNoMoreInteractions(configurationRepo); } - /** - * Requirements 1.5, 1.6: a stored value that changes between two requests governs the second - * request, with no application restart. - * - * Each of the three booleans is flipped on its own, so a service that happened to carry one - * value over while re-reading the others cannot pass. - */ + /** A changed stored value governs the next request; each boolean is flipped independently. */ @Test public void testFlippedStoredValueGovernsTheNextRequest() { String[] enabled = { "true" }; @@ -532,10 +395,7 @@ public void testFlippedStoredValueGovernsTheNextRequest() { assertFalse(passwordFeatureAvailabilityService.isResetAvailable(), "The flipped Password_Login_Setting governs the next request for reset"); } - /** - * Requirements 1.5, 1.6: the expiry value is likewise resolved per request, so an Administrator - * save of a new expiry governs the next evaluation. - */ + /** A changed expiry value governs the next request. */ @Test public void testFlippedExpiryValueGovernsTheNextRequest() { String[] expiry = { "24" }; diff --git a/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java b/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java index 840b576ea5..a4546094cd 100644 --- a/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java +++ b/src/test/java/org/tdl/vireo/utility/PasswordEligibilityRuleTest.java @@ -19,34 +19,15 @@ import org.tdl.vireo.model.User; /** - * Property 5: Eligibility predicate. - * - * Validates: Requirements 2.1, 2.2, 2.3, 2.8, 16.8 - * - * The property is one {@link ParameterizedTest} fed by an {@link MethodSource} generator producing - * well over one hundred cases, built from the cross product of the enumerated stored - * {@code User.password} values, the enumerated stored {@code User.netid} values, and the enumerated - * {@code User.shibbolethAffiliations} values. No property-based testing library is used and no new - * Maven dependency is introduced. - * - * {@link PasswordEligibilityRule} is static and stateless, so this test starts no Spring context - * and wires no mock. + * 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 { - /** - * The enumerated stored password values. - * - * The blank shapes are enumerated separately from the absent one because Requirement 2 - * criterion 2 routes null, empty, and whitespace-only alike to ineligible, and a rule written - * against {@code isEmpty} rather than a trim would separate them. The non-breaking space is - * included deliberately: {@code String.trim} removes characters at or below U+0020 only, so - * U+00A0 is a non-whitespace character under the rule as stated and a password composed of one - * is eligible. - */ + // 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: ineligible under criterion 2. + // Absent and blank. null, "", " ", @@ -54,7 +35,7 @@ public class PasswordEligibilityRuleTest { "\t\n", "\r\n ", - // Non-blank: the eligible side of criterion 1, when the netid is null. + // Non-blank. "$2a$10$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123", "x", "abc", @@ -63,20 +44,12 @@ public class PasswordEligibilityRuleTest { "\u00a0" ); - /** - * The enumerated stored netid values. - * - * The blank values are load-bearing: criterion 2 states that a non-null netid makes an Account - * ineligible including an empty or whitespace-only netid, which a rule written as a - * blank test rather than a null test would wrongly treat as eligible. The blank netid is - * reachable in practice, because the account-creation branch of - * {@code updateUserByCredentials} sets the netid with no emptiness guard. - */ + // 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 under criterion 1. + // The only eligible netid. null, - // Non-null, so ineligible under criterion 2, blank or not. + // Non-null, so ineligible. "", " ", "\t", @@ -85,14 +58,7 @@ public class PasswordEligibilityRuleTest { "a-very-long-institutional-net-identifier-0123456789-0123456789" ); - /** - * The enumerated {@code User.shibbolethAffiliations} values, varied across the case list while - * the expected result never changes. That invariance is what pins Requirement 2 criterion 8: - * the rule must consult this field in no part of the classification. - * - * The field is a {@code Set}, and the set the {@link User} constructor installs is a - * {@link TreeSet}, which holds no null element, so every element here is non-null. - */ + // 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(), @@ -101,13 +67,6 @@ public class PasswordEligibilityRuleTest { affiliations("alum", "faculty", "member", "staff", "student") ); - /** - * Build an affiliation set in the shape the {@link User} constructor installs. - * - * @param values The affiliation values. - * - * @return The set. - */ private static Set affiliations(String... values) { Set set = new TreeSet(); @@ -116,16 +75,7 @@ private static Set affiliations(String... values) { return set; } - /** - * Each case is one stored password value crossed with one stored netid value crossed with one - * affiliation value. - * - * The full cross product is generated rather than a sample, because the property is an "exactly - * when" over the combination: only the non-blank-password-and-null-netid cells are expected - * eligible, and every other cell is expected ineligible. - * - * @return The generated cases. - */ + // The full cross product, since eligibility is an "exactly when" over the combination. private static Stream providePasswordNetidAndAffiliationCombinations() { List cases = new ArrayList(); @@ -140,32 +90,11 @@ private static Stream providePasswordNetidAndAffiliationCombinations( return cases.stream(); } - /** - * The independently computed predicate, written straight from Requirement 2 criterion 1: the - * password holds at least one non-whitespace character and the netid is null. - * - * The affiliation value is deliberately not a parameter of this computation, which is the - * statement of Requirement 2 criterion 8 in code. - * - * @param password The stored password value, which may be null. - * @param netid The stored netid value, which may be null. - * - * @return The expected classification. - */ + // Affiliations are deliberately not a parameter. private static boolean expectedEligible(String password, String netid) { return netid == null && password != null && password.trim().length() > 0; } - /** - * Construct an Account carrying the supplied stored field values, leaving every other field as - * the constructor set it. - * - * @param password The stored password value. - * @param netid The stored netid value. - * @param affiliation The affiliation value, which may be null. - * - * @return The Account. - */ private static User accountOf(String password, String netid, Set affiliation) { User user = new User(); @@ -176,23 +105,7 @@ private static User accountOf(String password, String netid, Set affilia return user; } - /** - * Property 5: Eligibility predicate. - * - * Validates: Requirements 2.1, 2.2, 2.3, 2.8, 16.8 - * - * The rule returns eligible exactly when the stored password holds at least one non-whitespace - * character and the stored netid is null, and ineligible for every other combination. - * - * The same case drives both overloads, so the field-level form and the Account form cannot - * drift apart, and both are compared against the independently computed predicate rather than - * against each other alone — two forms that agree with each other and disagree with the - * requirement would otherwise pass. - * - * @param password The stored password value under test. - * @param netid The stored netid value under test. - * @param affiliation The affiliation value under test. - */ + // 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) { @@ -200,50 +113,28 @@ public void testEligibilityPredicate(String password, String netid, Set String description = "Eligibility for password '" + password + "', netid '" + netid + "', affiliations " + affiliation; - // Requirements 2.1, 2.2, 2.3: the Account form, classified from the stored fields at - // evaluation time. assertEquals( Boolean.valueOf(expected), Boolean.valueOf(PasswordEligibilityRule.isEligible(accountOf(password, netid, affiliation))), description + " through the Account form"); - // Requirements 2.1, 2.2, 2.3: the field-level form, driven by the same case so the two - // forms cannot drift. assertEquals( Boolean.valueOf(expected), Boolean.valueOf(PasswordEligibilityRule.isEligible(password, netid)), description + " through the field-level form"); - // Requirement 2.3: no tagging and no migration, so the same stored values classify the same - // way on a repeat evaluation and across two separately constructed Accounts. + // 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"); } - /** - * Property 5, the invariance half, stated as its own assertion rather than left to fall out of - * the case list. - * - * Validates: Requirements 2.8, 16.8 - * - * For one password and netid pair, every enumerated affiliation value is classified, and all of - * the results are asserted equal to one another and equal to the field-level result — which - * cannot see the field at all, because the field is not among its arguments. Varying the field - * while the result is pinned to the value produced without the field is what makes a rule that - * reads {@code User.shibbolethAffiliations} fail. - * - * @param password The stored password value under test. - * @param netid The stored netid value under test. - * @param affiliation Ignored here: this test varies the affiliation itself. The parameter keeps - * the generator shared with the predicate test, so the two cannot drift. - */ + // 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 result computed with no affiliation value in play at all: the field-level overload - // takes the password and the netid only. + // The field-level overload cannot see affiliations, so it is the baseline. boolean withoutAffiliations = PasswordEligibilityRule.isEligible(password, netid); Set observed = new LinkedHashSet(); @@ -253,37 +144,25 @@ public void testAffiliationsAreNotConsulted(String password, String netid, Set WHITESPACE_RUNS = Arrays.asList( "", " ", @@ -58,27 +45,19 @@ public class PasswordValidatorTest { " " ); - /** - * The enumerated candidate cores, before any whitespace padding is applied. - * - * The trimmed length 5 and trimmed length 6 boundary is enumerated explicitly across several - * character classes, so the rejected side and the accepted side of the boundary are each pinned - * for letters, digits, symbols, mixed case, and non-ASCII characters. Varying the character - * class while the expected result depends on the trimmed length alone is what pins Requirement - * 3 criterion 8: no character-class constraint exists. - */ + // 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, every length from one to four. + // Below the boundary. "a", "ab", "abc", "abcd", - // The rejected side of the boundary: trimmed length 5, across character classes. + // Trimmed length 5: rejected. "abcde", "ABCDE", "12345", @@ -86,7 +65,7 @@ public class PasswordValidatorTest { "aB3$x", "\u00e9\u00e8\u00ea\u00eb\u00ec", - // The accepted side of the boundary: trimmed length 6, across character classes. + // Trimmed length 6: accepted. "abcdef", "ABCDEF", "123456", @@ -94,29 +73,19 @@ public class PasswordValidatorTest { "aB3$x.", "\u00e9\u00e8\u00ea\u00eb\u00ec\u00ed", - // Comfortably above the boundary. + // Above the boundary. "abcdefg", "1234567890", "correct horse battery staple", "\u4e2d\u6587\u5bc6\u7801\u5f88\u5f3a\u5927", - // Interior whitespace, which trimming does not remove, so these clear the boundary on - // their trimmed length. + // Interior whitespace is not trimmed, so these count at full length. "a b c", "a b cd", "a\tb\tc\td" ); - /** - * Each case is one candidate password string. - * - * The enumerated cores are crossed with every whitespace padding shape on each side, which - * produces the pairs that separate a trimmed-length rule from an untrimmed-length one: a - * five-character core padded to eleven characters must still be rejected, and a six-character - * core padded on both sides must still be accepted. - * - * @return The generated cases. - */ + // 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(); @@ -138,7 +107,6 @@ private static Stream provideCandidates() { } } - // Whitespace-only candidates, in their own right. candidates.addAll(WHITESPACE_RUNS); Random random = new Random(GENERATOR_SEED); @@ -160,15 +128,7 @@ private static Stream provideCandidates() { return cases.stream(); } - /** - * Draw a candidate of a random length drawn from zero through ten — so the boundary lengths - * five and six are both reachable — built from a random character class and wrapped in random - * whitespace padding. - * - * @param random The fixed-seed source. - * - * @return The drawn candidate. - */ + // 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); @@ -200,14 +160,7 @@ private static String randomCandidate(Random random) { return leading + core.toString() + trailing; } - /** - * The independently computed acceptance rule, written straight from Requirement 3 criteria 1, - * 2 and 3: trim, then decide on the trimmed length alone. - * - * @param candidate The candidate password, which may be null. - * - * @return The expected decision. - */ + // Independent oracle: trim, then decide on trimmed length alone. private static Result expectedResult(String candidate) { if (candidate == null) { return Result.MISSING; @@ -226,24 +179,7 @@ private static Result expectedResult(String candidate) { return Result.ACCEPTED; } - /** - * Property 8: Shared validator decision. - * - * Validates: Requirements 3.1, 3.2, 3.3, 3.8 - * - * The validator reports {@code ACCEPTED} exactly when the candidate holds at least one - * non-whitespace character and the trimmed length is 6 or greater; reports {@code MISSING} when - * the candidate is absent or whitespace-only; and reports {@code TOO_SHORT} when the trimmed - * length is below 6. - * - * The decision is read three ways on every case, so no single reading can carry the property on - * its own: the single-argument overload, the two-argument overload fed a matching confirmation - * — which must agree, since a matching confirmation removes the only cause the two-argument - * form adds — and a repeat call, which must agree with the first because no reuse-history state - * exists (Requirement 3 criterion 8). - * - * @param candidate The candidate password under test. - */ + // 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) { @@ -251,50 +187,38 @@ public void testSharedValidatorDecision(String candidate) { String description = "Decision for candidate '" + candidate + "'"; - // Requirements 3.1, 3.2, 3.3: the decision rests on the trimmed length alone. assertEquals(expected, PasswordValidator.validate(candidate), description); - // Requirement 3.8: the minimum is the only constraint, declared as 6, so the expectation - // above and the constant cannot drift apart. + // Ties the oracle's literal 6 to the declared constant. assertEquals(6, PasswordValidator.MINIMUM_TRIMMED_LENGTH, "The declared minimum trimmed length"); - // Requirement 3.7: a matching confirmation removes the only rejection cause the - // two-argument overload adds, so the two overloads must agree on every candidate. A null - // candidate is MISSING before the comparison is reached either way. + // A matching confirmation adds no rejection cause, so both overloads must agree. assertEquals(expected, PasswordValidator.validate(candidate, candidate), description + " through the confirming overload"); - // Requirement 3.8: no reuse-history constraint exists, so the same candidate decided twice - // decides the same way. + // No reuse-history state, so a repeat call decides the same way. assertEquals(expected, PasswordValidator.validate(candidate), description + " on a repeat decision"); } - /** - * The enumerated candidate and confirmation values for Property 9, crossed with themselves. - * - * The list is chosen so the cross product contains the pairs that separate a raw-string - * comparison from any looser one: pairs differing only in letter case, pairs differing only in - * leading or trailing whitespace, pairs differing only in the kind of trailing whitespace, and - * the absent and whitespace-only values on either side. - */ + // 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, on either side of the pair. + // Absent and whitespace-only. null, "", " ", " ", "\t", - // Below and at the boundary, so a mismatch and a too-short cause can both be in play. + // Below and at the boundary. "abcde", "abcde ", "abcdef", - // Letter-case-only differences from "abcdef". + // Case-only differences from "abcdef". "ABCDEF", "Abcdef", "abcdeF", - // Surrounding-whitespace-only differences from "abcdef". + // Whitespace-only differences from "abcdef". " abcdef", "abcdef ", " abcdef ", @@ -308,17 +232,7 @@ public void testSharedValidatorDecision(String candidate) { "\u00e9bcdef" ); - /** - * Each case is one candidate and confirmation pair. - * - * Every enumerated value is crossed with every enumerated value, which yields the equal pairs - * and the differing pairs together — the property is an "exactly when", so both sides have to - * be generated. A fixed-seed {@link Random} then adds pairs drawn from the same value pool, - * including pairs built by perturbing a drawn value in a single character, which is the - * near-miss shape a comparison looser than equality would let through. - * - * @return The generated cases. - */ + // Full cross product of the values, plus seeded random pairs including single-character near-misses. private static Stream provideConfirmationPairs() { List cases = new ArrayList(); @@ -337,7 +251,7 @@ private static Stream provideConfirmationPairs() { switch (random.nextInt(4)) { case 0: - // The same raw value, so the accepting side of the property is drawn too. + // Same raw value, so the accepting side is drawn too. confirmation = candidate; break; case 1: @@ -357,15 +271,7 @@ private static Stream provideConfirmationPairs() { return cases.stream(); } - /** - * Alter one character of the supplied value, or append one when the value is empty, so the - * result differs from the input in exactly one position. - * - * @param value The value to perturb. - * @param random The fixed-seed source. - * - * @return The perturbed value, which never equals the input. - */ + // 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"; @@ -380,15 +286,7 @@ private static String perturb(String value, Random random) { return new String(characters); } - /** - * The independently computed decision for a pair, written straight from Requirement 3 criteria - * 1 through 4 in the order the design fixes: missing, then mismatch, then too short. - * - * @param candidate The candidate password, which may be null. - * @param confirmation The confirmation value, which may be null. - * - * @return The expected decision. - */ + // 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; @@ -405,23 +303,7 @@ private static Result expectedResult(String candidate, String confirmation) { return Result.ACCEPTED; } - /** - * Property 9: Confirmation mismatch. - * - * Validates: Requirements 3.4 - * - * The validator reports {@code MISMATCH} exactly when the candidate is present and the two raw - * strings differ — including when they differ only in letter case, or only in surrounding - * whitespace. The present qualifier is the evaluation order the design fixes: an absent or - * whitespace-only candidate is {@code MISSING} before the comparison is reached, so the - * mismatch claim is scoped to the candidates that get as far as being compared. - * - * Comparison is on the raw values, not the trimmed ones, which is why a candidate padded with - * whitespace against its unpadded confirmation is a mismatch rather than an acceptance. - * - * @param candidate The candidate password under test. - * @param confirmation The confirmation value under test. - */ + // 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) { @@ -431,42 +313,30 @@ public void testConfirmationMismatch(String candidate, String confirmation) { Result actual = PasswordValidator.validate(candidate, confirmation); - // Requirement 3.4: the mismatch cause, in its place in the evaluation order. assertEquals(expected, actual, description); boolean candidatePresent = candidate != null && candidate.trim().length() > 0; - // Requirement 3.4, as the "exactly when" it is stated as: among the candidates that reach - // the comparison, MISMATCH is reported precisely for the pairs whose raw strings differ. assertEquals( Boolean.valueOf(candidatePresent && !candidate.equals(confirmation)), Boolean.valueOf(Result.MISMATCH.equals(actual)), description + " reported as a mismatch"); - // Requirement 3.4: a mismatch is a rejection, and it is reported as the mismatch cause - // rather than folded into another one. if (Result.MISMATCH.equals(actual)) { assertEquals("The passwords do not match!", PasswordValidator.messageFor(actual), description + " message"); } } - /** - * The candidate cores used for Property 10, all of them carrying at least one non-whitespace - * character so padding them produces a meaningful untrimmed-against-trimmed distinction. - * - * Both sides of the boundary are present: cores whose trimmed length is below 6, which must be - * rejected however much whitespace surrounds them, and cores whose trimmed length is 6 or - * greater, which must be accepted and stored with their padding intact. - */ + // 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 on the trimmed value. + // Below the boundary. "a", "abc", "abcde", "12345", "!@#$%", - // At and above the boundary on the trimmed value. + // At and above the boundary. "abcdef", "ABCDEF", "123456", @@ -478,11 +348,7 @@ public void testConfirmationMismatch(String candidate, String confirmation) { "\u4e2d\u6587\u5bc6\u7801\u5f88\u5f3a" ); - /** - * The whitespace runs padded around a core for Property 10. The empty run is deliberately - * absent on its own account — it is still reachable, because each core is also emitted - * unpadded — so that every generated padded case genuinely differs from its trimmed form. - */ + // 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( " ", " ", @@ -493,16 +359,7 @@ public void testConfirmationMismatch(String candidate, String confirmation) { " " ); - /** - * Each case is one candidate password, most of them padded so the untrimmed value and the - * trimmed value differ. - * - * Every core is crossed with every padding run on the leading side, the trailing side, and both - * sides at once, which is what produces the shapes that separate storing the untrimmed value - * from storing the trimmed one. A fixed-seed {@link Random} then adds further padded draws. - * - * @return The generated cases. - */ + // Each core padded leading, trailing and both sides, plus seeded random padded draws. private static Stream provideStorageCandidates() { Set candidates = new LinkedHashSet(); @@ -536,14 +393,7 @@ private static Stream provideStorageCandidates() { return cases.stream(); } - /** - * A stand-in for the password encoder, recording the exact value it is handed so the stored - * value can be compared against the submitted one by identity as well as by equality. - * - * The encoding itself is irrelevant to this property — the claim is about which string reaches - * the encoder — so a recording stand-in is used rather than a real BCrypt encoder, which would - * add seconds per case for nothing. - */ + // 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; @@ -559,17 +409,7 @@ private String encode(String raw) { } - /** - * The caller shape the design fixes for every accepting path: validate the pair, and on - * {@code ACCEPTED} hand the **untrimmed** candidate to the encoder, with nothing stored on a - * rejection. - * - * @param candidate The candidate password. - * @param confirmation The confirmation value. - * @param encoder The recording stand-in. - * - * @return The validator's decision. - */ + // 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); @@ -580,30 +420,7 @@ private static Result validateThenStore(String candidate, String confirmation, R return result; } - /** - * Property 10: Untrimmed storage. - * - * Validates: Requirements 3.5 - * - * For any accepted candidate password carrying leading or trailing whitespace, the value handed - * to the password encoder is the untrimmed candidate, while the length check that accepted it - * was applied to the trimmed value. - * - * Three things together make up the claim, and all three are asserted on every case: - * - * 1. The acceptance decision is governed by the trimmed length. A padded candidate is accepted - * exactly when its trimmed length reaches the minimum, so ten spaces around a five-character - * core is still {@code TOO_SHORT} and a six-character core padded on both sides is still - * {@code ACCEPTED}. - * 2. The value that reaches the encoder is the submitted string itself — the same object, not a - * trimmed, stripped, or otherwise normalised copy — so the padding survives into storage. - * 3. The validator offers the caller no normalised form to store in its place. Its only - * String-returning member is {@code messageFor}, so the only value a caller holds after an - * accepting decision is the untrimmed candidate it submitted. That is asserted reflectively, - * because it is a claim about the shape of the API rather than about one call. - * - * @param candidate The candidate password under test. - */ + // 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) { @@ -615,9 +432,6 @@ public void testUntrimmedStorage(String candidate) { Result result = validateThenStore(candidate, candidate, encoder); - // Requirement 3.5, first half: the length check that decides acceptance is applied to the - // trimmed value, so the decision for a padded candidate matches the decision for its - // trimmed core. assertEquals( Boolean.valueOf(trimmed.length() >= PasswordValidator.MINIMUM_TRIMMED_LENGTH), Boolean.valueOf(Result.ACCEPTED.equals(result)), @@ -629,28 +443,22 @@ public void testUntrimmedStorage(String candidate) { description + " decided as its trimmed form is decided"); if (!Result.ACCEPTED.equals(result)) { - // Nothing is stored on a rejection, so there is no value to make a claim about. assertEquals(0, encoder.invocations, description + " handed to the encoder despite rejection"); assertNull(encoder.encoded, description + " recorded despite rejection"); return; } - // Requirement 3.5, second half: the encoder is handed the untrimmed candidate — the very - // string that was submitted, padding and all. 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"); - // The two halves are only distinguishable where the padding is real, so pin the difference - // explicitly wherever it exists: the stored value is not the trimmed value. if (!candidate.equals(trimmed)) { assertTrue(!trimmed.equals(encoder.encoded), description + " stored trimmed rather than untrimmed"); } - // Requirement 3.5: the validator hands a caller no normalised candidate to store in place of - // the submitted one. messageFor is its only String-returning member. + // 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; From 05120f7561cdcff9075699c8619abc96c8db6469 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Thu, 22 Oct 2026 13:02:19 -0400 Subject: [PATCH 05/20] Add password change message --- .../controllers/changePasswordController.js | 38 ++++++++++++++++++- src/main/webapp/app/views/myprofile.html | 8 ++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/main/webapp/app/controllers/changePasswordController.js b/src/main/webapp/app/controllers/changePasswordController.js index 2bb6378ed0..e7779bee47 100644 --- a/src/main/webapp/app/controllers/changePasswordController.js +++ b/src/main/webapp/app/controllers/changePasswordController.js @@ -10,6 +10,33 @@ vireo.controller('ChangePasswordController', function ($controller, $scope, User 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.'; + + // WsApi resolves with the response on success and rejects with it on failure; in either case + // the ApiResponse may arrive as a JSON string in response.body or already parsed on + // response.payload. Pull the server message defensively, falling back to the generic text. + var messageFrom = function (response, fallback) { + var apiRes = response; + + if (response && typeof response.body === 'string') { + try { + apiRes = angular.fromJson(response.body); + } catch (e) { + apiRes = response; + } + } else if (response && response.payload) { + apiRes = response.payload; + } + + 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; @@ -34,11 +61,20 @@ vireo.controller('ChangePasswordController', function ($controller, $scope, User }; $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(clear, clear); + ).then(function (response) { + $scope.passwordChangeFeedback = { type: 'success', message: messageFrom(response, GENERIC_SUCCESS) }; + clear(); + }, function (response) { + $scope.passwordChangeFeedback = { type: 'danger', message: messageFrom(response, GENERIC_FAILURE) }; + clear(); + }); }; }); diff --git a/src/main/webapp/app/views/myprofile.html b/src/main/webapp/app/views/myprofile.html index 74b1d86e9a..88253babca 100644 --- a/src/main/webapp/app/views/myprofile.html +++ b/src/main/webapp/app/views/myprofile.html @@ -247,6 +247,14 @@

Preferences

Change Password

+
+
+ +
+
+
From 1d4d471f1e7837ed08b396b0e88ddddb75debda3 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Thu, 22 Oct 2026 13:31:14 -0400 Subject: [PATCH 06/20] Fix password change error styling to use red alert --- .../controllers/changePasswordController.js | 36 ++++++++++++------- 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/main/webapp/app/controllers/changePasswordController.js b/src/main/webapp/app/controllers/changePasswordController.js index e7779bee47..53bba11b17 100644 --- a/src/main/webapp/app/controllers/changePasswordController.js +++ b/src/main/webapp/app/controllers/changePasswordController.js @@ -16,22 +16,26 @@ vireo.controller('ChangePasswordController', function ($controller, $scope, User var GENERIC_SUCCESS = 'Your password has been changed.'; var GENERIC_FAILURE = 'Your password could not be changed.'; - // WsApi resolves with the response on success and rejects with it on failure; in either case - // the ApiResponse may arrive as a JSON string in response.body or already parsed on - // response.payload. Pull the server message defensively, falling back to the generic text. - var messageFrom = function (response, fallback) { - var apiRes = response; - + // 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 { - apiRes = angular.fromJson(response.body); + return angular.fromJson(response.body); } catch (e) { - apiRes = response; + return response; } - } else if (response && response.payload) { - apiRes = response.payload; } + 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; @@ -69,10 +73,18 @@ vireo.controller('ChangePasswordController', function ($controller, $scope, User $scope.passwordChange.newPassword, $scope.passwordChange.confirm ).then(function (response) { - $scope.passwordChangeFeedback = { type: 'success', message: messageFrom(response, GENERIC_SUCCESS) }; + 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(response, GENERIC_FAILURE) }; + $scope.passwordChangeFeedback = { type: 'danger', message: messageFrom(parseResponse(response), GENERIC_FAILURE) }; clear(); }); }; From 52498e5041a4bca1d10aec215611fbbd824f95de Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Fri, 23 Oct 2026 13:37:24 -0400 Subject: [PATCH 07/20] Add administrator-initiated password reset Add reset token service, reset initiation and redemption endpoints, reset request email template, and reset-password client surfaces. --- .../vireo/controller/PasswordController.java | 142 +++ .../tdl/vireo/service/ResetTokenService.java | 205 ++++ .../vireo/service/ResetTokenVerification.java | 71 ++ .../SYSTEM_Password_Reset_Request.email | 21 + src/main/webapp/app/config/apiMapping.js | 5 + src/main/webapp/app/config/routes.js | 3 + .../controllers/resetPasswordController.js | 27 + .../app/controllers/userRepoController.js | 30 +- src/main/webapp/app/repo/userRepo.js | 8 + .../app/services/passwordResetService.js | 17 + src/main/webapp/app/views/resetPassword.html | 41 + src/main/webapp/app/views/users.html | 3 + .../controller/PasswordControllerTest.java | 914 ++++++++++++++++++ .../vireo/service/ResetTokenServiceTest.java | 601 ++++++++++++ .../vireo/service/SystemDataLoaderTest.java | 3 +- 15 files changed, 2089 insertions(+), 2 deletions(-) create mode 100644 src/main/java/org/tdl/vireo/service/ResetTokenService.java create mode 100644 src/main/java/org/tdl/vireo/service/ResetTokenVerification.java create mode 100644 src/main/resources/emails/SYSTEM_Password_Reset_Request.email create mode 100644 src/main/webapp/app/controllers/resetPasswordController.js create mode 100644 src/main/webapp/app/services/passwordResetService.js create mode 100644 src/main/webapp/app/views/resetPassword.html create mode 100644 src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java diff --git a/src/main/java/org/tdl/vireo/controller/PasswordController.java b/src/main/java/org/tdl/vireo/controller/PasswordController.java index ade626a49c..a0f959556e 100644 --- a/src/main/java/org/tdl/vireo/controller/PasswordController.java +++ b/src/main/java/org/tdl/vireo/controller/PasswordController.java @@ -1,24 +1,33 @@ package org.tdl.vireo.controller; +import static edu.tamu.weaver.response.ApiStatus.ERROR; import static edu.tamu.weaver.response.ApiStatus.INVALID; import static edu.tamu.weaver.response.ApiStatus.SUCCESS; import static org.springframework.web.bind.annotation.RequestMethod.POST; import java.util.Map; +import javax.mail.MessagingException; + 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.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import org.tdl.vireo.model.EmailTemplate; import org.tdl.vireo.model.User; 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.PasswordEligibilityRule; import org.tdl.vireo.utility.PasswordValidator; +import org.tdl.vireo.utility.TemplateUtility; import edu.tamu.weaver.auth.annotation.WeaverUser; import edu.tamu.weaver.auth.service.CryptoService; @@ -35,6 +44,9 @@ public class PasswordController { private static final Logger LOG = LoggerFactory.getLogger(PasswordController.class); + @Value("${app.url}") + private String url; + @Autowired private UserRepo userRepo; @@ -47,6 +59,15 @@ public class PasswordController { @Autowired private CryptoService cryptoService; + @Autowired + private ResetTokenService resetTokenService; + + @Autowired + private TemplateUtility templateUtility; + + @Autowired + private VireoEmailSender emailSender; + /** * Replaces the password on the authenticated Account only; nothing in the request body can * target another Account. Checks run in order (availability, eligibility, current password, @@ -103,4 +124,125 @@ public ApiResponse changePassword(@WeaverUser User user, @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.debug("Unable to send a password reset email, because: " + e.getMessage()); + + 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/service/ResetTokenService.java b/src/main/java/org/tdl/vireo/service/ResetTokenService.java new file mode 100644 index 0000000000..d9f9fa423e --- /dev/null +++ b/src/main/java/org/tdl/vireo/service/ResetTokenService.java @@ -0,0 +1,205 @@ +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.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. Never throws: every decode and parse failure is caught and converted + * to a failure result. + * + * 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); + + long issuedAtEpochSeconds; + try { + issuedAtEpochSeconds = Long.parseLong(issuedAtText); + } catch (NumberFormatException 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(Instant.ofEpochSecond(issuedAtEpochSeconds), clock.instant()); + if (elapsed.isNegative()) { + return ResetTokenVerification.invalid(); + } + if (elapsed.toHours() >= expiryHours) { + return ResetTokenVerification.expired(); + } + + return ResetTokenVerification.valid(email, Instant.ofEpochSecond(issuedAtEpochSeconds)); + } + + /** + * 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/resources/emails/SYSTEM_Password_Reset_Request.email b/src/main/resources/emails/SYSTEM_Password_Reset_Request.email new file mode 100644 index 0000000000..e2acfbee56 --- /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 +etd-support@jhu.edu. + +The Hopkins ETD Team diff --git a/src/main/webapp/app/config/apiMapping.js b/src/main/webapp/app/config/apiMapping.js index fbb872bfc7..0c99981373 100644 --- a/src/main/webapp/app/config/apiMapping.js +++ b/src/main/webapp/app/config/apiMapping.js @@ -966,6 +966,11 @@ var apiMapping = { '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/resetPasswordController.js b/src/main/webapp/app/controllers/resetPasswordController.js new file mode 100644 index 0000000000..2735f8d4a0 --- /dev/null +++ b/src/main/webapp/app/controllers/resetPasswordController.js @@ -0,0 +1,27 @@ +vireo.controller('ResetPasswordController', function ($controller, $location, $scope, PasswordResetService) { + + 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 = ''; + + // Leave the user signed out; direct them to sign in with the new password. + $location.path('/login'); + } + }); + }; + +}); diff --git a/src/main/webapp/app/controllers/userRepoController.js b/src/main/webapp/app/controllers/userRepoController.js index 6ee9acb50b..e05c702c6d 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,24 @@ 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) { + if (window.confirm('Send a password reset link to ' + user.email + '?')) { + UserRepo.resetPassword(user); + } + }; + $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 ab591ca51a..d8182fd59a 100644 --- a/src/main/webapp/app/repo/userRepo.js +++ b/src/main/webapp/app/repo/userRepo.js @@ -20,6 +20,14 @@ vireo.repo("UserRepo", function UserRepo(User, WsApi) { 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/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..a5b1b16788 100644 --- a/src/main/webapp/app/views/users.html +++ b/src/main/webapp/app/views/users.html @@ -15,6 +15,9 @@ + + + diff --git a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java index 55a6cd3c59..cd02ca7643 100644 --- a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java @@ -7,13 +7,19 @@ 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.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -36,13 +42,19 @@ 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; @@ -169,6 +181,12 @@ private static Map claim(String key, String value) { @Mock private CredentialNotificationService credentialNotificationService; + @Mock + private ResetTokenService resetTokenService; + + @Mock + private VireoEmailSender emailSender; + @InjectMocks private PasswordController passwordController; @@ -476,4 +494,900 @@ private void stubFakeCrypto() { lenient().when(cryptoService.encodePassword(anyString())).thenAnswer(invocation -> FAKE_PREFIX + invocation.getArgument(0)); } + // ----------------------------------------------------------------------------------------- + // Task 12.3 - server-side enforcement and authorization for POST /password/reset. + // + // Each rejection cause pins INVALID, that no reset token is constructed, that no email is + // sent, and that the target Account's stored password is left unchanged. + // ----------------------------------------------------------------------------------------- + + 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); + } + + // ----------------------------------------------------------------------------------------- + // Task 12.4 - missing-template, mail-failure, and success-response for POST /password/reset. + // + // These exercise the path beyond the gates of task 12.3: template resolution returning null + // (ERROR naming the template, no send, unchanged password), a MessagingException from the + // send (ERROR, unchanged password), and a successful send (SUCCESS naming the recipient). + // ----------------------------------------------------------------------------------------- + + 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 MessagingException { + // 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); + + doThrow(MessagingException.class).when(emailSender).sendEmail(anyString(), anyString(), anyString()); + + ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + + assertEquals(ApiStatus.ERROR, response.getMeta().getStatus()); + assertEquals(unchanged, user1.getPassword(), "the stored password must be left unchanged when the send fails"); + } + + @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 send targets the recipient's own email address and carries the resolved subject. + verify(emailSender).sendEmail(eq(user1.getEmail()), eq(RESET_SUBJECT), anyString()); + } + + // ----------------------------------------------------------------------------------------- + // Task 12.5 - Property 19: No side effects on initiation or verification (initiation arm). + // + // Validates Requirements 7.5, 8.3. + // + // Driving POST /password/reset for an eligible Account constructs a token and sends mail, but + // never writes the stored password: no userRepo.update and no userRepo.save occurs on the + // initiation path, and the Account's stored password hash is byte-identical before and after. + // Cases are enumerated email/hash shapes crossed with a fixed-seed Random, fed through a + // @ParameterizedTest producing at least 100 cases. No property-based testing library is used. + // ----------------------------------------------------------------------------------------- + + 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); + } + + // ----------------------------------------------------------------------------------------- + // Task 12.6 - Property 12: Server-side enforcement across every entry point (reset arm). + // + // Validates Requirements 7.8, 7.9. + // + // Initiation is gated by the conjunction of auth.pass.enabled, auth.pass.reset.enabled and + // the Password_Eligibility_Rule, enforced server-side regardless of which gate fails or how + // many fail at once. Every failing combination constructs no token, sends no email, and + // leaves the stored password unchanged; the combination where every gate holds succeeds. + // ----------------------------------------------------------------------------------------- + + @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(); + } + + // ----------------------------------------------------------------------------------------- + // Task 13.2 - server-side enforcement for POST /password/reset/redeem. + // + // Each rejection cause pins INVALID, leaves the target Account's stored password unchanged, + // and dispatches no notification: auth.pass.enabled false, auth.pass.reset.enabled false, each + // token failure class (EXPIRED and INVALID), and an ineligible Account named by an otherwise + // valid token. + // ----------------------------------------------------------------------------------------- + + 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; + } + + // ----------------------------------------------------------------------------------------- + // Task 13.3 - Property 20: Redemption succeeds exactly under its conjunction. + // + // Validates Requirement 9.3. + // + // Redemption replaces the stored password of the Account named by the token only when + // availability, token verification, eligibility and candidate validity all hold together; + // under any other combination the stored password is left unchanged and nothing is written. + // Each dimension is varied independently 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(); + } + + // ----------------------------------------------------------------------------------------- + // Task 13.4 - Property 21: A rejected candidate leaves the token usable. + // + // Validates Requirement 9.9. + // + // A submission whose new password the PasswordValidator rejects must not consume or otherwise + // invalidate the Reset_Token. The real ResetTokenService is wired in for this test, in place of + // the mock used elsewhere in this class, so the token's continued usability is genuinely + // exercised rather than merely assumed from a mock that cannot invalidate anything on its own. + // After the rejection, the very same token is redeemed 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")); + } + + // ----------------------------------------------------------------------------------------- + // Task 13.8 - Successful-redemption response assertions. + // + // Validates Requirements 9.4, 9.5. + // + // A completed redemption carries no payload at all, so neither a token nor a credential of any + // kind rides along: unlike AuthController.login, whose success payload is a JWT from + // tokenService.createToken, this handler has no token-issuing dependency to call, and unlike + // AuthController.registration, whose success payload is the created User, it returns no object + // payload whatsoever. The caller is left to sign in rather than being authenticated + // automatically. + // ----------------------------------------------------------------------------------------- + + @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); + } + + // ----------------------------------------------------------------------------------------- + // Task 13.6 - Property 12: Server-side enforcement across every entry point (redemption arm). + // + // Validates Requirements 9.7, 9.8. + // + // Redemption is gated by the conjunction of auth.pass.enabled, auth.pass.reset.enabled and the + // Password_Eligibility_Rule, enforced server-side regardless of which gate fails or how many + // fail at once. Every failing combination leaves the stored password unchanged and dispatches + // no notification; the combination where every gate holds succeeds. The token itself verifies + // throughout, so only the availability and eligibility 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(); + } + + // ----------------------------------------------------------------------------------------- + // Task 13.5 - Property 22: Failure message partition. + // + // Validates Requirements 10.1, 10.2, 10.3, 10.4. + // + // Every verification failure other than a genuine expiry reports the identical generic + // message, regardless of which of several cryptographically indistinguishable causes produced + // it: a malformed token, a tampered signature, an unknown account, a token invalidated by an + // unrelated password change, and a backward clock step. A genuine expiry reports a different, + // expiry-specific message, even though the overall response status is INVALID for every cause + // here - only the message content distinguishes expiry from the rest. The real + // ResetTokenService is wired in so each cause is genuinely produced rather than merely stubbed. + // ----------------------------------------------------------------------------------------- + + 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); + + Clock baseClock = Clock.systemUTC(); + 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; + } + + // ----------------------------------------------------------------------------------------- + // Task 13.7 - Property 26: Leak containment across every outbound artefact (redemption arm). + // + // Validates Requirement 10.6. + // + // No response or log line produced by POST /password/reset/redeem may contain the Account's + // email, the Reset_Token, or the stored password hash (before or after any replacement) - + // regardless of which gate failed, which token status was returned, or whether the redemption + // succeeded. Reuses the conjunction case matrix from task 13.3 so every combination already + // exercised for correctness is also checked for leak containment. + // ----------------------------------------------------------------------------------------- + + @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/service/ResetTokenServiceTest.java b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java new file mode 100644 index 0000000000..fee1dbf368 --- /dev/null +++ b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java @@ -0,0 +1,601 @@ +package org.tdl.vireo.service; + +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.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +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.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; + } + + // --------------------------------------------------------------------- + // Property 1: Reset token round trip. Validates Requirements 8.1, 8.10, 16.4. + // --------------------------------------------------------------------- + + 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()); + } + + // --------------------------------------------------------------------- + // Property 2: A stored-password change invalidates every earlier token. + // Validates Requirements 8.8, 16.5. + // --------------------------------------------------------------------- + + 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"); + } + + // --------------------------------------------------------------------- + // Property 3: Expiry boundary. Validates Requirements 8.5, 8.7, 16.6. + // VALID in [0, expiryHours), EXPIRED at or beyond expiryHours, 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"); + } + + // --------------------------------------------------------------------- + // Property 4: Single use and sibling invalidation. Validates Requirements 8.9, 9.6, 16.7. + // 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"); + } + } + + // --------------------------------------------------------------------- + // Property 15: Token tamper rejection. Validates Requirements 8.2. + // Any mutation to the encoded payload segment or the signature segment of a well-formed, + // otherwise-valid token must verify as INVALID (NOT EXPIRED, NOT VALID). The clock is kept + // inside the expiry window so an untampered baseline verifies VALID; this proves the INVALID + // result comes from tampering, not from expiry. + // --------------------------------------------------------------------- + + /** 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); + } + } + + // --------------------------------------------------------------------- + // Property 19: No side effects on initiation or verification (verification arm). + // Validates Requirements 7.5, 8.3. + // + // ResetTokenService.verify reads no persisted token state and writes no Account. Across a full + // construct-and-verify cycle the only repository interaction is the read-only findByEmail + // lookup: verify must never invoke userRepo.update or userRepo.save, and the Account's stored + // password hash must be byte-identical before and after the verify call. The whole partition of + // verification outcomes is exercised (VALID, EXPIRED, INVALID) so no outcome is left able to + // 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"); From ab5a1c359cb22b3fe25f8ab3e5549c24248002e4 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Wed, 28 Oct 2026 15:35:54 -0400 Subject: [PATCH 08/20] Update email template language to be generic --- src/main/resources/emails/SYSTEM_Password_Changed.email | 6 +++--- .../resources/emails/SYSTEM_Password_Reset_Request.email | 4 ++-- .../vireo/service/CredentialNotificationServiceTest.java | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/main/resources/emails/SYSTEM_Password_Changed.email b/src/main/resources/emails/SYSTEM_Password_Changed.email index f3fe38c072..be60cbb5af 100644 --- a/src/main/resources/emails/SYSTEM_Password_Changed.email +++ b/src/main/resources/emails/SYSTEM_Password_Changed.email @@ -8,7 +8,7 @@ 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 etd-support@jhu.edu right -away so we can help you secure your account. +If you did not make this change, please email +vireo@myuniversity.edu or call us at xxx-555-xxxx right away. -The Hopkins ETD Team +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 index e2acfbee56..652f1855d8 100644 --- a/src/main/resources/emails/SYSTEM_Password_Reset_Request.email +++ b/src/main/resources/emails/SYSTEM_Password_Reset_Request.email @@ -16,6 +16,6 @@ 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 -etd-support@jhu.edu. +vireo@myuniversity.edu or call us at xxx-555-xxxx. -The Hopkins ETD Team +The Vireo Team diff --git a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java index d1ec25ae02..ee02cb5cd5 100644 --- a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java @@ -412,9 +412,9 @@ private void stubAvailability(boolean enabled, boolean change, boolean reset) { private static final String PASSWORD_CHANGED_RESOURCE = "/emails/SYSTEM_Password_Changed.email"; - private static final String SUPPORT_ADDRESS = "etd-support@jhu.edu"; + private static final String SUPPORT_CONTACT_PHRASE = "vireo@myuniversity.edu or call us at xxx-555-xxxx"; - private static final String SIGN_OFF = "The Hopkins ETD Team"; + private static final String SIGN_OFF = "The Vireo Team"; private static final String CHANGE_TIME_PLACEHOLDER = "{CHANGE_TIME}"; @@ -445,7 +445,7 @@ public void testPackagedPasswordChangedTemplateCarriesChangeTime() throws IOExce public void testPackagedPasswordChangedTemplateCarriesSupportContact() throws IOException { String body = packagedBody(readPackagedPasswordChangedTemplate()); - assertTrue(body.contains(SUPPORT_ADDRESS), "The template body directs the recipient to " + SUPPORT_ADDRESS + ", got: " + body); + assertTrue(body.contains(SUPPORT_CONTACT_PHRASE), "The template body directs the recipient to " + SUPPORT_CONTACT_PHRASE + ", got: " + body); assertTrue(body.contains(SIGN_OFF), "The template body signs off as '" + SIGN_OFF + "', got: " + body); } From cf58a7267b6f518b59e19b25a811b129647ef657 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Thu, 29 Oct 2026 14:38:57 -0400 Subject: [PATCH 09/20] Add admin reset confirmation modal --- .../app/controllers/resetPasswordController.js | 7 ++++++- .../webapp/app/controllers/userRepoController.js | 11 ++++++++--- .../views/modals/users/confirmResetPassword.html | 15 +++++++++++++++ src/main/webapp/app/views/users.html | 6 ++++++ 4 files changed, 35 insertions(+), 4 deletions(-) create mode 100644 src/main/webapp/app/views/modals/users/confirmResetPassword.html diff --git a/src/main/webapp/app/controllers/resetPasswordController.js b/src/main/webapp/app/controllers/resetPasswordController.js index 2735f8d4a0..7594818e38 100644 --- a/src/main/webapp/app/controllers/resetPasswordController.js +++ b/src/main/webapp/app/controllers/resetPasswordController.js @@ -1,4 +1,4 @@ -vireo.controller('ResetPasswordController', function ($controller, $location, $scope, PasswordResetService) { +vireo.controller('ResetPasswordController', function ($controller, $location, $scope, PasswordResetService, StorageService) { angular.extend(this, $controller('AbstractController', { $scope: $scope })); @@ -19,6 +19,11 @@ vireo.controller('ResetPasswordController', function ($controller, $location, $s $scope.resetPassword.confirm = ''; // Leave the user signed out; direct them to sign in with the new password. + // LoginController.login() checks post_authorize_url after a successful local + // sign-in and navigates there; without it, it just reloads the current page + // (/login), which then shows "You are already logged in" with nowhere to go. + StorageService.set('post_authorize_url', '/myprofile'); + $location.path('/login'); } }); diff --git a/src/main/webapp/app/controllers/userRepoController.js b/src/main/webapp/app/controllers/userRepoController.js index e05c702c6d..ec14111008 100644 --- a/src/main/webapp/app/controllers/userRepoController.js +++ b/src/main/webapp/app/controllers/userRepoController.js @@ -71,9 +71,14 @@ vireo.controller('UserRepoController', function ($controller, $location, $scope, }; $scope.confirmResetPassword = function (user) { - if (window.confirm('Send a password reset link to ' + user.email + '?')) { - UserRepo.resetPassword(user); - } + $scope.userToResetPassword = user; + $scope.openModal('#confirmResetPassword'); + }; + + $scope.resetPassword = function () { + UserRepo.resetPassword($scope.userToResetPassword); + $scope.closeModal(); + $scope.userToResetPassword = null; }; $scope.roles = {}; 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/users.html b/src/main/webapp/app/views/users.html index a5b1b16788..502e14d136 100644 --- a/src/main/webapp/app/views/users.html +++ b/src/main/webapp/app/views/users.html @@ -26,4 +26,10 @@
+ + +
From 37faae20cb25747ceb1814e90d3b7ca3139a1a25 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Fri, 30 Oct 2026 11:38:50 -0400 Subject: [PATCH 10/20] Update config validator to allow 1 character input --- .../vireo/model/validation/ManagedConfigurationValidator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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..cbbabfe060 100644 --- a/src/main/java/org/tdl/vireo/model/validation/ManagedConfigurationValidator.java +++ b/src/main/java/org/tdl/vireo/model/validation/ManagedConfigurationValidator.java @@ -14,7 +14,7 @@ public ManagedConfigurationValidator() { 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.minlength, "Managed Configuration value must be at least 1 character", valueProperty, 1)); String typeProperty = "type"; this.addInputValidator(new InputValidator(InputValidationType.required, "Managed Configuration requires a type", typeProperty, true)); From 685d514f56095d62747a70f9f8094332e0b25083 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Fri, 30 Oct 2026 15:20:26 -0400 Subject: [PATCH 11/20] Update validation on link expiry --- .../app/controllers/settingsController.js | 22 +++++++++++++++++++ .../application/passwordManagement.html | 2 +- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/src/main/webapp/app/controllers/settingsController.js b/src/main/webapp/app/controllers/settingsController.js index a0e44d7839..de7a7e8213 100644 --- a/src/main/webapp/app/controllers/settingsController.js +++ b/src/main/webapp/app/controllers/settingsController.js @@ -95,6 +95,28 @@ vireo.controller("SettingsController", function ($controller, $injector, $scope, "false": "Disabled" }]; + // The generic ManagedConfiguration validator only enforces "at least 1 character" on every + // setting's value, so it accepts "0" here with no error even though the server-side + // PasswordFeatureAvailabilityService.getResetExpiryHours() treats anything outside 1..Integer.MAX_VALUE + // as invalid and silently falls back to 24. This client-only override gives the admin + // real-time feedback instead of a value that saves successfully but quietly has no effect. + $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 of 1 or more", + "property": "value", + "value": "^[1-9][0-9]*$" + } + } + }; + var userSettingsValidations = { "displayName": { "minlength": { diff --git a/src/main/webapp/app/views/admin/settings/application/passwordManagement.html b/src/main/webapp/app/views/admin/settings/application/passwordManagement.html index 09c51fbd5c..70afd5481c 100644 --- a/src/main/webapp/app/views/admin/settings/application/passwordManagement.html +++ b/src/main/webapp/app/views/admin/settings/application/passwordManagement.html @@ -32,7 +32,7 @@ label="Password Reset Link Expiry (hours)" model="settings.configurable.application['auth.pass.reset.expiryHours']" property="value" - validations="settings.configurable.application['auth.pass.reset.expiryHours'].getValidations()" + validations="expiryHoursValidations" confirm="updateConfiguration('application', 'auth.pass.reset.expiryHours')" form-view="true" tool-tip="Enter the number of hours a password reset link remains valid. Must be a whole number of 1 or more."> From 714de5a3ea9bf383ace160b03f225db12970a63a Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Mon, 2 Nov 2026 11:51:02 -0500 Subject: [PATCH 12/20] Remove email changed template --- .../org/tdl/vireo/service/CredentialNotificationService.java | 2 -- .../tdl/vireo/service/CredentialNotificationServiceTest.java | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java b/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java index 04c0d5e788..e0417579d1 100644 --- a/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java +++ b/src/main/java/org/tdl/vireo/service/CredentialNotificationService.java @@ -29,8 +29,6 @@ public class CredentialNotificationService { public static final String PASSWORD_CHANGED_TEMPLATE = "SYSTEM Password Changed"; - public static final String EMAIL_CHANGED_TEMPLATE = "SYSTEM Email Address Changed"; - private static final String PASSWORD_CHANGED_NOTIFICATION = "password-changed notification"; private static final String CHANGE_TIME_PARAMETER = "CHANGE_TIME"; diff --git a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java index ee02cb5cd5..84f7521d7f 100644 --- a/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/CredentialNotificationServiceTest.java @@ -215,7 +215,7 @@ private void assertNoSensitiveValueLogged(String log) { assertFalse(log.contains(TEST_TOKEN), "No token value may appear in the log output, got: " + log); } - // Always-on notification (password-changed arm). + // Always-on notification. private static final long GENERATOR_SEED = 20250101L; From ea98a6fee392d18f70befd3d41b609a2b11602f6 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Mon, 2 Nov 2026 14:20:37 -0500 Subject: [PATCH 13/20] Cleanup comments --- .../tdl/vireo/controller/UserController.java | 2 +- .../PasswordFeatureAvailabilityService.java | 3 - .../controllers/resetPasswordController.js | 6 +- .../app/controllers/settingsController.js | 7 +- .../vireo/controller/AuthControllerTest.java | 2 +- .../controller/PasswordControllerTest.java | 117 +++++------------- .../vireo/service/ResetTokenServiceTest.java | 32 ++--- 7 files changed, 44 insertions(+), 125 deletions(-) diff --git a/src/main/java/org/tdl/vireo/controller/UserController.java b/src/main/java/org/tdl/vireo/controller/UserController.java index 63d7f0ecfe..7637fdea06 100644 --- a/src/main/java/org/tdl/vireo/controller/UserController.java +++ b/src/main/java/org/tdl/vireo/controller/UserController.java @@ -53,7 +53,7 @@ public class UserController { @RequestMapping("/credentials") @PreAuthorize("hasRole('ROLE_STUDENT')") public ApiResponse credentials(@WeaverCredentials Credentials credentials, @WeaverUser User user) { - // User.password is @JsonIgnore'd, so the server computes eligibility. It rides in allCredentials as the String "true" or "false". + // User.password is @JsonIgnore'd, so eligibility is computed here; the map is Map. Map allCredentials = credentials.getAllCredentials(); diff --git a/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java b/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java index c50d0bc214..de42d354d2 100644 --- a/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java +++ b/src/main/java/org/tdl/vireo/service/PasswordFeatureAvailabilityService.java @@ -50,9 +50,6 @@ public boolean isResetAvailable() { return isPasswordLoginEnabled() && isResetEnabled(); } - // TODO: isChangeAvailableFor(User) and isResetAvailableFor(User) are added alongside - // PasswordEligibilityRule. - /** * 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. diff --git a/src/main/webapp/app/controllers/resetPasswordController.js b/src/main/webapp/app/controllers/resetPasswordController.js index 7594818e38..3856a49c2b 100644 --- a/src/main/webapp/app/controllers/resetPasswordController.js +++ b/src/main/webapp/app/controllers/resetPasswordController.js @@ -18,10 +18,8 @@ vireo.controller('ResetPasswordController', function ($controller, $location, $s $scope.resetPassword.newPassword = ''; $scope.resetPassword.confirm = ''; - // Leave the user signed out; direct them to sign in with the new password. - // LoginController.login() checks post_authorize_url after a successful local - // sign-in and navigates there; without it, it just reloads the current page - // (/login), which then shows "You are already logged in" with nowhere to go. + // Leave the user signed out. Without post_authorize_url, LoginController reloads + // /login after sign-in, which then just says "You are already logged in". StorageService.set('post_authorize_url', '/myprofile'); $location.path('/login'); diff --git a/src/main/webapp/app/controllers/settingsController.js b/src/main/webapp/app/controllers/settingsController.js index de7a7e8213..841f9816a5 100644 --- a/src/main/webapp/app/controllers/settingsController.js +++ b/src/main/webapp/app/controllers/settingsController.js @@ -95,11 +95,8 @@ vireo.controller("SettingsController", function ($controller, $injector, $scope, "false": "Disabled" }]; - // The generic ManagedConfiguration validator only enforces "at least 1 character" on every - // setting's value, so it accepts "0" here with no error even though the server-side - // PasswordFeatureAvailabilityService.getResetExpiryHours() treats anything outside 1..Integer.MAX_VALUE - // as invalid and silently falls back to 24. This client-only override gives the admin - // real-time feedback instead of a value that saves successfully but quietly has no effect. + // The generic ManagedConfiguration validations accept "0" here; the server would then silently + // fall back to 24 hours, so enforce a positive whole number client-side for immediate feedback. $scope.expiryHoursValidations = { "value": { "required": { diff --git a/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java b/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java index 8629f2bc97..d1efd57fda 100644 --- a/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/AuthControllerTest.java @@ -324,7 +324,7 @@ private void setupDataMap() { data.put("confirm", data.get("userPassword")); } - // Property 11: registration retrofit preserves outcomes. Additive; existing tests above are unchanged. + // The PasswordValidator retrofit preserves every registration outcome. Additive; existing tests above are unchanged. private static final long RETROFIT_GENERATOR_SEED = 20250101L; diff --git a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java index cd02ca7643..c48316ad7b 100644 --- a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java @@ -69,7 +69,7 @@ import edu.tamu.weaver.validation.utility.ValidationUtility; /** - * Tests for {@code POST /password/change}: gating, principal targeting and leak containment. + * 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. */ @@ -495,10 +495,8 @@ private void stubFakeCrypto() { } // ----------------------------------------------------------------------------------------- - // Task 12.3 - server-side enforcement and authorization for POST /password/reset. - // - // Each rejection cause pins INVALID, that no reset token is constructed, that no email is - // sent, and that the target Account's stored password is left unchanged. + // 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"; @@ -619,11 +617,8 @@ private void stubResetSettings(String passwordLoginEnabled, String resetEnabled) } // ----------------------------------------------------------------------------------------- - // Task 12.4 - missing-template, mail-failure, and success-response for POST /password/reset. - // - // These exercise the path beyond the gates of task 12.3: template resolution returning null - // (ERROR naming the template, no send, unchanged password), a MessagingException from the - // send (ERROR, unchanged password), and a successful send (SUCCESS naming the recipient). + // 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"; @@ -702,15 +697,8 @@ public void testInitiateResetSendsToTheRecipientOnSuccess() throws MessagingExce } // ----------------------------------------------------------------------------------------- - // Task 12.5 - Property 19: No side effects on initiation or verification (initiation arm). - // - // Validates Requirements 7.5, 8.3. - // - // Driving POST /password/reset for an eligible Account constructs a token and sends mail, but - // never writes the stored password: no userRepo.update and no userRepo.save occurs on the - // initiation path, and the Account's stored password hash is byte-identical before and after. - // Cases are enumerated email/hash shapes crossed with a fixed-seed Random, fed through a - // @ParameterizedTest producing at least 100 cases. No property-based testing library is used. + // 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() { @@ -782,14 +770,8 @@ public void initiateResetConstructsTokenAndSendsMailButWritesNoPassword(String e } // ----------------------------------------------------------------------------------------- - // Task 12.6 - Property 12: Server-side enforcement across every entry point (reset arm). - // - // Validates Requirements 7.8, 7.9. - // - // Initiation is gated by the conjunction of auth.pass.enabled, auth.pass.reset.enabled and - // the Password_Eligibility_Rule, enforced server-side regardless of which gate fails or how - // many fail at once. Every failing combination constructs no token, sends no email, and - // leaves the stored password unchanged; the combination where every gate holds succeeds. + // 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}") @@ -865,12 +847,9 @@ private static Stream provideResetEnforcementCases() { } // ----------------------------------------------------------------------------------------- - // Task 13.2 - server-side enforcement for POST /password/reset/redeem. - // - // Each rejection cause pins INVALID, leaves the target Account's stored password unchanged, - // and dispatches no notification: auth.pass.enabled false, auth.pass.reset.enabled false, each - // token failure class (EXPIRED and INVALID), and an ineligible Account named by an otherwise - // valid token. + // 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"; @@ -982,14 +961,9 @@ private Map redeemRequest(String token, String newPassword, Stri } // ----------------------------------------------------------------------------------------- - // Task 13.3 - Property 20: Redemption succeeds exactly under its conjunction. - // - // Validates Requirement 9.3. - // - // Redemption replaces the stored password of the Account named by the token only when - // availability, token verification, eligibility and candidate validity all hold together; - // under any other combination the stored password is left unchanged and nothing is written. - // Each dimension is varied independently against an otherwise-succeeding baseline. + // 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}") @@ -1079,15 +1053,9 @@ private static Stream provideRedemptionConjunctionCases() { } // ----------------------------------------------------------------------------------------- - // Task 13.4 - Property 21: A rejected candidate leaves the token usable. - // - // Validates Requirement 9.9. - // - // A submission whose new password the PasswordValidator rejects must not consume or otherwise - // invalidate the Reset_Token. The real ResetTokenService is wired in for this test, in place of - // the mock used elsewhere in this class, so the token's continued usability is genuinely - // exercised rather than merely assumed from a mock that cannot invalidate anything on its own. - // After the rejection, the very same token is redeemed successfully. + // 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") @@ -1136,16 +1104,8 @@ private static Stream provideRejectedCandidatesForTokenUsability() { } // ----------------------------------------------------------------------------------------- - // Task 13.8 - Successful-redemption response assertions. - // - // Validates Requirements 9.4, 9.5. - // - // A completed redemption carries no payload at all, so neither a token nor a credential of any - // kind rides along: unlike AuthController.login, whose success payload is a JWT from - // tokenService.createToken, this handler has no token-issuing dependency to call, and unlike - // AuthController.registration, whose success payload is the created User, it returns no object - // payload whatsoever. The caller is left to sign in rather than being authenticated - // automatically. + // 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 @@ -1171,15 +1131,8 @@ public void testRedeemResetSuccessCarriesNoTokenAndNoCredential() throws Excepti } // ----------------------------------------------------------------------------------------- - // Task 13.6 - Property 12: Server-side enforcement across every entry point (redemption arm). - // - // Validates Requirements 9.7, 9.8. - // - // Redemption is gated by the conjunction of auth.pass.enabled, auth.pass.reset.enabled and the - // Password_Eligibility_Rule, enforced server-side regardless of which gate fails or how many - // fail at once. Every failing combination leaves the stored password unchanged and dispatches - // no notification; the combination where every gate holds succeeds. The token itself verifies - // throughout, so only the availability and eligibility gates are under test here. + // 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}") @@ -1253,17 +1206,10 @@ private static Stream provideRedeemEnforcementCases() { } // ----------------------------------------------------------------------------------------- - // Task 13.5 - Property 22: Failure message partition. - // - // Validates Requirements 10.1, 10.2, 10.3, 10.4. - // - // Every verification failure other than a genuine expiry reports the identical generic - // message, regardless of which of several cryptographically indistinguishable causes produced - // it: a malformed token, a tampered signature, an unknown account, a token invalidated by an - // unrelated password change, and a backward clock step. A genuine expiry reports a different, - // expiry-specific message, even though the overall response status is INVALID for every cause - // here - only the message content distinguishes expiry from the rest. The real - // ResetTokenService is wired in so each cause is genuinely produced rather than merely stubbed. + // 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."; @@ -1347,15 +1293,8 @@ private static String tamper(String token) { } // ----------------------------------------------------------------------------------------- - // Task 13.7 - Property 26: Leak containment across every outbound artefact (redemption arm). - // - // Validates Requirement 10.6. - // - // No response or log line produced by POST /password/reset/redeem may contain the Account's - // email, the Reset_Token, or the stored password hash (before or after any replacement) - - // regardless of which gate failed, which token status was returned, or whether the redemption - // succeeded. Reuses the conjunction case matrix from task 13.3 so every combination already - // exercised for correctness is also checked for leak containment. + // 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}") diff --git a/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java index fee1dbf368..8ab075d333 100644 --- a/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java @@ -73,7 +73,7 @@ private static User userWith(String email, String storedHash) { } // --------------------------------------------------------------------- - // Property 1: Reset token round trip. Validates Requirements 8.1, 8.10, 16.4. + // Round trip: a constructed token verifies back to its email and issued-at instant. // --------------------------------------------------------------------- static Stream roundTripCases() { @@ -145,8 +145,7 @@ public void roundTripVerifiesValid(String email, String storedHash, Instant issu } // --------------------------------------------------------------------- - // Property 2: A stored-password change invalidates every earlier token. - // Validates Requirements 8.8, 16.5. + // A stored-password change invalidates every earlier token. // --------------------------------------------------------------------- static Stream passwordChangeCases() { @@ -204,8 +203,7 @@ public void storedPasswordChangeInvalidatesToken(String email, String oldPasswor } // --------------------------------------------------------------------- - // Property 3: Expiry boundary. Validates Requirements 8.5, 8.7, 16.6. - // VALID in [0, expiryHours), EXPIRED at or beyond expiryHours, INVALID for negative offsets. + // Expiry boundary: VALID in [0, expiryHours), EXPIRED at or beyond, INVALID for negative offsets. // --------------------------------------------------------------------- static Stream expiryCases() { @@ -269,9 +267,8 @@ public void expiryPartitionHolds(int expiryHours, long hourOffset) { } // --------------------------------------------------------------------- - // Property 4: Single use and sibling invalidation. Validates Requirements 8.9, 9.6, 16.7. - // The clock stays inside the expiry window throughout, so an expiry result cannot be mistaken - // for the single-use result. + // 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() { @@ -341,11 +338,8 @@ public void singleUseInvalidatesRedeemedAndSiblingTokens(String email, String pa } // --------------------------------------------------------------------- - // Property 15: Token tamper rejection. Validates Requirements 8.2. - // Any mutation to the encoded payload segment or the signature segment of a well-formed, - // otherwise-valid token must verify as INVALID (NOT EXPIRED, NOT VALID). The clock is kept - // inside the expiry window so an untampered baseline verifies VALID; this proves the INVALID - // result comes from tampering, not from expiry. + // 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. */ @@ -480,15 +474,9 @@ private static String mutate(String segment, Mutation mutation, int positionSeed } // --------------------------------------------------------------------- - // Property 19: No side effects on initiation or verification (verification arm). - // Validates Requirements 7.5, 8.3. - // - // ResetTokenService.verify reads no persisted token state and writes no Account. Across a full - // construct-and-verify cycle the only repository interaction is the read-only findByEmail - // lookup: verify must never invoke userRepo.update or userRepo.save, and the Account's stored - // password hash must be byte-identical before and after the verify call. The whole partition of - // verification outcomes is exercised (VALID, EXPIRED, INVALID) so no outcome is left able to - // hide a write. + // 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. */ From 3d0e738759b230dc7721e7f6a09bcd35686f0088 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Mon, 2 Nov 2026 15:41:48 -0500 Subject: [PATCH 14/20] Update delivery failure log level --- .../vireo/controller/PasswordController.java | 2 +- .../controller/PasswordControllerTest.java | 33 +++++++++++++++++-- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/tdl/vireo/controller/PasswordController.java b/src/main/java/org/tdl/vireo/controller/PasswordController.java index a0f959556e..d9e0815541 100644 --- a/src/main/java/org/tdl/vireo/controller/PasswordController.java +++ b/src/main/java/org/tdl/vireo/controller/PasswordController.java @@ -169,7 +169,7 @@ public ApiResponse initiateReset(@RequestBody Map data) { try { emailSender.sendEmail(user.getEmail(), emailTemplate.getSubject(), content); } catch (MessagingException e) { - LOG.debug("Unable to send a password reset email, because: " + e.getMessage()); + LOG.warn("Unable to send a password reset email.", e); return ApiResponse.fromException(ERROR, "Unable to send the password reset email.", e); } diff --git a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java index c48316ad7b..ee78a1476b 100644 --- a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java @@ -653,7 +653,7 @@ public void testInitiateResetReportsAnErrorWhenTheTemplateIsMissing() { } @Test - public void testInitiateResetReportsAnErrorWhenTheSendFails() throws MessagingException { + 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. @@ -667,12 +667,39 @@ public void testInitiateResetReportsAnErrorWhenTheSendFails() throws MessagingEx when(resetTokenService.construct(user1)).thenReturn(RESET_TOKEN); lenient().when(templateUtility.templateParameters(any(String.class), any(String[][].class))).thenReturn(RESET_MESSAGE); - doThrow(MessagingException.class).when(emailSender).sendEmail(anyString(), anyString(), anyString()); + MessagingException mailFailure = new MessagingException("transport failure"); + doThrow(mailFailure).when(emailSender).sendEmail(anyString(), anyString(), anyString()); - ApiResponse response = passwordController.initiateReset(resetRequest(RESET_EMAIL)); + 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 From 6295914f689cd807b1534447836d74bcb81300c4 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Mon, 2 Nov 2026 15:49:35 -0500 Subject: [PATCH 15/20] Fix time range issue --- .../org/tdl/vireo/service/ResetTokenService.java | 16 +++++++++------- .../tdl/vireo/service/ResetTokenServiceTest.java | 6 ++++++ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/tdl/vireo/service/ResetTokenService.java b/src/main/java/org/tdl/vireo/service/ResetTokenService.java index d9f9fa423e..852b11457c 100644 --- a/src/main/java/org/tdl/vireo/service/ResetTokenService.java +++ b/src/main/java/org/tdl/vireo/service/ResetTokenService.java @@ -5,6 +5,7 @@ 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; @@ -83,8 +84,8 @@ public String construct(User user) { } /** - * Verifies a reset token. Never throws: every decode and parse failure is caught and converted - * to a failure result. + * 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. @@ -138,10 +139,11 @@ public ResetTokenVerification verify(String token) { String bindingValue = payload.substring(priorPipe + 1, lastPipe); String issuedAtText = payload.substring(lastPipe + 1); - long issuedAtEpochSeconds; + Instant issuedAt; try { - issuedAtEpochSeconds = Long.parseLong(issuedAtText); - } catch (NumberFormatException e) { + long issuedAtEpochSeconds = Long.parseLong(issuedAtText); + issuedAt = Instant.ofEpochSecond(issuedAtEpochSeconds); + } catch (NumberFormatException | DateTimeException e) { return ResetTokenVerification.invalid(); } @@ -159,7 +161,7 @@ public ResetTokenVerification verify(String token) { int expiryHours = availabilityService.getResetExpiryHours(); - Duration elapsed = Duration.between(Instant.ofEpochSecond(issuedAtEpochSeconds), clock.instant()); + Duration elapsed = Duration.between(issuedAt, clock.instant()); if (elapsed.isNegative()) { return ResetTokenVerification.invalid(); } @@ -167,7 +169,7 @@ public ResetTokenVerification verify(String token) { return ResetTokenVerification.expired(); } - return ResetTokenVerification.valid(email, Instant.ofEpochSecond(issuedAtEpochSeconds)); + return ResetTokenVerification.valid(email, issuedAt); } /** diff --git a/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java index 8ab075d333..62d1bedd5d 100644 --- a/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java @@ -1,5 +1,6 @@ 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; @@ -11,15 +12,20 @@ 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; From 4944989a9301010cbc756f71434098d2548ed46e Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Mon, 2 Nov 2026 15:52:21 -0500 Subject: [PATCH 16/20] Update reset token test for new boundary cases --- .../vireo/service/ResetTokenServiceTest.java | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java index 62d1bedd5d..b1cfd7c23f 100644 --- a/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java +++ b/src/test/java/org/tdl/vireo/service/ResetTokenServiceTest.java @@ -150,6 +150,60 @@ public void roundTripVerifiesValid(String email, String storedHash, Instant issu 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. // --------------------------------------------------------------------- From 662fb0c2156aaed0b20e6fa0f38184892ec9e0a0 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Mon, 2 Nov 2026 18:38:36 -0500 Subject: [PATCH 17/20] Revert back to 2 character validation in ManagedConfiguration --- .../ManagedConfigurationValidator.java | 60 ++++++++++++++++++- .../app/controllers/settingsController.js | 7 +-- .../application/passwordManagement.html | 2 +- .../vireo/model/ManagedConfigurationTest.java | 58 ++++++++++++++++++ 4 files changed, 119 insertions(+), 8 deletions(-) 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 cbbabfe060..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 1 character", valueProperty, 1)); + 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/webapp/app/controllers/settingsController.js b/src/main/webapp/app/controllers/settingsController.js index 841f9816a5..d4c3ff935a 100644 --- a/src/main/webapp/app/controllers/settingsController.js +++ b/src/main/webapp/app/controllers/settingsController.js @@ -95,8 +95,7 @@ vireo.controller("SettingsController", function ($controller, $injector, $scope, "false": "Disabled" }]; - // The generic ManagedConfiguration validations accept "0" here; the server would then silently - // fall back to 24 hours, so enforce a positive whole number client-side for immediate feedback. + // Enforce the server's positive Java integer range before saving the setting. $scope.expiryHoursValidations = { "value": { "required": { @@ -107,9 +106,9 @@ vireo.controller("SettingsController", function ($controller, $injector, $scope, }, "pattern": { "type": "pattern", - "message": "Password Reset Link Expiry must be a whole number of 1 or more", + "message": "Password Reset Link Expiry must be a whole number from 1 through 2147483647", "property": "value", - "value": "^[1-9][0-9]*$" + "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])$" } } }; diff --git a/src/main/webapp/app/views/admin/settings/application/passwordManagement.html b/src/main/webapp/app/views/admin/settings/application/passwordManagement.html index 70afd5481c..eb57433f47 100644 --- a/src/main/webapp/app/views/admin/settings/application/passwordManagement.html +++ b/src/main/webapp/app/views/admin/settings/application/passwordManagement.html @@ -35,7 +35,7 @@ validations="expiryHoursValidations" confirm="updateConfiguration('application', 'auth.pass.reset.expiryHours')" form-view="true" - tool-tip="Enter the number of hours a password reset link remains valid. Must be a whole number of 1 or more."> + tool-tip="Enter the number of hours a password reset link remains valid. Must be a whole number from 1 through 2147483647.">
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")); + } + } From 4720617f6f11e3f2c4a03b26cfcba7926c4c7cd6 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Tue, 3 Nov 2026 09:25:41 -0500 Subject: [PATCH 18/20] Fix password tests --- .../tdl/vireo/controller/PasswordControllerTest.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java index ee78a1476b..c4875f1d96 100644 --- a/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java +++ b/src/test/java/org/tdl/vireo/controller/PasswordControllerTest.java @@ -20,6 +20,7 @@ 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; @@ -719,7 +720,10 @@ public void testInitiateResetSendsToTheRecipientOnSuccess() throws MessagingExce assertEquals(ApiStatus.SUCCESS, response.getMeta().getStatus()); - // The send targets the recipient's own email address and carries the resolved subject. + // 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()); } @@ -1250,7 +1254,10 @@ public void testRedeemResetReportsTheSameGenericMessageForEveryNonExpiryCause() ReflectionTestUtils.setField(realResetTokenService, "userRepo", userRepo); ReflectionTestUtils.setField(realResetTokenService, "availabilityService", availabilityService); - Clock baseClock = Clock.systemUTC(); + // 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); From 442eba6c4e52c53c227b0670ba510d58b0a3a1f5 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Tue, 3 Nov 2026 09:38:15 -0500 Subject: [PATCH 19/20] Clarify post-sign-in redirect comment in reset password controller --- src/main/webapp/app/controllers/resetPasswordController.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/webapp/app/controllers/resetPasswordController.js b/src/main/webapp/app/controllers/resetPasswordController.js index 3856a49c2b..13d6ffdd70 100644 --- a/src/main/webapp/app/controllers/resetPasswordController.js +++ b/src/main/webapp/app/controllers/resetPasswordController.js @@ -18,8 +18,8 @@ vireo.controller('ResetPasswordController', function ($controller, $location, $s $scope.resetPassword.newPassword = ''; $scope.resetPassword.confirm = ''; - // Leave the user signed out. Without post_authorize_url, LoginController reloads - // /login after sign-in, which then just says "You are already logged in". + // 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. StorageService.set('post_authorize_url', '/myprofile'); $location.path('/login'); From 3087d56bb4bbe9640c6dd995744df65f80eb7099 Mon Sep 17 00:00:00 2001 From: Timothy Sanders Date: Tue, 3 Nov 2026 11:45:36 -0500 Subject: [PATCH 20/20] Fix context path for post-reset redirect --- .../app/controllers/resetPasswordController.js | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/main/webapp/app/controllers/resetPasswordController.js b/src/main/webapp/app/controllers/resetPasswordController.js index 13d6ffdd70..542632504b 100644 --- a/src/main/webapp/app/controllers/resetPasswordController.js +++ b/src/main/webapp/app/controllers/resetPasswordController.js @@ -1,4 +1,4 @@ -vireo.controller('ResetPasswordController', function ($controller, $location, $scope, PasswordResetService, StorageService) { +vireo.controller('ResetPasswordController', function ($controller, $location, $scope, $window, PasswordResetService, StorageService) { angular.extend(this, $controller('AbstractController', { $scope: $scope })); @@ -19,8 +19,14 @@ vireo.controller('ResetPasswordController', function ($controller, $location, $s $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. - StorageService.set('post_authorize_url', '/myprofile'); + // 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'); }