Prevent bcrypt from raising a ValueError and log (#19078)

This commit is contained in:
Andrew Morgan 2025-10-21 11:52:28 +02:00 committed by GitHub
parent eac862629f
commit 418c9f3fe5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 27 additions and 2 deletions

1
changelog.d/19078.bugfix Normal file
View File

@ -0,0 +1 @@
Fix a bug introduced in 1.140.0 where an internal server error could be raised when hashing user passwords that are too long.

View File

@ -73,8 +73,18 @@ def main() -> None:
pw = unicodedata.normalize("NFKC", password)
bytes_to_hash = pw.encode("utf8") + password_pepper.encode("utf8")
if len(bytes_to_hash) > 72:
# bcrypt only looks at the first 72 bytes
print(
f"Password is too long ({len(bytes_to_hash)} bytes); truncating to 72 bytes for bcrypt. "
"This is expected behaviour and will not affect a user's ability to log in. 72 bytes is "
"sufficient entropy for a password."
)
bytes_to_hash = bytes_to_hash[:72]
hashed = bcrypt.hashpw(
pw.encode("utf8") + password_pepper.encode("utf8"),
bytes_to_hash,
bcrypt.gensalt(bcrypt_rounds),
).decode("ascii")

View File

@ -1683,8 +1683,22 @@ class AuthHandler:
# Normalise the Unicode in the password
pw = unicodedata.normalize("NFKC", password)
bytes_to_hash = pw.encode(
"utf8"
) + self.hs.config.auth.password_pepper.encode("utf8")
if len(bytes_to_hash) > 72:
# bcrypt only looks at the first 72 bytes.
#
# Note: we explicitly DO NOT log the length of the user's password here.
logger.debug(
"Password is too long; truncating to 72 bytes for bcrypt. "
"This is expected behaviour and will not affect a user's ability to log in. 72 bytes is "
"sufficient entropy for a password."
)
bytes_to_hash = bytes_to_hash[:72]
return bcrypt.hashpw(
pw.encode("utf8") + self.hs.config.auth.password_pepper.encode("utf8"),
bytes_to_hash,
bcrypt.gensalt(self.bcrypt_rounds),
).decode("ascii")