diff --git a/CHANGELOG-7.0.md b/CHANGELOG-7.0.md index 93cd53e..6f13f77 100644 --- a/CHANGELOG-7.0.md +++ b/CHANGELOG-7.0.md @@ -98,6 +98,13 @@ Not a plain change of casing: `UserField::uUpdated_at` is now `UserField::Update ## Bug Fixes +- A model created with `new UserModel(...)` was saved without checking its password against the + service's `PasswordDefinition` (only users created or loaded by `UsersService` had it). The service + now sets the new `PasswordDefinitionValidator` (a MicroORM `EntityValidatorInterface`) on the users + repository, so every save, also through `UsersRepository` or MicroORM's `Repository`, checks a plain + password and throws `InvalidArgumentException` outside the rules; a stored hash is not checked. + A validator declared on the user model's `TableAttribute` still runs. + - `UserPropertiesRepository` converted the user id for its queries without the database at hand (`getUpdateFunctionValue($userid, null)`), so a UUID user id was always written as `X'…'`. With byjg/micro-orm 7.0, which writes a UUID in the syntax of each database, the diff --git a/docs/password-validation.md b/docs/password-validation.md index 3082d2f..bccd6ce 100644 --- a/docs/password-validation.md +++ b/docs/password-validation.md @@ -29,7 +29,7 @@ $userModel->setPassword('WeakPwd'); // Throws InvalidArgumentException ### Applying Rules Through UsersService -Instead of attaching the definition to every `UserModel` manually, pass it to the `UsersService` constructor. Every entity created through the service (e.g., via `addUser()` or `getUsersEntity()`) receives the same `PasswordDefinition`. +Instead of attaching the definition to every `UserModel` manually, pass it to the `UsersService` constructor. Every entity created or loaded through the service (e.g., via `addUser()`, `getUsersEntity()` or `getById()`) receives the same `PasswordDefinition`, and the service sets a `PasswordDefinitionValidator` on the users repository: every save, also of a model created with `new` and saved through `UsersRepository` or MicroORM's `Repository` directly, checks a plain password against the definition and throws `InvalidArgumentException` when it does not match. A stored hash is never checked. A validator the user model declares (`#[TableAttribute(validator: ...)]`) still runs after it; one set later with `setValidator()` replaces it. ```php passwordDefinition?->setPasswordMapper($passwordUpdateFunction); + // Every save of the users repository checks a plain password against the definition, + // also a user created with new and saved without this service + if ($this->passwordDefinition !== null) { + $repository = $usersRepository->getRepository(); + $modelValidator = $repository->getMapper()->getValidator(); + if (is_string($modelValidator)) { + $modelValidator = new $modelValidator(); + } + /** @var EntityValidatorInterface|null $modelValidator The repository checked it */ + $repository->setValidator(new PasswordDefinitionValidator($this->passwordDefinition, $modelValidator)); + } + $propertyMapper = $propertiesRepository->getRepository()->getMapper(); $propertyCheck = ($propertyMapper->getFieldMap(UserPropertyField::Userid->value) !== null) && ($propertyMapper->getFieldMap(UserPropertyField::Name->value) !== null) && @@ -116,7 +131,7 @@ public function getLoginValue(UserModel $user): ?string /** * @inheritDoc */ - #[\Override] + #[Override] public function save(UserModel $model): UserModel { $newUser = false; @@ -152,7 +167,7 @@ public function save(UserModel $model): UserModel * @param string|null $role * @inheritDoc */ - #[\Override] + #[Override] public function addUser(string $name, string $userName, string $email, string $password, ?string $role = null): UserModel { @@ -208,7 +223,7 @@ protected function canAddUser(UserModel $model): bool /** * @inheritDoc */ - #[\Override] + #[Override] public function getById(string|Literal|int $userid): ?UserModel { $user = $this->usersRepository->getById($userid); @@ -222,7 +237,7 @@ public function getById(string|Literal|int $userid): ?UserModel /** * @inheritDoc */ - #[\Override] + #[Override] public function getByEmail(string $email): ?UserModel { $fieldMap = $this->usersRepository->getMapper()->getFieldMap(UserField::Email->value); @@ -240,7 +255,7 @@ public function getByEmail(string $email): ?UserModel /** * @inheritDoc */ - #[\Override] + #[Override] public function getByUsername(string $username): ?UserModel { $fieldMap = $this->usersRepository->getMapper()->getFieldMap(UserField::Username->value); @@ -258,7 +273,7 @@ public function getByUsername(string $username): ?UserModel /** * @inheritDoc */ - #[\Override] + #[Override] public function getByLogin(string $login): ?UserModel { return match($this->loginField) { @@ -307,7 +322,7 @@ protected function resolveUserFieldValue(UserModel $user, string $fieldName, ?st /** * @inheritDoc */ - #[\Override] + #[Override] public function removeByLogin(string $login): bool { $user = $this->getByLogin($login); @@ -323,7 +338,7 @@ public function removeByLogin(string $login): bool /** * @inheritDoc */ - #[\Override] + #[Override] public function removeById(string|Literal|int $userid): bool { try { @@ -340,7 +355,7 @@ public function removeById(string|Literal|int $userid): bool /** * @inheritDoc */ - #[\Override] + #[Override] public function isValidUser(string $login, string $password): ?UserModel { $user = $this->getByLogin($login); @@ -360,7 +375,7 @@ public function isValidUser(string $login, string $password): ?UserModel /** * @inheritDoc */ - #[\Override] + #[Override] public function rehashPasswordIfNeeded(UserModel $user, string $password): bool { $mapper = $this->passwordMapper(); @@ -407,7 +422,7 @@ protected function passwordMapper(): PasswordMapperInterface /** * @inheritDoc */ - #[\Override] + #[Override] public function hasProperty(string|int|Literal $userId, string $propertyName, ?string $value = null): bool { $user = $this->getById($userId); @@ -432,7 +447,7 @@ public function hasProperty(string|int|Literal $userId, string $propertyName, ?s /** * @inheritDoc */ - #[\Override] + #[Override] public function getProperty(string|Literal|int $userId, string $propertyName): array|string|UserPropertiesModel|null { $properties = $this->propertiesRepository->getByUserIdAndName($userId, $propertyName); @@ -456,7 +471,7 @@ public function getProperty(string|Literal|int $userId, string $propertyName): a /** * @inheritDoc */ - #[\Override] + #[Override] public function addProperty(string|Literal|int $userId, string $propertyName, ?string $value): bool { $user = $this->getById($userId); @@ -493,7 +508,7 @@ public function addProperty(string|Literal|int $userId, string $propertyName, ?s /** * @inheritDoc */ - #[\Override] + #[Override] public function setProperty(string|Literal|int $userId, string $propertyName, ?string $value): bool { $properties = $this->propertiesRepository->getByUserIdAndName($userId, $propertyName); @@ -529,7 +544,7 @@ public function setProperty(string|Literal|int $userId, string $propertyName, ?s /** * @inheritDoc */ - #[\Override] + #[Override] public function removeProperty(string|Literal|int $userId, string $propertyName, ?string $value = null): bool { $user = $this->getById($userId); @@ -543,7 +558,7 @@ public function removeProperty(string|Literal|int $userId, string $propertyName, /** * @inheritDoc */ - #[\Override] + #[Override] public function removeAllProperties(string $propertyName, ?string $value = null): void { $this->propertiesRepository->deleteByName($propertyName, $value); @@ -552,7 +567,7 @@ public function removeAllProperties(string $propertyName, ?string $value = null) /** * @inheritDoc */ - #[\Override] + #[Override] public function getUsersByProperty(string $propertyName, string $value): array { return $this->getUsersByPropertySet([$propertyName => $value]); @@ -561,7 +576,7 @@ public function getUsersByProperty(string $propertyName, string $value): array /** * @inheritDoc */ - #[\Override] + #[Override] public function getUsersByPropertySet(array $propertiesArray): array { $userTable = $this->usersRepository->getTableName(); @@ -607,7 +622,7 @@ public function getUsersByPropertySet(array $propertiesArray): array return $users; } - #[\Override] + #[Override] public function createInsecureAuthToken( string|UserModel $login, JwtWrapper $jwtWrapper, @@ -665,7 +680,7 @@ public function createInsecureAuthToken( /** * @inheritDoc */ - #[\Override] + #[Override] public function createAuthToken( string $login, string $password, @@ -698,7 +713,7 @@ public function createAuthToken( * @throws NotAuthenticatedException * @throws UserNotFoundException */ - #[\Override] + #[Override] public function isValidToken(string $login, JwtWrapper $jwtWrapper, string $token): UserToken { $user = $this->getByLogin($login); @@ -722,7 +737,7 @@ public function isValidToken(string $login, JwtWrapper $jwtWrapper, string $toke ); } - #[\Override] + #[Override] public function getUsersEntity(array $fields): UserModel { $entity = $this->getUsersRepository()->getMapper()->getEntity($fields); diff --git a/src/Validator/PasswordDefinitionValidator.php b/src/Validator/PasswordDefinitionValidator.php new file mode 100644 index 0000000..ce9e589 --- /dev/null +++ b/src/Validator/PasswordDefinitionValidator.php @@ -0,0 +1,36 @@ +withPasswordDefinition($this->passwordDefinition); + } + + $this->next?->validate($instance, $isInsert); + } +} diff --git a/tests/Fixture/BlockedNameValidator.php b/tests/Fixture/BlockedNameValidator.php new file mode 100644 index 0000000..1f1c7ec --- /dev/null +++ b/tests/Fixture/BlockedNameValidator.php @@ -0,0 +1,21 @@ +getName() === 'Blocked') { + throw new RuntimeException('Blocked name'); + } + } +} diff --git a/tests/Fixture/UserModelWithValidator.php b/tests/Fixture/UserModelWithValidator.php new file mode 100644 index 0000000..f8024c4 --- /dev/null +++ b/tests/Fixture/UserModelWithValidator.php @@ -0,0 +1,11 @@ +executor = DatabaseExecutor::using(Factory::getDbInstance('sqlite://' . self::DATABASE)); $this->executor->execute("create table users ( @@ -60,7 +63,7 @@ private function createDatabase(string $passwordColumn = 'password varchar(255)' ); $this->service = new UsersService( - new UsersRepository($this->executor, UserModel::class), + new UsersRepository($this->executor, $userClass), new UserPropertiesRepository($this->executor, UserPropertiesModel::class), LoginField::Username, new PasswordDefinition() @@ -166,6 +169,74 @@ public function testColumnTooShortTruncatingTheHash(): void $this->assertNotNull($this->service->isValidUser('old', 'old'), 'the user can still log in'); } + /** + * @param callable(UserModel): mixed $save + */ + private function assertSaveChecksTheDefinition(callable $save): void + { + $user = new UserModel('New User', 'new@example.com', 'new', 'weak'); + try { + $save($user); + $this->fail('A password outside the definition was saved'); + } catch (\InvalidArgumentException $e) { + $this->assertStringContainsString('Password does not match the password definition', $e->getMessage()); + } + $this->assertNull($this->service->getByUsername('new')); + + $user->setPassword('n3wPassw0rd'); + $save($user); + $this->assertNotNull($this->service->isValidUser('new', 'n3wPassw0rd')); + } + + /** + * A user created with new has no password definition: the service's save() checks its password + */ + public function testServiceSaveChecksTheDefinition(): void + { + $this->createDatabase(); + + $this->assertSaveChecksTheDefinition(fn(UserModel $user) => $this->service->save($user)); + } + + /** + * Saved without the service, through the users repository or MicroORM's: still checked + */ + public function testRepositorySaveChecksTheDefinition(): void + { + $this->createDatabase(); + + $this->assertSaveChecksTheDefinition(fn(UserModel $user) => $this->service->getUsersRepository()->save($user)); + $this->executor->execute("delete from users where username = 'new'"); + $this->assertSaveChecksTheDefinition(fn(UserModel $user) => $this->service->getUsersRepository()->getRepository()->save($user)); + } + + /** + * The validator the user model declares still runs + */ + public function testTheValidatorOfTheModelStillRuns(): void + { + $this->createDatabase(userClass: UserModelWithValidator::class); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Blocked name'); + $this->service->save(new UserModelWithValidator('Blocked', 'blocked@example.com', 'blocked', 'n3wPassw0rd')); + } + + /** + * Saving a loaded user does not check its stored hash: an old SHA-1 password weaker than the + * definition is kept + */ + public function testSaveKeepsAStoredHash(): void + { + $this->createDatabase(); + $user = $this->service->getByUsername('old'); + $user->setName('Renamed'); + + $this->service->save($user); + + $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