diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java index 3e1886af3c..883f9872ec 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/core/security/RollerPasswordEncoders.java @@ -17,7 +17,7 @@ package org.apache.roller.weblogger.ui.core.security; - +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; @@ -130,9 +130,22 @@ public static PasswordEncoder create() { */ private record ExternalLoginAware(PasswordEncoder delegate) implements PasswordEncoder { + /** + * Returns null for a password that BCrypt refuses as too long. A + * login re-encodes the password it has just checked against an older + * encoding, and for such a password that login has to succeed and + * leave the stored password as it is. + */ @Override public String encode(CharSequence rawPassword) { - return delegate.encode(rawPassword); + try { + return delegate.encode(rawPassword); + } catch (IllegalArgumentException e) { + if (rawPassword != null && isTooLong(rawPassword.toString())) { + return null; + } + throw e; + } } @Override @@ -161,4 +174,21 @@ public boolean upgradeEncoding(String encodedPassword) { public static String randomUnusedPassword() { return RandomStringUtils.secure().nextAlphanumeric(64); } + + /** + * The longest password, in UTF-8 bytes, that BCrypt accepts. PBKDF2, + * SCrypt and Argon2 take longer ones, but the limit applies whatever the + * algorithm, so that a site can switch to BCrypt, the default, without + * leaving passwords it can't re-encode. + */ + public static final int MAX_PASSWORD_BYTES = 72; + + /** + * Returns true when a typed password is longer than an encoder accepts, so + * that a form can say so instead of failing when the password is encoded. + */ + public static boolean isTooLong(String password) { + return password != null + && password.getBytes(StandardCharsets.UTF_8).length > MAX_PASSWORD_BYTES; + } } diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java index 7e66fb9959..aedf671f90 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/admin/UserEdit.java @@ -231,7 +231,10 @@ private boolean isAdd() { return actionName.equals("createUser"); } - private void myValidate() { + void myValidate() { + if (RollerPasswordEncoders.isTooLong(getBean().getPassword())) { + addError("userRegister.error.passwordTooLong"); + } // the external-login marker never matches at login if (RollerPasswordEncoders.isExternalLoginMarker(getBean().getPassword())) { addError("error.add.user.reservedPassword"); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java index 49bccca2ae..a4d69cc32d 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Profile.java @@ -135,6 +135,9 @@ public String save() { } public void myValidate() { + if (RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { + addError("userRegister.error.passwordTooLong"); + } // the external-login marker never matches at login if (RollerPasswordEncoders.isExternalLoginMarker(getBean().getPasswordText())) { addError("error.add.user.reservedPassword"); diff --git a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java index 7f89da85fc..78ad48c98e 100644 --- a/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java +++ b/app/src/main/java/org/apache/roller/weblogger/ui/struts2/core/Register.java @@ -70,6 +70,10 @@ public class Register extends UIAction { private String activationCode = null; private ProfileBean bean = new ProfileBean(); + // generated for OIDC users, kept out of the bean so that the form never + // renders it + private String unusedPassword = null; + public Register() { this.pageTitle = "newUser.addNewUser"; } @@ -212,7 +216,9 @@ public String save() { ud.setEnabled(Boolean.TRUE); // If user set both password and passwordConfirm then reset password - if (!StringUtils.isEmpty(getBean().getPasswordText()) && + if (unusedPassword != null) { + ud.resetPassword(unusedPassword); + } else if (!StringUtils.isEmpty(getBean().getPasswordText()) && !StringUtils.isEmpty(getBean().getPasswordConfirm())) { ud.resetPassword(getBean().getPasswordText()); } @@ -414,29 +420,35 @@ public void myValidate() { } // check password, it is required if OpenID and SSO are disabled - if (AuthMethod.ROLLERDB.name().equals(getAuthMethod()) + if ((AuthMethod.ROLLERDB.name().equals(getAuthMethod()) + || (AuthMethod.DB_OIDC.name().equals(getAuthMethod()) + && StringUtils.isEmpty(getBean().getOpenIdUrl()))) && StringUtils.isEmpty(getBean().getPasswordText())) { - addError("error.add.user.passwordEmpty"); + addError("error.add.user.missingPassword"); return; } // User.password does not allow null, so generate one for OIDC users + unusedPassword = null; if (getAuthMethod().equals(AuthMethod.OIDC.name()) || (getAuthMethod().equals(AuthMethod.DB_OIDC.name()) && !StringUtils.isEmpty(getBean().getOpenIdUrl()))) { - String randomString = RollerPasswordEncoders.randomUnusedPassword(); - getBean().setPasswordText(randomString); - getBean().setPasswordConfirm(randomString); - } - - // the external-login marker is stored for users who log in elsewhere - // and never matches at login - if (!usingSSO && RollerPasswordEncoders.isExternalLoginMarker(getBean().getPasswordText())) { - addError("error.add.user.reservedPassword"); - } + unusedPassword = RollerPasswordEncoders.randomUnusedPassword(); + } else { + // (with LDAP or CMA the bean holds the marker, not a typed password) + if (!usingSSO && RollerPasswordEncoders.isTooLong(getBean().getPasswordText())) { + addError("userRegister.error.passwordTooLong"); + } + + // the external-login marker is stored for users who log in + // elsewhere and never matches at login + if (!usingSSO && RollerPasswordEncoders.isExternalLoginMarker(getBean().getPasswordText())) { + addError("error.add.user.reservedPassword"); + } - // check that passwords match - if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { - addError("userRegister.error.mismatchedPasswords"); + // check that passwords match + if (!StringUtils.equals(getBean().getPasswordText(), getBean().getPasswordConfirm())) { + addError("userRegister.error.mismatchedPasswords"); + } } // check that username is not taken diff --git a/app/src/main/resources/ApplicationResources.properties b/app/src/main/resources/ApplicationResources.properties index deb045f0c0..574e03c6ff 100644 --- a/app/src/main/resources/ApplicationResources.properties +++ b/app/src/main/resources/ApplicationResources.properties @@ -1522,6 +1522,7 @@ userRegister.button.save=Sign Up userRegister.success.ready=Yes, form appears to be complete. Click the button below. userRegister.error.mismatchedPasswords=Your passwords do not match! +userRegister.error.passwordTooLong=Your password is too long. Accented letters, non-Latin characters and emoji take up more room than other characters, so use fewer of them or a shorter password. userRegister.error.missingOpenID=Open ID URL must be provided. userRegister.error.missingOpenIDOrPassword=Either an Open ID URL or a password must be provided. userRegister.error.bothOpenIDAndPassword=Please supply just a password or an OpenID (not both). diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java index f38522b300..06a18cfca9 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/core/security/PasswordUpgradeTest.java @@ -100,6 +100,25 @@ void successfulLoginStoresTheConfiguredEncoding() throws Exception { assertEquals(stored, storedPassword(), "an up-to-date hash is left alone"); } + @Test + void aPasswordTooLongToReEncodeStillLogsIn() throws Exception { + // 73 bytes, one more than BCrypt encodes + String longPassword = "a".repeat(73); + String longHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-1") + .digest(longPassword.getBytes(StandardCharsets.UTF_8))); + UserManager mgr = WebloggerFactory.getWeblogger().getUserManager(); + User user = mgr.getUserByUserName(userName); + user.setPassword(longHash); + mgr.saveUser(user); + TestUtils.endSession(true); + + assertTrue(provider().authenticate(UsernamePasswordAuthenticationToken.unauthenticated( + userName, longPassword)).isAuthenticated()); + TestUtils.endSession(true); + + assertEquals(longHash, storedPassword()); + } + @Test void failedLoginLeavesThePasswordAlone() throws Exception { assertThrows(BadCredentialsException.class, () -> provider().authenticate( diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/admin/UserEditPasswordLengthTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/admin/UserEditPasswordLengthTest.java new file mode 100644 index 0000000000..56e1c8a7ba --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/admin/UserEditPasswordLengthTest.java @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.roller.weblogger.ui.struts2.admin; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class UserEditPasswordLengthTest { + + @Test + void rejectsPasswordTooLongToEncode() { + UserEdit action = new UserEdit() { + @Override + public String getText(String key) { + return key; + } + }; + action.setActionName("createUser"); + action.getBean().setUserName("emoji"); + // 20 emoji, 80 bytes in UTF-8 + action.getBean().setPassword("😀".repeat(20)); + action.myValidate(); + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + assertEquals(1, action.getActionErrors().size(), action.getActionErrors().toString()); + } +} diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java index a76f131f59..3e68e8aec5 100644 --- a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/ExternalLoginMarkerPasswordTest.java @@ -127,7 +127,7 @@ void registrationAcceptsAnOrdinaryPassword() { @Test void registrationWithoutAPasswordDoesNotFail() throws Exception { - // db-oidc does not require a password when the form is validated + // neither a password nor an OpenID URL is typed setProperty("authentication.method", "db-oidc"); Register action = withText(new Register()); action.getBean().setUserName("newuser"); diff --git a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java new file mode 100644 index 0000000000..bd8dac1f08 --- /dev/null +++ b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/core/PasswordFormValidationTest.java @@ -0,0 +1,240 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.roller.weblogger.ui.struts2.core; + +import java.io.InputStream; +import java.lang.reflect.Field; +import java.util.List; +import java.util.Properties; + +import jakarta.servlet.http.HttpServletRequest; + +import org.apache.roller.weblogger.business.UserManager; +import org.apache.roller.weblogger.business.Weblogger; +import org.apache.roller.weblogger.business.WebloggerFactory; +import org.apache.roller.weblogger.config.AuthMethod; +import org.apache.roller.weblogger.config.WebloggerConfig; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.when; + +/** + * Passwords that the encoder can't take get a form error, and a password + * generated for an OIDC user is never put in the form. + */ +class PasswordFormValidationTest { + + // 20 emoji, 80 bytes in UTF-8 + private static final String TOO_LONG = "😀".repeat(20); + // 72 bytes in UTF-8 + private static final String LONGEST = "a".repeat(72); + private static final String MARKER = "users.passwords.externalAuthValue"; + + @Test + void profileRejectsPasswordTooLongToEncode() { + Profile action = new Profile() { + @Override + public String getText(String key) { + return key; + } + }; + action.getBean().setPasswordText(TOO_LONG); + action.getBean().setPasswordConfirm(TOO_LONG); + action.myValidate(); + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + + @Test + void profileRejectsPasswordTooLongToEncodeWithOpenIdUrl() { + Profile action = new Profile() { + @Override + public String getText(String key) { + return key; + } + }; + action.getBean().setOpenIdUrl("https://idp.example.com#emoji"); + action.getBean().setPasswordText(TOO_LONG); + action.getBean().setPasswordConfirm(TOO_LONG); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } catch (Exception e) { + throw new AssertionError(e); + } + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + + @Test + void profileAcceptsLongestPassword() { + Profile action = new Profile() { + @Override + public String getText(String key) { + return key; + } + }; + action.getBean().setPasswordText(LONGEST); + action.getBean().setPasswordConfirm(LONGEST); + action.myValidate(); + assertFalse(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + + @Test + void registerRejectsPasswordTooLongToEncode() throws Exception { + Register action = register(AuthMethod.ROLLERDB); + action.getBean().setUserName("emoji"); + action.getBean().setPasswordText(TOO_LONG); + action.getBean().setPasswordConfirm(TOO_LONG); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + } + + @Test + void registerReportsATakenUserNameWithATooLongPassword() throws Exception { + Register action = register(AuthMethod.ROLLERDB); + action.getBean().setUserName("taken"); + action.getBean().setPasswordText(TOO_LONG); + action.getBean().setPasswordConfirm(TOO_LONG + "x"); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + assertTrue(action.getActionErrors().contains("userRegister.error.passwordTooLong")); + assertTrue(action.getActionErrors().contains("userRegister.error.mismatchedPasswords")); + assertTrue(action.getActionErrors().contains("error.add.user.userNameInUse")); + } + + @Test + void registerRequiresAPasswordInDatabaseMode() throws Exception { + Register action = register(AuthMethod.ROLLERDB); + action.getBean().setUserName("nopassword"); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + assertEquals(List.of("error.add.user.missingPassword"), List.copyOf(action.getActionErrors())); + assertTrue(messages().containsKey("error.add.user.missingPassword")); + } + + @Test + void registerRequiresAPasswordWithoutAnOpenIdUrl() throws Exception { + Register action = register(AuthMethod.DB_OIDC); + action.getBean().setUserName("nopassword"); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + assertEquals(List.of("error.add.user.missingPassword"), List.copyOf(action.getActionErrors())); + } + + @Test + void registerDoesNotMeasureThePlaceholderOfAnExternalLogin() throws Exception { + Properties config = config(); + String saved = config.getProperty(MARKER); + // longer than a typed password may be + config.setProperty(MARKER, "x".repeat(80)); + try (MockedStatic factory = mockUserManager()) { + HttpServletRequest request = mock(HttpServletRequest.class); + when(request.getUserPrincipal()).thenReturn(() -> "cmauser"); + Register action = new Register() { + @Override + public String getText(String key) { + return key; + } + + @Override + protected HttpServletRequest getServletRequest() { + return request; + } + }; + setAuthMethod(action, AuthMethod.CMA); + + action.myValidate(); + + assertEquals("cmauser", action.getBean().getUserName()); + assertFalse(action.hasActionErrors(), action.getActionErrors().toString()); + } finally { + if (saved == null) { + config.remove(MARKER); + } else { + config.setProperty(MARKER, saved); + } + } + } + + @Test + void registerKeepsGeneratedPasswordOutOfTheForm() throws Exception { + Register action = register(AuthMethod.DB_OIDC); + action.getBean().setUserName("taken"); + action.getBean().setOpenIdUrl("https://idp.example.com#taken"); + try (MockedStatic factory = mockUserManager()) { + action.myValidate(); + } + // the form is shown again with an error, and must not carry the password + assertTrue(action.getActionErrors().contains("error.add.user.userNameInUse")); + assertNull(action.getBean().getPasswordText()); + assertNull(action.getBean().getPasswordConfirm()); + assertNull(action.getBean().getPassword()); + } + + private static Register register(AuthMethod authMethod) throws Exception { + Register action = new Register() { + @Override + public String getText(String key) { + return key; + } + }; + setAuthMethod(action, authMethod); + return action; + } + + private static void setAuthMethod(Register action, AuthMethod authMethod) throws Exception { + Field field = Register.class.getDeclaredField("authMethod"); + field.setAccessible(true); + field.set(action, authMethod); + } + + private static Properties config() throws ReflectiveOperationException { + Field field = WebloggerConfig.class.getDeclaredField("config"); + field.setAccessible(true); + return (Properties) field.get(null); + } + + private static Properties messages() throws Exception { + Properties messages = new Properties(); + try (InputStream in = Register.class.getResourceAsStream("/ApplicationResources.properties")) { + messages.load(in); + } + return messages; + } + + private static MockedStatic mockUserManager() throws Exception { + UserManager userManager = mock(UserManager.class); + when(userManager.getUserByUserName("taken", null)) + .thenReturn(new org.apache.roller.weblogger.pojos.User()); + Weblogger weblogger = mock(Weblogger.class); + when(weblogger.getUserManager()).thenReturn(userManager); + MockedStatic factory = mockStatic(WebloggerFactory.class); + factory.when(WebloggerFactory::getWeblogger).thenReturn(weblogger); + return factory; + } +}