password.test 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /**
  3. * @file
  4. * Provides unit tests for password.inc.
  5. */
  6. /**
  7. * Unit tests for password hashing API.
  8. */
  9. class PasswordHashingTest extends DrupalWebTestCase {
  10. protected $profile = 'testing';
  11. public static function getInfo() {
  12. return array(
  13. 'name' => 'Password hashing',
  14. 'description' => 'Password hashing unit tests.',
  15. 'group' => 'System',
  16. );
  17. }
  18. function setUp() {
  19. require_once DRUPAL_ROOT . '/' . variable_get('password_inc', 'includes/password.inc');
  20. parent::setUp();
  21. }
  22. /**
  23. * Test password hashing.
  24. */
  25. function testPasswordHashing() {
  26. // Set a log2 iteration count that is deliberately out of bounds to test
  27. // that it is corrected to be within bounds.
  28. variable_set('password_count_log2', 1);
  29. // Set up a fake $account with a password 'baz', hashed with md5.
  30. $password = 'baz';
  31. $account = (object) array('name' => 'foo', 'pass' => md5($password));
  32. // The md5 password should be flagged as needing an update.
  33. $this->assertTrue(user_needs_new_hash($account), 'User with md5 password needs a new hash.');
  34. // Re-hash the password.
  35. $old_hash = $account->pass;
  36. $account->pass = user_hash_password($password);
  37. $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_MIN_HASH_COUNT, 'Re-hashed password has the minimum number of log2 iterations.');
  38. $this->assertTrue($account->pass != $old_hash, 'Password hash changed.');
  39. $this->assertTrue(user_check_password($password, $account), 'Password check succeeds.');
  40. // Since the log2 setting hasn't changed and the user has a valid password,
  41. // user_needs_new_hash() should return FALSE.
  42. $this->assertFalse(user_needs_new_hash($account), 'User does not need a new hash.');
  43. // Increment the log2 iteration to MIN + 1.
  44. variable_set('password_count_log2', DRUPAL_MIN_HASH_COUNT + 1);
  45. $this->assertTrue(user_needs_new_hash($account), 'User needs a new hash after incrementing the log2 count.');
  46. // Re-hash the password.
  47. $old_hash = $account->pass;
  48. $account->pass = user_hash_password($password);
  49. $this->assertIdentical(_password_get_count_log2($account->pass), DRUPAL_MIN_HASH_COUNT + 1, 'Re-hashed password has the correct number of log2 iterations.');
  50. $this->assertTrue($account->pass != $old_hash, 'Password hash changed again.');
  51. // Now the hash should be OK.
  52. $this->assertFalse(user_needs_new_hash($account), 'Re-hashed password does not need a new hash.');
  53. $this->assertTrue(user_check_password($password, $account), 'Password check succeeds with re-hashed password.');
  54. }
  55. }