class PhpPasswordTest

Same name in other branches
  1. 10 core/tests/Drupal/Tests/Core/Password/PhpPasswordTest.php \Drupal\Tests\Core\Password\PhpPasswordTest

Unit tests for password hashing API.

@coversDefaultClass \Drupal\Core\Password\PhpPassword @group System

Hierarchy

Expanded class hierarchy of PhpPasswordTest

File

core/tests/Drupal/Tests/Core/Password/PhpPasswordTest.php, line 17

Namespace

Drupal\Tests\Core\Password
View source
class PhpPasswordTest extends UnitTestCase {
    
    /**
     * The raw password.
     */
    protected string $password;
    
    /**
     * The hashed password.
     */
    protected string $passwordHash;
    
    /**
     * The password hasher under test.
     */
    protected PasswordInterface $passwordHasher;
    
    /**
     * {@inheritdoc}
     */
    protected function setUp() : void {
        parent::setUp();
        $this->password = $this->randomMachineName();
        $this->passwordHasher = new PhpPassword(PASSWORD_BCRYPT, [
            'cost' => 5,
        ]);
        $this->passwordHash = $this->passwordHasher
            ->hash($this->password);
    }
    
    /**
     * Tests a password needs update.
     *
     * @covers ::hash
     * @covers ::needsRehash
     */
    public function testPasswordNeedsUpdate() : void {
        $weakHash = (new PhpPassword(PASSWORD_BCRYPT, [
            'cost' => 4,
        ]))->hash($this->password);
        $this->assertTrue($this->passwordHasher
            ->needsRehash($weakHash), 'Password hash with weak cost settings needs a new hash.');
    }
    
    /**
     * Tests password hashing.
     *
     * @covers ::check
     * @covers ::needsRehash
     */
    public function testPasswordChecking() : void {
        $this->assertTrue($this->passwordHasher
            ->check($this->password, $this->passwordHash), 'Password check succeeds.');
        $this->assertFalse($this->passwordHasher
            ->needsRehash($this->passwordHash), 'Does not need a new hash.');
    }
    
    /**
     * Tests password rehashing.
     *
     * @covers ::hash
     * @covers ::check
     * @covers ::needsRehash
     */
    public function testPasswordRehashing() : void {
        // Increment the cost by one.
        $strongHasher = new PhpPassword(PASSWORD_BCRYPT, [
            'cost' => 6,
        ]);
        $this->assertTrue($strongHasher->needsRehash($this->passwordHash), 'Needs a new hash after incrementing the cost option.');
        // Re-hash the password.
        $rehashedPassword = $strongHasher->hash($this->password);
        $this->assertNotEquals($rehashedPassword, $this->passwordHash, 'Password hash changed again.');
        // Now the hash should be OK.
        $this->assertFalse($strongHasher->needsRehash($rehashedPassword), 'Re-hashed password does not need a new hash.');
        $this->assertTrue($strongHasher->check($this->password, $rehashedPassword), 'Password check succeeds with re-hashed password.');
        $this->assertTrue($this->passwordHasher
            ->check($this->password, $rehashedPassword), 'Password check succeeds with re-hashed password with original hasher.');
    }
    
    /**
     * Verifies that passwords longer than 512 bytes are not hashed.
     *
     * @covers ::hash
     *
     * @dataProvider providerLongPasswords
     */
    public function testLongPassword($password, $allowed) : void {
        $passwordHash = $this->passwordHasher
            ->hash($password);
        if ($allowed) {
            $this->assertNotFalse($passwordHash);
        }
        else {
            $this->assertFalse($passwordHash);
        }
    }
    
    /**
     * Provides the test matrix for testLongPassword().
     */
    public static function providerLongPasswords() {
        // '512 byte long password is allowed.'
        $passwords['allowed'] = [
            str_repeat('x', PasswordInterface::PASSWORD_MAX_LENGTH),
            TRUE,
        ];
        // 513 byte long password is not allowed.
        $passwords['too_long'] = [
            str_repeat('x', PasswordInterface::PASSWORD_MAX_LENGTH + 1),
            FALSE,
        ];
        // Check a string of 3-byte UTF-8 characters, 510 byte long password is
        // allowed.
        $len = (int) floor(PasswordInterface::PASSWORD_MAX_LENGTH / 3);
        $diff = PasswordInterface::PASSWORD_MAX_LENGTH % 3;
        $passwords['utf8'] = [
            str_repeat('€', $len),
            TRUE,
        ];
        // 512 byte long password is allowed.
        $passwords['ut8_extended'] = [
            $passwords['utf8'][0] . str_repeat('x', $diff),
            TRUE,
        ];
        // Check a string of 3-byte UTF-8 characters, 513 byte long password is
        // allowed.
        $passwords['utf8_too_long'] = [
            str_repeat('€', $len + 1),
            FALSE,
        ];
        return $passwords;
    }
    
    /**
     * Tests password check in case provided hash is NULL.
     *
     * @covers ::check
     */
    public function testEmptyHash() : void {
        $this->assertFalse($this->passwordHasher
            ->check($this->password, NULL));
        $this->assertFalse($this->passwordHasher
            ->check($this->password, ''));
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title
ExpectDeprecationTrait::expectDeprecation public function Adds an expected deprecation.
ExpectDeprecationTrait::getCallableName private static function Returns a callable as a string suitable for inclusion in a message.
ExpectDeprecationTrait::setUpErrorHandler public function Sets up the test error handler.
ExpectDeprecationTrait::tearDownErrorHandler public function Tears down the test error handler.
PhpPasswordTest::$password protected property The raw password.
PhpPasswordTest::$passwordHash protected property The hashed password.
PhpPasswordTest::$passwordHasher protected property The password hasher under test.
PhpPasswordTest::providerLongPasswords public static function Provides the test matrix for testLongPassword().
PhpPasswordTest::setUp protected function Overrides UnitTestCase::setUp
PhpPasswordTest::testEmptyHash public function Tests password check in case provided hash is NULL.
PhpPasswordTest::testLongPassword public function Verifies that passwords longer than 512 bytes are not hashed.
PhpPasswordTest::testPasswordChecking public function Tests password hashing.
PhpPasswordTest::testPasswordNeedsUpdate public function Tests a password needs update.
PhpPasswordTest::testPasswordRehashing public function Tests password rehashing.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
UnitTestCase::$root protected property The app root.
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::setUpBeforeClass public static function

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.