Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Security] add support for opportunistic password migrations #31843

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 5, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

Expand All @@ -25,7 +26,7 @@
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class EntityUserProvider implements UserProviderInterface
class EntityUserProvider implements UserProviderInterface, PasswordUpgraderInterface
{
private $registry;
private $managerName;
Expand Down Expand Up @@ -107,6 +108,22 @@ public function supportsClass($class)
return $class === $this->getClass() || is_subclass_of($class, $this->getClass());
}

/**
* {@inheritdoc}
*/
public function upgradePassword(UserInterface $user, string $newEncodedPassword): void
{
$class = $this->getClass();
if (!$user instanceof $class) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
}

$repository = $this->getRepository();
if ($repository instanceof PasswordUpgraderInterface) {
$repository->upgradePassword($user, $newEncodedPassword);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So the idea would be that users would make their UserRepository implement this, right? Hmm, I guess there’s no generic way to do this... I mean, we could have them configure a “password” field and use that to make the query for them... though I don’t love more yaml config. And.. we can’t make a trait generic enough to do this. I guess best I can think of us add this to the repository automatically in make:user. It’s also a bit unfortunate that (unless you use the maker) you could silently “miss out” on this feature by not implementing this interface. Again, this is more unhelpful pondering than solution :)

Copy link
Member Author

@nicolas-grekas nicolas-grekas Jun 25, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Persistency is always custom, there is no single method we can provide to do it.
Requiring setPassword() on the entity wouldn't make it persist.
And yes, this must be opt-in, because not everyone will want/have the auth to write to the backend.
At this point, you need to review the maker-bundle PR:
symfony/maker-bundle#389

}
}

