1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
|
<?php
namespace MediaWiki\Tests\Auth;
use MediaWiki\Auth\AuthenticationRequest;
use MediaWiki\Auth\AuthenticationResponse;
use MediaWiki\Auth\AuthManager;
use MediaWiki\Auth\PasswordAuthenticationRequest;
use MediaWiki\Auth\PrimaryAuthenticationProvider;
use MediaWiki\Auth\TemporaryPasswordAuthenticationRequest;
use MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider;
use MediaWiki\Config\HashConfig;
use MediaWiki\MainConfigNames;
use MediaWiki\Password\PasswordFactory;
use MediaWiki\Request\FauxRequest;
use MediaWiki\Status\Status;
use MediaWiki\Tests\Unit\Auth\AuthenticationProviderTestTrait;
use MediaWiki\Tests\Unit\DummyServicesTrait;
use MediaWiki\User\UserIdentity;
use MediaWiki\User\UserNameUtils;
use MediaWikiIntegrationTestCase;
use StatusValue;
use Wikimedia\Message\MessageSpecifier;
use Wikimedia\ScopedCallback;
use Wikimedia\TestingAccessWrapper;
/**
* TODO clean up and reduce duplication
*
* @group AuthManager
* @group Database
* @covers \MediaWiki\Auth\AbstractTemporaryPasswordPrimaryAuthenticationProvider
* @covers \MediaWiki\Auth\TemporaryPasswordPrimaryAuthenticationProvider
*/
class TemporaryPasswordPrimaryAuthenticationProviderTest extends MediaWikiIntegrationTestCase {
use AuthenticationProviderTestTrait;
use DummyServicesTrait;
private AuthManager $manager;
private Status $validity;
private PasswordFactory $testPasswordFactory;
protected function setUp(): void {
parent::setUp();
$mwServices = $this->getServiceContainer();
$hookContainer = $this->createHookContainer();
$this->manager = new AuthManager(
new FauxRequest(),
$mwServices->getMainConfig(),
$this->getDummyObjectFactory(),
$hookContainer,
$mwServices->getReadOnlyMode(),
$this->createNoOpMock( UserNameUtils::class ),
$mwServices->getBlockManager(),
$mwServices->getWatchlistManager(),
$mwServices->getDBLoadBalancer(),
$mwServices->getContentLanguage(),
$mwServices->getLanguageConverterFactory(),
$mwServices->getBotPasswordStore(),
$mwServices->getUserFactory(),
$mwServices->getUserIdentityLookup(),
$mwServices->getUserOptionsManager()
);
$this->validity = Status::newGood();
// A is unsalted MD5 (thus fast) ... we don't care about security here, this is test only
$this->testPasswordFactory = new PasswordFactory(
$this->getConfVar( MainConfigNames::PasswordConfig ),
'A'
);
}
/**
* Get an instance of the provider
*
* $provider->checkPasswordValidity is mocked to return $this->validity,
* because we don't need to test that here.
*
* @param array $params
* @param UserNameUtils|null $userNameUtils
* @return TemporaryPasswordPrimaryAuthenticationProvider
*/
protected function getProvider( array $params = [], ?UserNameUtils $userNameUtils = null ) {
$userNameUtils ??= $this->getServiceContainer()->getUserNameUtils();
$mwServices = $this->getServiceContainer();
$mockedMethods[] = 'checkPasswordValidity';
$provider = $this->getMockBuilder( TemporaryPasswordPrimaryAuthenticationProvider::class )
->onlyMethods( $mockedMethods )
->setConstructorArgs( [
$mwServices->getConnectionProvider(),
$mwServices->getUserOptionsLookup(),
$params,
] )
->getMock();
$provider->method( 'checkPasswordValidity' )
->willReturnCallback( function () {
return $this->validity;
} );
$this->initProvider(
$provider, $mwServices->getMainConfig(), null, $this->manager, null, $userNameUtils
);
return $provider;
}
protected function hookMailer( $func = null ) {
$hookContainer = $this->getServiceContainer()->getHookContainer();
$this->clearHook( 'AlternateUserMailer' );
if ( $func ) {
$reset = $hookContainer->scopedRegister( 'AlternateUserMailer', $func );
} else {
$reset = $hookContainer->scopedRegister( 'AlternateUserMailer', function () {
$this->fail( 'AlternateUserMailer hook called unexpectedly' );
return false;
} );
}
return $reset;
}
/**
* Set the new password (i.e. single use temporary password)
* hash for the given user, with an optional expiry time.
*
* @param UserIdentity $user The user to update the new password for.
* @param string $hash Password hash to store.
* @param int|null $expiry UNIX timestamp at which the new password expires, or `null` for no expiry.
*/
private function setNewPassword(
UserIdentity $user,
string $hash,
?int $expiry = null
): void {
$dbw = $this->getDb();
$dbw->newUpdateQueryBuilder()
->update( 'user' )
->set( [
'user_newpassword' => $hash,
'user_newpass_time' => $expiry ? $dbw->timestamp( $expiry ) : null
] )
->where( [ 'user_id' => $user->getId() ] )
->execute();
}
public function testBasics() {
$provider = $this->getProvider();
$this->assertSame(
PrimaryAuthenticationProvider::TYPE_CREATE,
$provider->accountCreationType()
);
$existingUserName = $this->getTestUser()->getUserIdentity()->getName();
$this->assertTrue( $provider->testUserExists( $existingUserName ) );
$this->assertTrue( $provider->testUserExists( lcfirst( $existingUserName ) ) );
$this->assertFalse( $provider->testUserExists( 'DoesNotExist' ) );
$this->assertFalse( $provider->testUserExists( '<invalid>' ) );
$req = new PasswordAuthenticationRequest;
$req->action = AuthManager::ACTION_CHANGE;
$req->username = '<invalid>';
$provider->providerChangeAuthenticationData( $req );
}
public function testConfig() {
$config = new HashConfig( [
MainConfigNames::EnableEmail => false,
MainConfigNames::NewPasswordExpiry => 100,
MainConfigNames::PasswordReminderResendTime => 101,
] );
$provider = new TemporaryPasswordPrimaryAuthenticationProvider(
$this->getServiceContainer()->getConnectionProvider(),
$this->getServiceContainer()->getUserOptionsLookup()
);
$providerPriv = TestingAccessWrapper::newFromObject( $provider );
$this->initProvider( $provider, $config );
$this->assertSame( false, $providerPriv->emailEnabled );
$this->assertSame( 100, $providerPriv->newPasswordExpiry );
$this->assertSame( 101, $providerPriv->passwordReminderResendTime );
$provider = new TemporaryPasswordPrimaryAuthenticationProvider(
$this->getServiceContainer()->getConnectionProvider(),
$this->getServiceContainer()->getUserOptionsLookup(),
[
'emailEnabled' => true,
'newPasswordExpiry' => 42,
'passwordReminderResendTime' => 43,
]
);
$providerPriv = TestingAccessWrapper::newFromObject( $provider );
$this->initProvider( $provider, $config );
$this->assertSame( true, $providerPriv->emailEnabled );
$this->assertSame( 42, $providerPriv->newPasswordExpiry );
$this->assertSame( 43, $providerPriv->passwordReminderResendTime );
}
/**
* @dataProvider provideTestUserCanAuthenticateErrorCases
*
* @param string|null $userName The user name to check, or `null` to use the user name of the test user
* @param callable|null $passwordProvider Optional callable that takes a `PasswordFactory` and produces
* a password hash override to set for the test user
* @param int|null $passwordExpiry Expiry to set for the password returned by `$passwordProvider`, or
* `null` to set no expiry.
* @return void
*/
public function testTestUserCanAuthenticateErrorCases(
?string $userName = null,
?callable $passwordProvider = null,
?int $passwordExpiry = null
): void {
$user = self::getMutableTestUser()->getUser();
if ( $passwordProvider !== null ) {
$this->setNewPassword(
$user,
$passwordProvider( $this->testPasswordFactory ),
$passwordExpiry
);
}
$userName ??= $user->getName();
$result = $this->getProvider( [ 'newPasswordExpiry' => 100 ] )->testUserCanAuthenticate( $userName );
$this->assertFalse( $result );
}
public function provideTestUserCanAuthenticateErrorCases(): iterable {
yield 'invalid user name' => [ '<invalid>' ];
yield 'nonexistent user' => [ 'DoesNotExist' ];
yield 'user with invalid password' => [
null,
fn () => PasswordFactory::newInvalidPassword()->toString()
];
yield 'user with expired password' => [
null,
fn ( PasswordFactory $passwordFactory ) => $passwordFactory->newFromPlaintext( 'password' )->toString(),
time() - 3_600
];
}
public function testTestUserCanAuthenticateSimple(): void {
$user = self::getMutableTestUser()->getUser();
$this->setNewPassword(
$user,
$this->testPasswordFactory->newFromPlaintext( 'password' )->toString()
);
$result = $this->getProvider()->testUserCanAuthenticate( $user->getName() );
$this->assertTrue( $result );
}
public function testTestUserCanAuthenticateCaseInsensitive(): void {
$user = self::getMutableTestUser()->getUser();
$this->setNewPassword(
$user,
$this->testPasswordFactory->newFromPlaintext( 'password' )->toString()
);
$result = $this->getProvider()->testUserCanAuthenticate( lcfirst( $user->getName() ) );
$this->assertTrue( $result );
}
public function testTestUserCanAuthenticateWithNonExpiredTemporaryPassword(): void {
$user = self::getMutableTestUser()->getUser();
$this->setNewPassword(
$user,
$this->testPasswordFactory->newFromPlaintext( 'password' )->toString(),
time() - 100
);
$result = $this->getProvider( [ 'newPasswordExpiry' => 3600 ] )->testUserCanAuthenticate( $user->getName() );
$this->assertTrue( $result );
}
/**
* @dataProvider provideGetAuthenticationRequests
* @param string $action
* @param bool $registered
* @param bool $temporary
* @param AuthenticationRequest[] $expected
*/
public function testGetAuthenticationRequests(
string $action,
bool $registered,
bool $temporary,
array $expected
) {
$username = $registered ? 'TestGetAuthenticationRequests' : null;
$options = [ 'username' => $username ];
$userNameUtils = $this->createMock( UserNameUtils::class );
$userNameUtils->method( 'isTemp' )
->with( $username )
->willReturn( $temporary );
$actual = $this->getProvider( [ 'emailEnabled' => true ], $userNameUtils )
->getAuthenticationRequests( $action, $options );
foreach ( $actual as $req ) {
if ( $req instanceof TemporaryPasswordAuthenticationRequest && $req->password !== null ) {
$req->password = 'random';
}
}
$this->assertEquals( $expected, $actual );
}
public static function provideGetAuthenticationRequests(): iterable {
yield 'login attempt as anonymous user' => [
AuthManager::ACTION_LOGIN, false, false, [ new PasswordAuthenticationRequest ]
];
yield 'login attempt as named user' => [
AuthManager::ACTION_LOGIN, true, false, [ new PasswordAuthenticationRequest ]
];
yield 'login attempt as temporary user' => [
AuthManager::ACTION_LOGIN, true, true, [ new PasswordAuthenticationRequest ]
];
yield 'signup attempt as anonymous user' => [
AuthManager::ACTION_CREATE, false, false, []
];
yield 'signup attempt as named user' => [
AuthManager::ACTION_CREATE, true, false, [ new TemporaryPasswordAuthenticationRequest( 'random' ) ]
];
yield 'signup attempt as temporary user' => [
AuthManager::ACTION_CREATE, true, true, []
];
yield 'account linking attempt as anonymous user' => [
AuthManager::ACTION_LINK, false, false, []
];
yield 'account linking attempt as named user' => [
AuthManager::ACTION_LINK, true, false, []
];
yield 'account linking attempt as temporary user' => [
AuthManager::ACTION_LINK, true, true, []
];
yield 'credential change attempt as anonymous user' => [
AuthManager::ACTION_CHANGE, false, false, [ new TemporaryPasswordAuthenticationRequest( 'random' ) ]
];
yield 'credential change attempt as named user' => [
AuthManager::ACTION_CHANGE, true, false, [ new TemporaryPasswordAuthenticationRequest( 'random' ) ]
];
yield 'credential change attempt as temporary user' => [
AuthManager::ACTION_CHANGE, true, true, [ new TemporaryPasswordAuthenticationRequest( 'random' ) ]
];
yield 'credential remove attempt as anonymous user' => [
AuthManager::ACTION_REMOVE, false, false, [ new TemporaryPasswordAuthenticationRequest() ]
];
yield 'credential remove attempt as named user' => [
AuthManager::ACTION_REMOVE, true, false, [ new TemporaryPasswordAuthenticationRequest() ]
];
yield 'credential remove attempt as temporary user' => [
AuthManager::ACTION_REMOVE, true, true, [ new TemporaryPasswordAuthenticationRequest() ]
];
}
/**
* @dataProvider provideAuthenticationErrorCases
* @param string $password
* @param string $expectedErrorMessage
* @param int $newPasswordExpiry
* @param StatusValue|null $validationError
* @return void
*/
public function testAuthenticationErrorCases(
string $password,
string $expectedErrorMessage,
int $newPasswordExpiry = 100,
?StatusValue $validationError = null
) {
$user = self::getMutableTestUser()->getUser();
$validPassword = 'TemporaryPassword';
$hash = ':A:' . md5( $validPassword );
$this->setNewPassword( $user, $hash, time() - 10 );
$req = self::makePasswordAuthenticationRequest( $user->getName(), $password );
$reqs = [ PasswordAuthenticationRequest::class => $req ];
$provider = $this->getProvider( [ 'newPasswordExpiry' => $newPasswordExpiry ] );
$this->validity = $validationError ?? Status::newGood();
$response = $provider->beginPrimaryAuthentication( $reqs );
$this->assertSame( AuthenticationResponse::FAIL, $response->status );
if ( $validationError !== null ) {
$this->assertSame(
$validationError->getMessages()[0]->getKey(),
$response->message->getParams()[0]->getKey()
);
}
}
public static function provideAuthenticationErrorCases(): iterable {
yield 'validation failure' => [
'TemporaryPassword',
'fatalpassworderror',
100,
Status::newFatal( 'arbitrary-failure' )
];
yield 'expired password' => [
'TemporaryPassword',
'wrongpassword',
1
];
yield 'wrong password' => [
'Wrong',
'wrongpassword'
];
}
/**
* @dataProvider provideAuthenticationAbstainCases
* @param PasswordAuthenticationRequest|null $req The authentication request to send,
* or `null` to send no requests
* @return void
*/
public function testAuthenticationAbstainCases( ?PasswordAuthenticationRequest $req ): void {
$reqs = $req ? [ PasswordAuthenticationRequest::class => $req ] : [];
$response = $this->getProvider()->beginPrimaryAuthentication( $reqs );
$this->assertEquals( AuthenticationResponse::newAbstain(), $response );
}
public static function provideAuthenticationAbstainCases(): iterable {
yield 'no requests' => [ null ];
yield 'no user name' => [ self::makePasswordAuthenticationRequest( null, 'bar' ) ];
yield 'no password' => [ self::makePasswordAuthenticationRequest( 'foo' ) ];
yield 'invalid user name' => [ self::makePasswordAuthenticationRequest( '<invalid>', 'bar' ) ];
yield 'nonexistent user' => [ self::makePasswordAuthenticationRequest( 'DoesNotExist', 'bar' ) ];
}
private static function makePasswordAuthenticationRequest(
?string $userName = null,
?string $password = null
): PasswordAuthenticationRequest {
$req = new PasswordAuthenticationRequest();
$req->action = AuthManager::ACTION_LOGIN;
$req->username = $userName;
$req->password = $password;
return $req;
}
public function testAuthenticationSuccess(): void {
$user = self::getMutableTestUser()->getUser();
$password = 'TemporaryPassword';
$hash = ':A:' . md5( $password );
$this->setNewPassword( $user, $hash, time() - 10 );
$req = self::makePasswordAuthenticationRequest( $user->getName(), $password );
$reqs = [ PasswordAuthenticationRequest::class => $req ];
$provider = $this->getProvider();
$this->manager->removeAuthenticationSessionData( null );
$this->validity = Status::newGood();
$this->assertEquals(
AuthenticationResponse::newPass( $user->getName() ),
$provider->beginPrimaryAuthentication( $reqs )
);
$this->assertNotNull( $this->manager->getAuthenticationSessionData( 'reset-pass' ) );
}
public function testAuthenticationSuccessCaseInsensitive(): void {
$user = self::getMutableTestUser()->getUser();
$password = 'TemporaryPassword';
$hash = ':A:' . md5( $password );
$this->setNewPassword( $user, $hash, time() - 10 );
$req = self::makePasswordAuthenticationRequest( lcfirst( $user->getName() ), $password );
$reqs = [ PasswordAuthenticationRequest::class => $req ];
$provider = $this->getProvider();
$this->manager->removeAuthenticationSessionData( null );
$this->validity = Status::newGood();
$this->assertEquals(
AuthenticationResponse::newPass( $user->getName() ),
$provider->beginPrimaryAuthentication( $reqs )
);
$this->assertNotNull( $this->manager->getAuthenticationSessionData( 'reset-pass' ) );
}
/**
* @dataProvider provideProviderAllowsAuthenticationDataChange
*
* @param string $type
* @param callable $usernameGetter Function that takes the username of a sysop user and returns the username to
* use for testing.
* @param Status $validity Result of the password validity check
* @param StatusValue $expect1 Expected result with $checkData = false
* @param StatusValue $expect2 Expected result with $checkData = true
*/
public function testProviderAllowsAuthenticationDataChange( $type, callable $usernameGetter,
Status $validity,
StatusValue $expect1, StatusValue $expect2
) {
$user = $usernameGetter( $this->getTestSysop()->getUserIdentity()->getName() );
if ( $type === PasswordAuthenticationRequest::class ||
$type === TemporaryPasswordAuthenticationRequest::class
) {
$req = new $type();
$req->password = 'NewPassword';
} else {
$req = $this->createMock( $type );
}
$req->action = AuthManager::ACTION_CHANGE;
$req->username = $user;
$provider = $this->getProvider();
$this->validity = $validity;
$this->assertEquals( $expect1, $provider->providerAllowsAuthenticationDataChange( $req, false ) );
$this->assertEquals( $expect2, $provider->providerAllowsAuthenticationDataChange( $req, true ) );
}
public static function provideProviderAllowsAuthenticationDataChange() {
$err = StatusValue::newGood();
$err->error( 'arbitrary-warning' );
return [
[
AuthenticationRequest::class,
static fn ( $sysopUsername ) => $sysopUsername,
Status::newGood(),
StatusValue::newGood( 'ignored' ),
StatusValue::newGood( 'ignored' ),
],
[
PasswordAuthenticationRequest::class,
static fn ( $sysopUsername ) => $sysopUsername,
Status::newGood(),
StatusValue::newGood( 'ignored' ),
StatusValue::newGood( 'ignored' ),
],
[
TemporaryPasswordAuthenticationRequest::class,
static fn ( $sysopUsername ) => $sysopUsername,
Status::newGood(),
StatusValue::newGood(),
StatusValue::newGood(),
],
[
TemporaryPasswordAuthenticationRequest::class,
'lcfirst',
Status::newGood(),
StatusValue::newGood(),
StatusValue::newGood(),
],
[
TemporaryPasswordAuthenticationRequest::class,
static fn ( $sysopUsername ) => $sysopUsername,
Status::wrap( $err ),
StatusValue::newGood(),
$err,
],
[
TemporaryPasswordAuthenticationRequest::class,
static fn ( $sysopUsername ) => $sysopUsername,
Status::newFatal( 'arbitrary-error' ),
StatusValue::newGood(),
StatusValue::newFatal( 'arbitrary-error' ),
],
[
TemporaryPasswordAuthenticationRequest::class,
static fn () => 'DoesNotExist',
Status::newGood(),
StatusValue::newGood(),
StatusValue::newGood( 'ignored' ),
],
[
TemporaryPasswordAuthenticationRequest::class,
static fn () => '<invalid>',
Status::newGood(),
StatusValue::newGood(),
StatusValue::newGood( 'ignored' ),
],
];
}
/**
* @dataProvider provideProviderChangeAuthenticationData
* @param string $type
* @param bool $changed
*/
public function testProviderChangeAuthenticationData( $type, $changed ) {
$user = $this->getTestSysop()->getUserIdentity()->getName();
$oldpass = 'OldTempPassword';
$newpass = 'NewTempPassword';
$dbw = $this->getDb();
$oldHash = $dbw->newSelectQueryBuilder()
->select( 'user_newpassword' )
->from( 'user' )
->where( [ 'user_name' => $user ] )
->fetchField();
$cb = new ScopedCallback( static function () use ( $dbw, $user, $oldHash ) {
$dbw->newUpdateQueryBuilder()
->update( 'user' )
->set( [ 'user_newpassword' => $oldHash ] )
->where( [ 'user_name' => $user ] )
->execute();
} );
$hash = ':A:' . md5( $oldpass );
$dbw->newUpdateQueryBuilder()
->update( 'user' )
->set( [ 'user_newpassword' => $hash, 'user_newpass_time' => $dbw->timestamp( time() + 1000 ) ] )
->where( [ 'user_name' => $user ] )
->execute();
$provider = $this->getProvider();
$loginReq = new PasswordAuthenticationRequest();
$loginReq->action = AuthManager::ACTION_CHANGE;
$loginReq->username = $user;
$loginReq->password = $oldpass;
$loginReqs = [ PasswordAuthenticationRequest::class => $loginReq ];
$this->assertEquals(
AuthenticationResponse::newPass( $user ),
$provider->beginPrimaryAuthentication( $loginReqs )
);
if ( $type === PasswordAuthenticationRequest::class ||
$type === TemporaryPasswordAuthenticationRequest::class
) {
$changeReq = new $type();
$changeReq->password = $newpass;
} else {
$changeReq = $this->createMock( $type );
}
$changeReq->action = AuthManager::ACTION_CHANGE;
$changeReq->username = $user;
$resetMailer = $this->hookMailer();
$provider->providerChangeAuthenticationData( $changeReq );
ScopedCallback::consume( $resetMailer );
$loginReq->password = $oldpass;
$ret = $provider->beginPrimaryAuthentication( $loginReqs );
$this->assertEquals(
AuthenticationResponse::FAIL,
$ret->status,
'old password should fail'
);
$this->assertEquals(
'wrongpassword',
$ret->message->getKey(),
'old password should fail'
);
$loginReq->password = $newpass;
$ret = $provider->beginPrimaryAuthentication( $loginReqs );
if ( $changed ) {
$this->assertEquals(
AuthenticationResponse::newPass( $user ),
$ret,
'new password should pass'
);
$this->assertNotNull(
$dbw->newSelectQueryBuilder()
->select( 'user_newpass_time' )
->from( 'user' )
->where( [ 'user_name' => $user ] )
->fetchField()
);
} else {
$this->assertEquals(
AuthenticationResponse::FAIL,
$ret->status,
'new password should fail'
);
$this->assertEquals(
'wrongpassword',
$ret->message->getKey(),
'new password should fail'
);
$this->assertNull(
$dbw->newSelectQueryBuilder()
->select( 'user_newpass_time' )
->from( 'user' )
->where( [ 'user_name' => $user ] )
->fetchField()
);
}
}
public static function provideProviderChangeAuthenticationData() {
return [
[ AuthenticationRequest::class, false ],
[ PasswordAuthenticationRequest::class, false ],
[ TemporaryPasswordAuthenticationRequest::class, true ],
];
}
/**
* @dataProvider provideChangeAuthenticationDataEmailErrorCases
*
* @param array $providerConfig Configuration to pass on to the auth provider
* @param string|null $caller Caller on behalf of which the request is sent
* @param string $expectedError Expected error message key
*/
public function testProviderChangeAuthenticationDataEmailError(
array $providerConfig,
?string $caller,
string $expectedError
): void {
$user = self::getMutableTestUser()->getUser();
$dbw = $this->getDb();
$dbw->newUpdateQueryBuilder()
->update( 'user' )
->set( [ 'user_newpass_time' => $dbw->timestamp( time() - 5 * 3600 ) ] )
->where( [ 'user_id' => $user->getId() ] )
->execute();
$req = TemporaryPasswordAuthenticationRequest::newRandom();
$req->username = $user->getName();
$req->mailpassword = true;
$req->caller = $caller;
$provider = $this->getProvider( $providerConfig );
$status = $provider->providerAllowsAuthenticationDataChange( $req );
$this->assertFalse( $status->isGood() );
$this->assertSame(
[ $expectedError ],
array_map( fn ( MessageSpecifier $spec ) => $spec->getKey(), $status->getMessages() )
);
}
public static function provideChangeAuthenticationDataEmailErrorCases(): iterable {
yield 'email disabled' => [
[ 'emailEnabled' => false ],
'127.0.0.1',
'passwordreset-emaildisabled'
];
yield 'password reset rate limited' => [
[ 'emailEnabled' => true, 'passwordReminderResendTime' => 10 ],
'127.0.0.1',
'throttled-mailpassword'
];
yield 'missing caller' => [
[ 'emailEnabled' => true, 'passwordReminderResendTime' => 0 ],
null,
'passwordreset-nocaller'
];
yield 'invalid IP caller' => [
[ 'emailEnabled' => true, 'passwordReminderResendTime' => 0 ],
'127.0.0.256',
'passwordreset-nosuchcaller'
];
yield 'invalid registered caller' => [
[ 'emailEnabled' => true, 'passwordReminderResendTime' => 0 ],
'<Invalid>',
'passwordreset-nosuchcaller'
];
}
/**
* @dataProvider provideChangeAuthenticationDataEmailSuccessCases
* @param string $caller Caller on behalf of which the request is sent
*/
public function testProviderChangeAuthenticationDataEmailSuccess( string $caller ) {
$user = self::getMutableTestUser()->getUser();
$dbw = $this->getDb();
$dbw->newUpdateQueryBuilder()
->update( 'user' )
->set( [ 'user_newpass_time' => $dbw->timestamp( time() + 5 * 3600 ) ] )
->where( [ 'user_id' => $user->getId() ] )
->execute();
$req = TemporaryPasswordAuthenticationRequest::newRandom();
$req->username = $user->getName();
$req->mailpassword = true;
$req->caller = $caller;
$provider = $this->getProvider( [ 'emailEnabled' => true, 'passwordReminderResendTime' => 0 ] );
$status = $provider->providerAllowsAuthenticationDataChange( $req, true );
$this->assertEquals( StatusValue::newGood(), $status );
$mailed = false;
$resetMailer = $this->hookMailer( function ( $headers, $to, $from, $subject, $body )
use ( &$mailed, $req, $user )
{
$mailed = true;
$this->assertSame( $user->getEmail(), $to[0]->address );
$this->assertStringContainsString( $req->password, $body );
return false;
} );
$provider->providerChangeAuthenticationData( $req );
ScopedCallback::consume( $resetMailer );
$this->assertTrue( $mailed );
}
public static function provideChangeAuthenticationDataEmailSuccessCases(): iterable {
yield 'anonymous caller' => [ '127.0.0.1' ];
yield 'registered caller' => [ 'TestUser' ];
}
/**
* @dataProvider provideAccountCreationSuccessCases
* @param AuthenticationRequest[] $reqs
*/
public function testTestForAccountCreationSuccess( array $reqs ) {
$user = $this->getServiceContainer()->getUserFactory()->newFromName( 'foo' );
$status = $this->getProvider()->testForAccountCreation( $user, $user, $reqs );
$this->assertTrue( $status->isGood() );
}
public static function provideAccountCreationSuccessCases(): iterable {
$req = new TemporaryPasswordAuthenticationRequest();
$req->username = 'Foo';
$req->password = 'Bar';
yield 'no password request' => [
[],
];
yield 'validated password request' => [
[ TemporaryPasswordAuthenticationRequest::class => $req ],
];
}
public function testTestForAccountCreationError(): void {
$req = new TemporaryPasswordAuthenticationRequest();
$req->username = 'Foo';
$req->password = 'Bar';
$user = $this->getServiceContainer()->getUserFactory()->newFromName( 'foo' );
$provider = $this->getProvider();
$this->validity->error( 'arbitrary warning' );
$status = $provider->testForAccountCreation(
$user, $user, [ TemporaryPasswordAuthenticationRequest::class => $req ]
);
$this->assertFalse( $status->isGood() );
$this->assertTrue( $status->hasMessage( 'arbitrary warning' ) );
}
/**
* @dataProvider provideAccountCreationAbstainCases
* @param TemporaryPasswordAuthenticationRequest|null $req
* @return void
*/
public function testAccountCreationAbstain( ?TemporaryPasswordAuthenticationRequest $req ) {
$resetMailer = $this->hookMailer();
$user = $this->getServiceContainer()->getUserFactory()->newFromName( 'Foo' );
$reqs = $req ? [ TemporaryPasswordAuthenticationRequest::class => $req ] : [];
$provider = $this->getProvider();
$response = $provider->beginPrimaryAccountCreation( $user, $user, $reqs );
$this->assertSame( AuthenticationResponse::ABSTAIN, $response->status );
}
public static function provideAccountCreationAbstainCases(): iterable {
yield 'no authentication requests' => [
null,
];
yield 'request without password' => [
self::makeTemporaryPasswordAuthenticationRequest( 'foo' ),
];
yield 'request without username' => [
self::makeTemporaryPasswordAuthenticationRequest( null, 'bar' ),
];
}
public function testAccountCreationPassForUserNameWithDifferentCase(): void {
$user = $this->getServiceContainer()->getUserFactory()->newFromName( 'Foo' );
$pass = 'NewPassword';
$req = self::makeTemporaryPasswordAuthenticationRequest( 'foo', $pass );
$reqs = [ TemporaryPasswordAuthenticationRequest::class => $req ];
$provider = $this->getProvider();
$response = $provider->beginPrimaryAccountCreation( $user, $user, $reqs );
$this->assertSame( AuthenticationResponse::PASS, $response->status );
$this->assertSame( $response->username, $user->getName() );
$this->assertSame(
$response->createRequest->username,
$user->getName()
);
}
public function testAccountCreationPass(): void {
$resetMailer = $this->hookMailer();
$user = self::getMutableTestUser()->getUser();
$pass = 'NewPassword';
$req = self::makeTemporaryPasswordAuthenticationRequest( $user->getName(), $pass );
$reqs = [ TemporaryPasswordAuthenticationRequest::class => $req ];
$provider = $this->getProvider();
$response = $provider->beginPrimaryAccountCreation( $user, $user, $reqs );
$this->assertSame( AuthenticationResponse::PASS, $response->status );
$this->assertSame( $response->username, $user->getName() );
$this->assertSame(
$response->createRequest->username,
$user->getName()
);
$this->assertNull( $this->manager->getAuthenticationSessionData( 'no-email' ) );
$authreq = new PasswordAuthenticationRequest();
$authreq->action = AuthManager::ACTION_CREATE;
$authreq->username = $user->getName();
$authreq->password = $pass;
$authreqs = [ PasswordAuthenticationRequest::class => $authreq ];
$failedAttemptResponse = $provider->beginPrimaryAuthentication( $authreqs );
$this->assertSame( AuthenticationResponse::FAIL, $failedAttemptResponse->status, 'account creation not finished yet' );
$this->assertSame( null, $provider->finishAccountCreation( $user, $user, $response ) );
$response = $provider->beginPrimaryAuthentication( $authreqs );
$this->assertSame( AuthenticationResponse::PASS, $response->status, 'new password is set' );
}
private static function makeTemporaryPasswordAuthenticationRequest(
?string $userName = null,
?string $password = null
): TemporaryPasswordAuthenticationRequest {
$req = new TemporaryPasswordAuthenticationRequest();
$req->username = $userName;
$req->password = $password;
return $req;
}
/**
* @dataProvider provideAccountCreationEmailErrorCases
*
* @param array $providerConfig Configuration to pass on to the auth provider
* @param string $userEmail Email to set for the user being tested
* @param string $expectedError Expected error message key
*/
public function testAccountCreationEmailErrorCases(
array $providerConfig,
string $userEmail,
string $expectedError
): void {
$creator = $this->getServiceContainer()->getUserFactory()->newFromName( 'Foo' );
$user = self::getMutableTestUser()->getUser();
$user->setEmail( $userEmail );
$req = TemporaryPasswordAuthenticationRequest::newRandom();
$req->username = $user->getName();
$req->mailpassword = true;
$provider = $this->getProvider( $providerConfig );
$status = $provider->testForAccountCreation( $user, $creator, [ $req ] );
$this->assertEquals( StatusValue::newFatal( $expectedError ), $status );
}
public static function provideAccountCreationEmailErrorCases(): iterable {
yield 'email disabled' => [
[ 'emailEnabled' => false ],
'test@localhost.localdomain',
'emaildisabled'
];
yield 'missing user email' => [
[ 'emailEnabled' => true ],
'',
'noemailcreate'
];
}
public function testAccountCreationEmailSuccess(): void {
$creator = $this->getServiceContainer()->getUserFactory()->newFromName( 'Foo' );
$user = self::getMutableTestUser()->getUser();
$user->setEmail( 'test@localhost.localdomain' );
$req = TemporaryPasswordAuthenticationRequest::newRandom();
$req->username = $user->getName();
$req->mailpassword = true;
$provider = $this->getProvider( [ 'emailEnabled' => true ] );
$status = $provider->testForAccountCreation( $user, $creator, [ $req ] );
$this->assertEquals( StatusValue::newGood(), $status );
$mailed = false;
$resetMailer = $this->hookMailer( function ( $headers, $to, $from, $subject, $body )
use ( &$mailed, $req )
{
$mailed = true;
$this->assertSame( 'test@localhost.localdomain', $to[0]->address );
$this->assertStringContainsString( $req->password, $body );
return false;
} );
$expect = AuthenticationResponse::newPass( $user->getName() );
$expect->createRequest = clone $req;
$expect->createRequest->username = $user->getName();
$res = $provider->beginPrimaryAccountCreation( $user, $creator, [ $req ] );
$this->assertEquals( $expect, $res );
$this->assertTrue( $this->manager->getAuthenticationSessionData( 'no-email' ) );
$this->assertFalse( $mailed );
$this->assertSame( 'byemail', $provider->finishAccountCreation( $user, $creator, $res ) );
$this->assertTrue( $mailed );
ScopedCallback::consume( $resetMailer );
$this->assertTrue( $mailed );
}
}
|