From 1860ab2a16269e7861f62b1c29124f888d6cd368 Mon Sep 17 00:00:00 2001 From: Joao Gilberto Magalhaes Date: Thu, 29 Oct 2026 18:42:58 -0400 Subject: [PATCH 1/2] Hash passwords with bcrypt by default, still reading SHA-1 hashes - PasswordBcryptMapper is UserModel's default: a 60-character hash is bcrypt, a 40-character one SHA-1, so existing users keep logging in; new and changed passwords get bcrypt - PasswordMapperInterface: verifyPassword() and needsRehash(); isValidUser() verifies with the mapper instead of comparing hashes with === - UserModel::setPassword() asks the mapper whether a value is a hash (was strlen != 40) - PasswordSha1Mapper stays selectable and compares with hash_equals() --- CHANGELOG-7.0.md | 18 +++ docs/authentication.md | 30 ++++- docs/custom-fields.md | 2 +- docs/database-storage.md | 12 +- docs/mappers.md | 7 +- docs/user-management.md | 24 ++-- src/Interfaces/PasswordMapperInterface.php | 13 +++ src/MapperFunctions/PasswordBcryptMapper.php | 66 +++++++++++ src/MapperFunctions/PasswordSha1Mapper.php | 15 ++- src/Model/UserModel.php | 21 +++- src/Service/UsersService.php | 21 +++- tests/Fixture/PasswordMd5Mapper.php | 12 ++ tests/PasswordBcryptMapperTest.php | 70 ++++++++++++ tests/PasswordUpgradeTest.php | 104 ++++++++++++++++++ tests/TestUsersBase.php | 6 +- .../UsersDBDatasetByUsernameTestUsersBase.php | 5 +- 16 files changed, 388 insertions(+), 38 deletions(-) create mode 100644 src/MapperFunctions/PasswordBcryptMapper.php create mode 100644 tests/PasswordBcryptMapperTest.php create mode 100644 tests/PasswordUpgradeTest.php diff --git a/CHANGELOG-7.0.md b/CHANGELOG-7.0.md index 2a719ed..97b1c3b 100644 --- a/CHANGELOG-7.0.md +++ b/CHANGELOG-7.0.md @@ -16,6 +16,24 @@ to fix the user id conversion in `UserPropertiesRepository` (see Bug Fixes). ## Breaking Changes +### Passwords are hashed with bcrypt + +`UserModel` hashes passwords with the new `PasswordBcryptMapper` instead of `PasswordSha1Mapper` +(unsalted SHA-1). + +- **Widen the password column** to `VARCHAR(255)`: a bcrypt hash has 60 characters, and a new user + or a changed password does not fit in the `CHAR(40)` of a SHA-1 column. +- **Existing users keep logging in.** The bcrypt mapper verifies a 40-character SHA-1 hash too, and + `UsersService::isValidUser()` replaces it with a bcrypt hash at that user's next successful login. +- **To keep SHA-1**, select `PasswordSha1Mapper` on the password field of your user model: + `#[FieldAttribute(updateFunction: PasswordSha1Mapper::class)]`. +- **Custom password mappers** implement two new methods of `PasswordMapperInterface`: + `verifyPassword(string $password, string $hash): bool` and `needsRehash(string $hash): bool`. + `isValidUser()` uses them instead of comparing the hash of the password with `===`; a SHA-1 or + MD5 mapper verifies with `hash_equals()` and returns `false` from `needsRehash()`. +- `UserModel::setPassword()` asks the password mapper whether a value is already a hash (it skipped + the password definition for any 40-character value). + ### Dependencies | Package | 6.x | 7.0 | diff --git a/docs/authentication.md b/docs/authentication.md index 8123fd7..bfbde43 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -28,7 +28,8 @@ The `isValidUser()` method uses the login field configured in your `UsersService ## Password Hashing -By default, passwords are automatically hashed using SHA-1 when saved. The library uses the `PasswordSha1Mapper` for this purpose. +By default, passwords are hashed with bcrypt when saved, by the `PasswordBcryptMapper` of +`UserModel`. The password column needs 60 characters; `VARCHAR(255)` leaves room for other algorithms. ```php setPassword('plaintext password'); $users->save($user); -// The password is stored as SHA-1 hash in the database +// The password is stored as a bcrypt hash ($2y$...) in the database ``` -:::warning SHA-1 Deprecation -SHA-1 is used for backward compatibility. For new projects, consider implementing a custom password hasher using bcrypt or Argon2. See [Mappers](mappers.md) for details. +The bcrypt mapper also reads the SHA-1 hashes of `PasswordSha1Mapper`, the default before 7.0: a +stored 40-character hash still logs in, and `isValidUser()` replaces it with a bcrypt hash at that +login. Users move to bcrypt as they log in, without a password reset. A bcrypt hash with a lower cost +than PHP's current one is replaced the same way. + +To keep SHA-1, select its mapper in your user model: + +```php +isPasswordEncrypted($value)) { + return $value; + } + + // Leave null + if (empty($value)) { + return null; + } + + return password_hash((string)$value, PASSWORD_BCRYPT); + } + + #[\Override] + public function isPasswordEncrypted(mixed $password): bool + { + return is_string($password) && ($this->isBcrypt($password) || $this->isSha1($password)); + } + + #[\Override] + public function verifyPassword(string $password, string $hash): bool + { + if ($this->isBcrypt($hash)) { + return password_verify($password, $hash); + } + if ($this->isSha1($hash)) { + return hash_equals(strtolower($hash), sha1($password)); + } + return false; + } + + #[\Override] + public function needsRehash(string $hash): bool + { + return !$this->isBcrypt($hash) || password_needs_rehash($hash, PASSWORD_BCRYPT); + } + + private function isBcrypt(string $hash): bool + { + return strlen($hash) === 60 && password_get_info($hash)['algo'] === PASSWORD_BCRYPT; + } + + private function isSha1(string $hash): bool + { + return strlen($hash) === 40 && ctype_xdigit($hash); + } +} diff --git a/src/MapperFunctions/PasswordSha1Mapper.php b/src/MapperFunctions/PasswordSha1Mapper.php index db3b79d..7558e4e 100644 --- a/src/MapperFunctions/PasswordSha1Mapper.php +++ b/src/MapperFunctions/PasswordSha1Mapper.php @@ -6,7 +6,8 @@ use ByJG\Authenticate\Interfaces\PasswordMapperInterface; /** - * Mapper function to hash passwords using SHA1 + * Mapper function to hash passwords using SHA1 (unsalted). PasswordBcryptMapper, the default, + * also reads these hashes and upgrades them; select this mapper only to keep SHA-1. */ class PasswordSha1Mapper implements PasswordMapperInterface { @@ -32,4 +33,16 @@ public function isPasswordEncrypted(mixed $password): bool { return (is_string($password) && strlen($password) === 40); } + + #[\Override] + public function verifyPassword(string $password, string $hash): bool + { + return hash_equals(strtolower($hash), sha1($password)); + } + + #[\Override] + public function needsRehash(string $hash): bool + { + return false; + } } diff --git a/src/Model/UserModel.php b/src/Model/UserModel.php index 85ccdc8..cd5ffc3 100644 --- a/src/Model/UserModel.php +++ b/src/Model/UserModel.php @@ -3,7 +3,7 @@ namespace ByJG\Authenticate\Model; use ByJG\Authenticate\Definition\PasswordDefinition; -use ByJG\Authenticate\MapperFunctions\PasswordSha1Mapper; +use ByJG\Authenticate\MapperFunctions\PasswordBcryptMapper; use ByJG\MicroOrm\Attributes\FieldAttribute; use ByJG\MicroOrm\Attributes\TableAttribute; use ByJG\MicroOrm\Literal\Literal; @@ -30,7 +30,7 @@ class UserModel #[FieldAttribute] protected ?string $username = null; - #[FieldAttribute(updateFunction: PasswordSha1Mapper::class)] + #[FieldAttribute(updateFunction: PasswordBcryptMapper::class)] protected ?string $password = null; #[FieldAttribute] @@ -136,8 +136,8 @@ public function getPassword(): ?string */ public function setPassword(?string $password): void { - // Password len equals to 40 means that the password is already encrypted with sha1 - if (!empty($this->passwordDefinition) && !empty($password) && strlen($password) != 40) { + // A hash (read from the database) is not checked against the password definition + if (!empty($this->passwordDefinition) && !empty($password) && !$this->isPasswordHash($password)) { $match = $this->passwordDefinition->matchPassword($password); if ($match != PasswordDefinition::SUCCESS) { throw new InvalidArgumentException("Password does not match the password definition [$match]"); @@ -147,6 +147,19 @@ public function setPassword(?string $password): void $this->password = $password; } + /** + * Whether the value is a hash, by the password mapper UsersService registers on the + * password definition; the default mapper when there is none. + */ + protected function isPasswordHash(string $password): bool + { + $mapper = $this->passwordDefinition?->getPasswordMapper() ?? PasswordBcryptMapper::class; + if (is_string($mapper)) { + $mapper = new $mapper(); + } + return $mapper->isPasswordEncrypted($password); + } + /** * @return string|null */ diff --git a/src/Service/UsersService.php b/src/Service/UsersService.php index c706e5e..7138cce 100644 --- a/src/Service/UsersService.php +++ b/src/Service/UsersService.php @@ -348,18 +348,29 @@ public function isValidUser(string $login, string $password): ?UserModel return null; } - // Hash the password for comparison using the model's configured password mapper + // The model's password mapper verifies the password against the stored hash $passwordFieldMapping = $this->usersRepository->getMapper()->getFieldMap(UserField::Password->value); if ($passwordFieldMapping === null) { throw new InvalidArgumentException('Password field mapping not found'); } - $hashedPassword = $passwordFieldMapping->getUpdateFunctionValue($password, null); + $mapper = $passwordFieldMapping->getUpdateFunction(); + if (is_string($mapper)) { + $mapper = new $mapper(); + } + /** @var PasswordMapperInterface $mapper The constructor checks it */ + $hash = (string)$user->getPassword(); + if (!$mapper->verifyPassword($password, $hash)) { + return null; + } - if ($user->getPassword() === $hashedPassword) { - return $user; + // An older hash (SHA-1, or bcrypt with a lower cost) is replaced now that the password is known. + // The new hash is set directly: an existing password is not checked against the definition. + if ($mapper->needsRehash($hash)) { + $user->setPassword((string)$mapper->processedValue($password, $user)); + $this->usersRepository->save($user); } - return null; + return $user; } /** diff --git a/tests/Fixture/PasswordMd5Mapper.php b/tests/Fixture/PasswordMd5Mapper.php index e845549..3c6709e 100644 --- a/tests/Fixture/PasswordMd5Mapper.php +++ b/tests/Fixture/PasswordMd5Mapper.php @@ -32,4 +32,16 @@ public function isPasswordEncrypted(mixed $password): bool { return is_string($password) && strlen($password) === 32 && ctype_xdigit($password); } + + #[\Override] + public function verifyPassword(string $password, string $hash): bool + { + return hash_equals(strtolower($hash), md5($password)); + } + + #[\Override] + public function needsRehash(string $hash): bool + { + return false; + } } diff --git a/tests/PasswordBcryptMapperTest.php b/tests/PasswordBcryptMapperTest.php new file mode 100644 index 0000000..c3c0fcc --- /dev/null +++ b/tests/PasswordBcryptMapperTest.php @@ -0,0 +1,70 @@ +mapper = new PasswordBcryptMapper(); + } + + public function testHashesWithBcrypt(): void + { + $hash = (string)$this->mapper->processedValue('mySecret1', null); + + $this->assertSame(PASSWORD_BCRYPT, password_get_info($hash)['algo']); + $this->assertSame(60, strlen($hash)); + $this->assertNotSame($hash, $this->mapper->processedValue('mySecret1', null), 'bcrypt salts every hash'); + } + + public function testKeepsAHashAsIs(): void + { + $bcrypt = password_hash('mySecret1', PASSWORD_BCRYPT); + $sha1 = sha1('mySecret1'); + + $this->assertSame($bcrypt, $this->mapper->processedValue($bcrypt, null)); + $this->assertSame($sha1, $this->mapper->processedValue($sha1, null)); + $this->assertNull($this->mapper->processedValue('', null)); + } + + public function testRecognizesHashes(): void + { + $this->assertTrue($this->mapper->isPasswordEncrypted(password_hash('x', PASSWORD_BCRYPT))); + $this->assertTrue($this->mapper->isPasswordEncrypted(sha1('x'))); + $this->assertFalse($this->mapper->isPasswordEncrypted('mySecret1')); + $this->assertFalse($this->mapper->isPasswordEncrypted(str_repeat('z', 40)), '40 characters but not hexadecimal'); + $this->assertFalse($this->mapper->isPasswordEncrypted(str_repeat('z', 60)), '60 characters but not bcrypt'); + } + + public function testVerifiesBcrypt(): void + { + $hash = password_hash('mySecret1', PASSWORD_BCRYPT); + + $this->assertTrue($this->mapper->verifyPassword('mySecret1', $hash)); + $this->assertFalse($this->mapper->verifyPassword('wrong', $hash)); + } + + public function testVerifiesSha1(): void + { + $hash = sha1('mySecret1'); + + $this->assertTrue($this->mapper->verifyPassword('mySecret1', $hash)); + $this->assertTrue($this->mapper->verifyPassword('mySecret1', strtoupper($hash))); + $this->assertFalse($this->mapper->verifyPassword('wrong', $hash)); + $this->assertFalse($this->mapper->verifyPassword('mySecret1', 'not a hash')); + } + + public function testNeedsRehash(): void + { + $this->assertTrue($this->mapper->needsRehash(sha1('mySecret1')), 'SHA-1 is upgraded'); + $this->assertTrue($this->mapper->needsRehash(password_hash('mySecret1', PASSWORD_BCRYPT, ['cost' => 4])), 'a lower cost is upgraded'); + $this->assertFalse($this->mapper->needsRehash(password_hash('mySecret1', PASSWORD_BCRYPT))); + } +} diff --git a/tests/PasswordUpgradeTest.php b/tests/PasswordUpgradeTest.php new file mode 100644 index 0000000..9f89a8a --- /dev/null +++ b/tests/PasswordUpgradeTest.php @@ -0,0 +1,104 @@ +executor = DatabaseExecutor::using(Factory::getDbInstance(self::CONNECTION_STRING)); + $this->executor->execute('create table users ( + userid integer primary key autoincrement, + name varchar(45), + email varchar(200), + username varchar(20), + password varchar(255), + created_at datetime default (datetime(\'2017-12-04\')), + updated_at datetime, + deleted_at datetime, + role varchar(20));' + ); + $this->executor->execute('create table users_property ( + id integer primary key autoincrement, + userid integer, + name varchar(45), + value varchar(45));' + ); + + // A user saved by an older version: SHA-1, and a password weaker than today's definition + $this->executor->execute( + "insert into users (name, email, username, password, role) values ('Old User', 'old@example.com', 'old', '" . sha1('old') . "', 'user')" + ); + + $this->service = new UsersService( + new UsersRepository($this->executor, UserModel::class), + new UserPropertiesRepository($this->executor, UserPropertiesModel::class), + LoginField::Username, + new PasswordDefinition() + ); + } + + #[\Override] + protected function tearDown(): void + { + unlink('/tmp/teste_upgrade.db'); + } + + private function storedPassword(): string + { + return (string)$this->executor->getScalar("select password from users where username = 'old'"); + } + + public function testSha1PasswordLogsInAndIsUpgradedToBcrypt(): void + { + $user = $this->service->isValidUser('old', 'old'); + + $this->assertNotNull($user); + $this->assertSame('old', $user->getUsername()); + $this->assertSame(PASSWORD_BCRYPT, password_get_info($this->storedPassword())['algo']); + $this->assertTrue(password_verify('old', $this->storedPassword())); + + // And the next login uses the bcrypt hash + $this->assertNotNull($this->service->isValidUser('old', 'old')); + } + + public function testWrongPasswordIsNotUpgraded(): void + { + $this->assertNull($this->service->isValidUser('old', 'wrong')); + $this->assertSame(sha1('old'), $this->storedPassword()); + } + + /** + * A model with a password definition (as Gluo's BaseUser sets in its constructor) is given the + * stored hash when it is loaded: a hash is not checked against the definition + */ + public function testAStoredHashIsNotCheckedAgainstTheDefinition(): void + { + $definition = new PasswordDefinition([PasswordDefinition::MINIMUM_CHARS => 100]); + foreach ([password_hash('old', PASSWORD_BCRYPT), sha1('old')] as $hash) { + $user = (new UserModel())->withPasswordDefinition($definition); + $user->setPassword($hash); + $this->assertSame($hash, $user->getPassword()); + } + } +} diff --git a/tests/TestUsersBase.php b/tests/TestUsersBase.php index 9d47b70..d0c4d54 100644 --- a/tests/TestUsersBase.php +++ b/tests/TestUsersBase.php @@ -470,7 +470,9 @@ public function testGetByUsername(): void $this->assertEquals('User 2', $user->getName()); $this->assertEquals('user2', $user->getUsername()); $this->assertEquals('user2@gmail.com', $user->getEmail()); - $this->assertEquals('c88b5c841897dafe75cdd9f8ba98b32f007d6bc3', $user->getPassword()); + // The stored hash is the one of pwd2, whatever the model's password mapper + $this->assertNotEquals('pwd2', $user->getPassword()); + $this->assertEquals($user->getUserid(), $this->object->isValidUser($this->__chooseValue('user2', 'user2@gmail.com'), 'pwd2')?->getUserid()); } public function testGetByUserProperty(): void @@ -706,7 +708,7 @@ public function testPasswordHashRemainsUnchangedOnSave(): void // Store the original password hash $originalHash = $user->getPassword(); - $this->assertEquals($originalHash, sha1($originalPassword)); + $this->assertNotEquals($originalPassword, $originalHash); // Verify the user can authenticate with the original password $login = $this->__chooseValue('testuser', 'test@example.com'); diff --git a/tests/UsersDBDatasetByUsernameTestUsersBase.php b/tests/UsersDBDatasetByUsernameTestUsersBase.php index 3c9f2e1..f70cf19 100644 --- a/tests/UsersDBDatasetByUsernameTestUsersBase.php +++ b/tests/UsersDBDatasetByUsernameTestUsersBase.php @@ -58,7 +58,8 @@ public function __setUp($loginField) $this->assertEquals(1, $user->getUserid()); $this->assertEquals('User 1', $user->getName()); $this->assertEquals('user1', $user->getUsername()); - $this->assertEquals('a63d4b132a9a1d3430f9ae507825f572449e0d17', $user->getPassword()); + // UserModel hashes with bcrypt by default + $this->assertSame(PASSWORD_BCRYPT, password_get_info((string)$user->getPassword())['algo']); $this->assertEquals('', $user->getRole()); $this->assertNotNull($user->getCreatedAt()); $this->assertMatchesRegularExpression('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $user->getCreatedAt()); @@ -96,7 +97,7 @@ public function testAddUser() $this->assertEquals('John Doe', $user->getName()); $this->assertEquals('john', $user->getUsername()); $this->assertEquals('johndoe@gmail.com', $user->getEmail()); - $this->assertEquals('91dfd9ddb4198affc5c194cd8ce6d338fde470e2', $user->getPassword()); + $this->assertSame(PASSWORD_BCRYPT, password_get_info((string)$user->getPassword())['algo']); $this->assertEquals('', $user->getRole()); $this->assertNotNull($user->getCreatedAt()); $this->assertMatchesRegularExpression('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $user->getCreatedAt()); From 8eec8d43378c4bc5d56f789d16be1072fe0197b9 Mon Sep 17 00:00:00 2001 From: Joao Gilberto Magalhaes Date: Thu, 29 Oct 2026 18:47:32 -0400 Subject: [PATCH 2/2] Upgrade the password hash at login, not in isValidUser() - isValidUser() only checks the password - UsersService::rehashPasswordIfNeeded() replaces an older hash (SHA-1, or bcrypt with a lower cost); createAuthToken() calls it at login - It reads the new hash back and keeps the old one when the column is too short for it (rejected or truncated), so nobody is locked out before the column is widened --- CHANGELOG-7.0.md | 6 +- docs/authentication.md | 20 +++- docs/mappers.md | 5 +- src/Interfaces/UsersServiceInterface.php | 14 +++ src/MapperFunctions/PasswordBcryptMapper.php | 4 +- src/Service/UsersService.php | 60 ++++++++--- tests/PasswordUpgradeTest.php | 106 ++++++++++++++++--- 7 files changed, 179 insertions(+), 36 deletions(-) diff --git a/CHANGELOG-7.0.md b/CHANGELOG-7.0.md index 97b1c3b..93cd53e 100644 --- a/CHANGELOG-7.0.md +++ b/CHANGELOG-7.0.md @@ -24,9 +24,13 @@ to fix the user id conversion in `UserPropertiesRepository` (see Bug Fixes). - **Widen the password column** to `VARCHAR(255)`: a bcrypt hash has 60 characters, and a new user or a changed password does not fit in the `CHAR(40)` of a SHA-1 column. - **Existing users keep logging in.** The bcrypt mapper verifies a 40-character SHA-1 hash too, and - `UsersService::isValidUser()` replaces it with a bcrypt hash at that user's next successful login. + the new `UsersService::rehashPasswordIfNeeded()` replaces it with a bcrypt hash at that user's next + login: `createAuthToken()` calls it; a login of your own calls it after `isValidUser()`, which only + checks the password. It reads the new hash back and keeps the old one when the column is too short + (rejected or truncated), so nobody is locked out before the column is widened. - **To keep SHA-1**, select `PasswordSha1Mapper` on the password field of your user model: `#[FieldAttribute(updateFunction: PasswordSha1Mapper::class)]`. +- `UsersServiceInterface` has the new `rehashPasswordIfNeeded()`. - **Custom password mappers** implement two new methods of `PasswordMapperInterface`: `verifyPassword(string $password, string $hash): bool` and `needsRehash(string $hash): bool`. `isValidUser()` uses them instead of comparing the hash of the password with `===`; a SHA-1 or diff --git a/docs/authentication.md b/docs/authentication.md index bfbde43..f9053b3 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -41,9 +41,23 @@ $users->save($user); ``` The bcrypt mapper also reads the SHA-1 hashes of `PasswordSha1Mapper`, the default before 7.0: a -stored 40-character hash still logs in, and `isValidUser()` replaces it with a bcrypt hash at that -login. Users move to bcrypt as they log in, without a password reset. A bcrypt hash with a lower cost -than PHP's current one is replaced the same way. +stored 40-character hash still logs in. At login, `createAuthToken()` replaces it with a bcrypt hash, +so users move to bcrypt as they log in, without a password reset. A bcrypt hash with a lower cost than +PHP's current one is replaced the same way. `isValidUser()` only checks the password and never writes. + +A login of your own (without `createAuthToken()`) upgrades the hash with `rehashPasswordIfNeeded()`: + +```php +isValidUser($login, $password); +if ($user !== null) { + $users->rehashPasswordIfNeeded($user, $password); +} +``` + +`rehashPasswordIfNeeded()` reads the new hash back. If the password column is too short for it (the +`CHAR(40)` of a SHA-1 schema), the new hash is rejected or truncated by the database; the method then +keeps the old hash and returns `false`, so the user can still log in. Widen the column to upgrade. To keep SHA-1, select its mapper in your user model: diff --git a/docs/mappers.md b/docs/mappers.md index cba444c..d03f204 100644 --- a/docs/mappers.md +++ b/docs/mappers.md @@ -44,12 +44,13 @@ class CustomUserModel extends UserModel This package ships with a few mapper utilities that complement the ones provided by Micro ORM: -- **PasswordBcryptMapper** – hashes passwords with bcrypt (the default on `UserModel`). It also verifies the SHA-1 hashes of `PasswordSha1Mapper`, which `UsersService::isValidUser()` upgrades to bcrypt at the next login. +- **PasswordBcryptMapper** – hashes passwords with bcrypt (the default on `UserModel`). It also verifies the SHA-1 hashes of `PasswordSha1Mapper`, which are upgraded to bcrypt at the next login. - **PasswordSha1Mapper** – hashes passwords with unsalted SHA-1 (the default before 7.0). A password mapper implements `PasswordMapperInterface`: `processedValue()` hashes a plain password, `isPasswordEncrypted()` recognizes a stored hash, `verifyPassword()` checks a password against a hash, - and `needsRehash()` tells `isValidUser()` to replace a hash at a successful login. + and `needsRehash()` tells `UsersService::rehashPasswordIfNeeded()` (called by `createAuthToken()`) + to replace a hash at a successful login. - **UserIdGeneratorMapper** – derives a user ID from the username when the primary key is empty. ```php passwordMapper()->verifyPassword($password, (string)$user->getPassword())) { + return null; + } + + return $user; + } + + /** + * @inheritDoc + */ + #[\Override] + public function rehashPasswordIfNeeded(UserModel $user, string $password): bool + { + $mapper = $this->passwordMapper(); + $oldHash = (string)$user->getPassword(); + if (!$mapper->needsRehash($oldHash)) { + return false; + } + + // Set as a hash: an existing password is not checked against the password definition + $user->setPassword((string)$mapper->processedValue($password, $user)); + try { + $this->usersRepository->save($user); + $stored = $this->usersRepository->getById($user->getUserid() ?? '')?->getPassword(); + if ($mapper->verifyPassword($password, (string)$stored)) { + return true; + } + } catch (Throwable) { + // A column too short for the new hash, in strict mode: nothing was written + } + + // Not stored, or stored truncated (a column too short, without strict mode): keep the old hash + $user->setPassword($oldHash); + $this->usersRepository->save($user); + return false; + } + + /** + * The password mapper of the user model (the constructor checks it is a PasswordMapperInterface) + */ + protected function passwordMapper(): PasswordMapperInterface + { $passwordFieldMapping = $this->usersRepository->getMapper()->getFieldMap(UserField::Password->value); if ($passwordFieldMapping === null) { throw new InvalidArgumentException('Password field mapping not found'); @@ -357,20 +400,8 @@ public function isValidUser(string $login, string $password): ?UserModel if (is_string($mapper)) { $mapper = new $mapper(); } - /** @var PasswordMapperInterface $mapper The constructor checks it */ - $hash = (string)$user->getPassword(); - if (!$mapper->verifyPassword($password, $hash)) { - return null; - } - - // An older hash (SHA-1, or bcrypt with a lower cost) is replaced now that the password is known. - // The new hash is set directly: an existing password is not checked against the definition. - if ($mapper->needsRehash($hash)) { - $user->setPassword((string)$mapper->processedValue($password, $user)); - $this->usersRepository->save($user); - } - - return $user; + /** @var PasswordMapperInterface $mapper */ + return $mapper; } /** @@ -649,6 +680,7 @@ public function createAuthToken( if (is_null($user)) { throw new UserNotFoundException('User not found'); } + $this->rehashPasswordIfNeeded($user, $password); return $this->createInsecureAuthToken( $user, diff --git a/tests/PasswordUpgradeTest.php b/tests/PasswordUpgradeTest.php index 9f89a8a..5e14860 100644 --- a/tests/PasswordUpgradeTest.php +++ b/tests/PasswordUpgradeTest.php @@ -6,11 +6,14 @@ use ByJG\AnyDataset\Db\Factory; use ByJG\Authenticate\Definition\PasswordDefinition; use ByJG\Authenticate\Enum\LoginField; +use ByJG\Authenticate\Exception\UserNotFoundException; use ByJG\Authenticate\Model\UserModel; use ByJG\Authenticate\Model\UserPropertiesModel; use ByJG\Authenticate\Repository\UserPropertiesRepository; use ByJG\Authenticate\Repository\UsersRepository; use ByJG\Authenticate\Service\UsersService; +use ByJG\JwtWrapper\JwtHashHmacSecret; +use ByJG\JwtWrapper\JwtWrapper; use PHPUnit\Framework\TestCase; /** @@ -18,25 +21,28 @@ */ class PasswordUpgradeTest extends TestCase { - const string CONNECTION_STRING = 'sqlite:///tmp/teste_upgrade.db'; + const string DATABASE = '/tmp/teste_upgrade.db'; private DatabaseExecutor $executor; private UsersService $service; - #[\Override] - protected function setUp(): void + /** + * @param string $passwordColumn The password column, as an older schema may have it + * @param string|null $trigger A trigger to create after the tables + */ + private function createDatabase(string $passwordColumn = 'password varchar(255)', ?string $trigger = null): void { - $this->executor = DatabaseExecutor::using(Factory::getDbInstance(self::CONNECTION_STRING)); - $this->executor->execute('create table users ( + $this->executor = DatabaseExecutor::using(Factory::getDbInstance('sqlite://' . self::DATABASE)); + $this->executor->execute("create table users ( userid integer primary key autoincrement, name varchar(45), email varchar(200), username varchar(20), - password varchar(255), - created_at datetime default (datetime(\'2017-12-04\')), + $passwordColumn, + created_at datetime default (datetime('2017-12-04')), updated_at datetime, deleted_at datetime, - role varchar(20));' + role varchar(20));" ); $this->executor->execute('create table users_property ( id integer primary key autoincrement, @@ -44,6 +50,9 @@ protected function setUp(): void name varchar(45), value varchar(45));' ); + if ($trigger !== null) { + $this->executor->execute($trigger); + } // A user saved by an older version: SHA-1, and a password weaker than today's definition $this->executor->execute( @@ -61,7 +70,9 @@ protected function setUp(): void #[\Override] protected function tearDown(): void { - unlink('/tmp/teste_upgrade.db'); + if (file_exists(self::DATABASE)) { + unlink(self::DATABASE); + } } private function storedPassword(): string @@ -69,23 +80,90 @@ private function storedPassword(): string return (string)$this->executor->getScalar("select password from users where username = 'old'"); } - public function testSha1PasswordLogsInAndIsUpgradedToBcrypt(): void + private function login(): void + { + $jwt = new JwtWrapper('api.test.com', new JwtHashHmacSecret(base64_encode(str_repeat('s', 64)))); + $this->service->createAuthToken('old', 'old', $jwt); + } + + public function testIsValidUserDoesNotWrite(): void + { + $this->createDatabase(); + + $this->assertNotNull($this->service->isValidUser('old', 'old')); + $this->assertSame(sha1('old'), $this->storedPassword()); + } + + public function testRehashReplacesASha1Hash(): void { + $this->createDatabase(); $user = $this->service->isValidUser('old', 'old'); - $this->assertNotNull($user); - $this->assertSame('old', $user->getUsername()); + $this->assertTrue($this->service->rehashPasswordIfNeeded($user, 'old')); $this->assertSame(PASSWORD_BCRYPT, password_get_info($this->storedPassword())['algo']); $this->assertTrue(password_verify('old', $this->storedPassword())); + $this->assertNotNull($this->service->isValidUser('old', 'old'), 'the next login uses the bcrypt hash'); + } - // And the next login uses the bcrypt hash - $this->assertNotNull($this->service->isValidUser('old', 'old')); + public function testRehashKeepsACurrentBcryptHash(): void + { + $this->createDatabase(); + $this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old'); + $hash = $this->storedPassword(); + + $this->assertFalse($this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old')); + $this->assertSame($hash, $this->storedPassword()); + } + + public function testLoginUpgradesTheHash(): void + { + $this->createDatabase(); + + $this->login(); + + $this->assertSame(PASSWORD_BCRYPT, password_get_info($this->storedPassword())['algo']); } public function testWrongPasswordIsNotUpgraded(): void { + $this->createDatabase(); + $this->assertNull($this->service->isValidUser('old', 'wrong')); + try { + $jwt = new JwtWrapper('api.test.com', new JwtHashHmacSecret(base64_encode(str_repeat('s', 64)))); + $this->service->createAuthToken('old', 'wrong', $jwt); + $this->fail('A wrong password logged in'); + } catch (UserNotFoundException) { + } + $this->assertSame(sha1('old'), $this->storedPassword()); + } + + /** + * A column that rejects the longer hash (as MySQL does in strict mode): the user keeps SHA-1 + */ + public function testColumnTooShortRejectingTheHash(): void + { + $this->createDatabase('password varchar(40) check (length(password) <= 40)'); + + $this->assertFalse($this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old')); + $this->assertSame(sha1('old'), $this->storedPassword()); + $this->login(); + $this->assertNotNull($this->service->isValidUser('old', 'old'), 'the user can still log in'); + } + + /** + * A column that truncates the longer hash (as MySQL does without strict mode): the SHA-1 hash + * is restored instead of leaving a truncated bcrypt hash nobody can log in with + */ + public function testColumnTooShortTruncatingTheHash(): void + { + $this->createDatabase('password varchar(40)', "create trigger truncate_password after update of password on users + begin update users set password = substr(new.password, 1, 40) where userid = new.userid; end"); + + $this->assertFalse($this->service->rehashPasswordIfNeeded($this->service->isValidUser('old', 'old'), 'old')); $this->assertSame(sha1('old'), $this->storedPassword()); + $this->login(); + $this->assertNotNull($this->service->isValidUser('old', 'old'), 'the user can still log in'); } /**