private function getObjectManager()
{
return $this->registry->getManager($this->managerName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Bridge\Doctrine\Security\User\EntityUserProvider;
use Symfony\Bridge\Doctrine\Test\DoctrineTestHelper;
use Symfony\Bridge\Doctrine\Tests\Fixtures\User;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;

class EntityUserProviderTest extends TestCase
{
Expand Down Expand Up @@ -175,6 +176,23 @@ public function testLoadUserByUserNameShouldDeclineInvalidInterface()
$provider->loadUserByUsername('name');
}

public function testPasswordUpgrades()
{
$user = new User(1, 1, 'user1');

$repository = $this->getMockBuilder(PasswordUpgraderInterface::class)->getMock();
$repository->expects($this->once())
->method('upgradePassword')
->with($user, 'foobar');

$provider = new EntityUserProvider(
$this->getManager($this->getObjectManager($repository)),
'Symfony\Bridge\Doctrine\Tests\Fixtures\User'
);

$provider->upgradePassword($user, 'foobar');
}

private function getManager($em, $name = null)
{
$manager = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock();
Expand Down
5 changes: 3 additions & 2 deletions 5 src/Symfony/Bridge/Doctrine/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
"symfony/property-access": "^3.4|^4.0|^5.0",
"symfony/property-info": "^3.4|^4.0|^5.0",
"symfony/proxy-manager-bridge": "^3.4|^4.0|^5.0",
"symfony/security-core": "^3.4|^4.0|^5.0",
"symfony/security-core": "^4.4|^5.0",
"symfony/expression-language": "^3.4|^4.0|^5.0",
"symfony/validator": "^3.4|^4.0|^5.0",
"symfony/translation": "^3.4|^4.0|^5.0",
Expand All @@ -49,7 +49,8 @@
"phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0",
"symfony/dependency-injection": "<3.4",
"symfony/form": "<4.4",
"symfony/messenger": "<4.3"
"symfony/messenger": "<4.3",
"symfony/security-core": "<4.4"
},
"suggest": {
"symfony/form": "",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
<argument /> <!-- User Provider -->
<argument /> <!-- Provider-shared Key -->
<argument /> <!-- User Checker -->
<argument type="service" id="security.password_encoder" />
</service>

<service id="security.authentication.listener.guard"
Expand Down
28 changes: 27 additions & 1 deletion 28 src/Symfony/Component/Ldap/Security/LdapUserProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,12 @@

use Symfony\Component\Ldap\Entry;
use Symfony\Component\Ldap\Exception\ConnectionException;
use Symfony\Component\Ldap\Exception\ExceptionInterface;
use Symfony\Component\Ldap\LdapInterface;
use Symfony\Component\Security\Core\Exception\InvalidArgumentException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

Expand All @@ -27,7 +29,7 @@
* @author Charles Sarrazin <charles@sarraz.in>
* @author Robin Chalas <robin.chalas@gmail.com>
*/
class LdapUserProvider implements UserProviderInterface
class LdapUserProvider implements UserProviderInterface, PasswordUpgraderInterface
{
private $ldap;
private $baseDn;
Expand Down Expand Up @@ -109,6 +111,30 @@ public function refreshUser(UserInterface $user)
return new LdapUser($user->getEntry(), $user->getUsername(), $user->getPassword(), $user->getRoles());
}

/**
* {@inheritdoc}
*/
public function upgradePassword(UserInterface $user, string $newEncodedPassword): void
{
if (!$user instanceof LdapUser) {
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));
}

if (null === $this->passwordAttribute) {
return;
}

try {
if ($user->isEqualTo($this->loadUserByUsername($user->getUsername()))) {
$user->getEntry()->setAttribute($this->passwordAttribute, [$newEncodedPassword]);
$this->ldap->getEntryManager()->update($user->getEntry());
$user->setPassword($newEncodedPassword);
}
} catch (ExceptionInterface $e) {
// ignore failed password upgrades
}
}

/**
* {@inheritdoc}
*/
Expand Down
3 changes: 3 additions & 0 deletions 3 src/Symfony/Component/Security/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ CHANGELOG
* Deprecated class `LdapUserProvider`, use `Symfony\Component\Ldap\Security\LdapUserProvider` instead
* Added method `needsRehash()` to `PasswordEncoderInterface` and `UserPasswordEncoderInterface`
* Added `MigratingPasswordEncoder`
* Added and implemented `PasswordUpgraderInterface`, for opportunistic password migrations
* Added `Guard\PasswordAuthenticatedInterface`, an optional interface
for "guard" authenticators that deal with user passwords

4.3.0
-----
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
Expand Down Expand Up @@ -54,9 +55,15 @@ protected function checkAuthentication(UserInterface $user, UsernamePasswordToke
throw new BadCredentialsException('The presented password cannot be empty.');
}

if (!$this->encoderFactory->getEncoder($user)->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) {
$encoder = $this->encoderFactory->getEncoder($user);

if (!$encoder->isPasswordValid($user->getPassword(), $presentedPassword, $user->getSalt())) {
throw new BadCredentialsException('The presented password is invalid.');
}

if ($this->userProvider instanceof PasswordUpgraderInterface && method_exists($encoder, 'needsRehash') && $encoder->needsRehash($user->getPassword())) {
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
$this->userProvider->upgradePassword($user, $encoder->encodePassword($presentedPassword, $user->getSalt()));
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@
use Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider;
use Symfony\Component\Security\Core\Encoder\PlaintextPasswordEncoder;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Tests\Encoder\TestPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class DaoAuthenticationProviderTest extends TestCase
{
Expand Down Expand Up @@ -247,6 +251,44 @@ public function testCheckAuthentication()
$method->invoke($provider, $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserInterface')->getMock(), $token);
}

public function testPasswordUpgrades()
{
$user = new User('user', 'pwd');

$encoder = $this->getMockBuilder(TestPasswordEncoderInterface::class)->getMock();
$encoder->expects($this->once())
->method('isPasswordValid')
->willReturn(true)
;
$encoder->expects($this->once())
->method('encodePassword')
->willReturn('foobar')
;
$encoder->expects($this->once())
->method('needsRehash')
->willReturn(true)
;

$provider = $this->getProvider(null, null, $encoder);

$userProvider = ((array) $provider)[sprintf("\0%s\0userProvider", DaoAuthenticationProvider::class)];
$userProvider->expects($this->once())
->method('upgradePassword')
->with($user, 'foobar')
;

$method = new \ReflectionMethod($provider, 'checkAuthentication');
$method->setAccessible(true);

$token = $this->getSupportedToken();
$token->expects($this->once())
->method('getCredentials')
->willReturn('foo')
;

$method->invoke($provider, $user, $token);
}

protected function getSupportedToken()
{
$mock = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\Authentication\\Token\\UsernamePasswordToken')->setMethods(['getCredentials', 'getUser', 'getProviderKey'])->disableOriginalConstructor()->getMock();
Expand All @@ -261,7 +303,7 @@ protected function getSupportedToken()

protected function getProvider($user = null, $userChecker = null, $passwordEncoder = null)
{
$userProvider = $this->getMockBuilder('Symfony\\Component\\Security\\Core\\User\\UserProviderInterface')->getMock();
$userProvider = $this->getMockBuilder([UserProviderInterface::class, PasswordUpgraderInterface::class])->getMock();
if (null !== $user) {
$userProvider->expects($this->once())
->method('loadUserByUsername')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Encoder\MigratingPasswordEncoder;
use Symfony\Component\Security\Core\Encoder\NativePasswordEncoder;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;

class MigratingPasswordEncoderTest extends TestCase
{
Expand Down Expand Up @@ -66,8 +65,3 @@ public function testFallback()
$this->assertTrue($encoder->isPasswordValid('abc', 'foo', 'salt'));
}
}

interface TestPasswordEncoderInterface extends PasswordEncoderInterface
{
public function needsRehash(string $encoded): bool;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Core\Tests\Encoder;

use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;

interface TestPasswordEncoderInterface extends PasswordEncoderInterface
{
public function needsRehash(string $encoded): bool;
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\ChainUserProvider;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\User;

class ChainUserProviderTest extends TestCase
{
Expand Down Expand Up @@ -188,6 +190,28 @@ public function testAcceptsTraversable()
$this->assertSame($account, $provider->refreshUser($this->getAccount()));
}

public function testPasswordUpgrades()
{
$user = new User('user', 'pwd');

$provider1 = $this->getMockBuilder(PasswordUpgraderInterface::class)->getMock();
$provider1
->expects($this->once())
->method('upgradePassword')
->willThrowException(new UnsupportedUserException('unsupported'))
;

$provider2 = $this->getMockBuilder(PasswordUpgraderInterface::class)->getMock();
$provider2
->expects($this->once())
->method('upgradePassword')
->with($user, 'foobar')
;

$provider = new ChainUserProvider([$provider1, $provider2]);
$provider->upgradePassword($user, 'foobar');
}

protected function getAccount()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
Expand Down
18 changes: 17 additions & 1 deletion 18 src/Symfony/Component/Security/Core/User/ChainUserProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class ChainUserProvider implements UserProviderInterface
class ChainUserProvider implements UserProviderInterface, PasswordUpgraderInterface
{
private $providers;

Expand Down Expand Up @@ -104,4 +104,20 @@ public function supportsClass($class)

return false;
}

/**
* {@inheritdoc}
*/
public function upgradePassword(UserInterface $user, string $newEncodedPassword): void
{
foreach ($this->providers as $provider) {
if ($provider instanceof PasswordUpgraderInterface) {
try {
$provider->upgradePassword($user, $newEncodedPassword);
} catch (UnsupportedUserException $e) {
nicolas-grekas marked this conversation as resolved.
Show resolved Hide resolved
// ignore: password upgrades are opportunistic
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Security\Core\User;

/**
* @author Nicolas Grekas <p@tchwork.com>
*/
interface PasswordUpgraderInterface
{
/**
* Upgrades the encoded password of a user, typically for using a better hash algorithm.
*
* This method should persist the new password in the user storage and update the $user object accordingly.
* Because you don't want your users not being able to log in, this method should be opportunistic:
* it's fine if it does nothing or if it fails without throwing any exception.
*/
public function upgradePassword(UserInterface $user, string $newEncodedPassword): void;
}
Loading
Morty Proxy This is a proxified and sanitized view of the page, visit original site.