3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\MediaWikiServices
;
7 use Wikimedia\TestingAccessWrapper
;
12 class UserTest
extends MediaWikiTestCase
{
18 protected function setUp() {
21 $this->setMwGlobals( [
22 'wgGroupPermissions' => [],
23 'wgRevokePermissions' => [],
26 $this->setUpPermissionGlobals();
28 $this->user
= new User
;
29 $this->user
->addToDatabase();
30 $this->user
->addGroup( 'unittesters' );
33 private function setUpPermissionGlobals() {
34 global $wgGroupPermissions, $wgRevokePermissions;
36 # Data for regular $wgGroupPermissions test
37 $wgGroupPermissions['unittesters'] = [
43 $wgGroupPermissions['testwriters'] = [
49 # Data for regular $wgRevokePermissions test
50 $wgRevokePermissions['formertesters'] = [
54 # For the options test
55 $wgGroupPermissions['*'] = [
56 'editmyoptions' => true,
61 * @covers User::getGroupPermissions
63 public function testGroupPermissions() {
64 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
65 $this->assertContains( 'runtest', $rights );
66 $this->assertNotContains( 'writetest', $rights );
67 $this->assertNotContains( 'modifytest', $rights );
68 $this->assertNotContains( 'nukeworld', $rights );
70 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
71 $this->assertContains( 'runtest', $rights );
72 $this->assertContains( 'writetest', $rights );
73 $this->assertContains( 'modifytest', $rights );
74 $this->assertNotContains( 'nukeworld', $rights );
78 * @covers User::getGroupPermissions
80 public function testRevokePermissions() {
81 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
82 $this->assertNotContains( 'runtest', $rights );
83 $this->assertNotContains( 'writetest', $rights );
84 $this->assertNotContains( 'modifytest', $rights );
85 $this->assertNotContains( 'nukeworld', $rights );
89 * @covers User::getRights
91 public function testUserPermissions() {
92 $rights = $this->user
->getRights();
93 $this->assertContains( 'runtest', $rights );
94 $this->assertNotContains( 'writetest', $rights );
95 $this->assertNotContains( 'modifytest', $rights );
96 $this->assertNotContains( 'nukeworld', $rights );
100 * @covers User::getRights
102 public function testUserGetRightsHooks() {
104 $user->addToDatabase();
105 $user->addGroup( 'unittesters' );
106 $user->addGroup( 'testwriters' );
107 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
109 $rights = $user->getRights();
110 $this->assertContains( 'test', $rights, 'sanity check' );
111 $this->assertContains( 'runtest', $rights, 'sanity check' );
112 $this->assertContains( 'writetest', $rights, 'sanity check' );
113 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
115 // Add a hook manipluating the rights
116 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
117 $rights[] = 'nukeworld';
118 $rights = array_diff( $rights, [ 'writetest' ] );
121 $userWrapper->mRights
= null;
122 $rights = $user->getRights();
123 $this->assertContains( 'test', $rights );
124 $this->assertContains( 'runtest', $rights );
125 $this->assertNotContains( 'writetest', $rights );
126 $this->assertContains( 'nukeworld', $rights );
128 // Add a Session that limits rights
129 $mock = $this->getMockBuilder( stdclass
::class )
130 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
132 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
133 $mock->method( 'getSessionId' )->willReturn(
134 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
136 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
137 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
138 ->setMethods( [ 'getSession' ] )
140 $mockRequest->method( 'getSession' )->willReturn( $session );
141 $userWrapper->mRequest
= $mockRequest;
143 $userWrapper->mRights
= null;
144 $rights = $user->getRights();
145 $this->assertContains( 'test', $rights );
146 $this->assertNotContains( 'runtest', $rights );
147 $this->assertNotContains( 'writetest', $rights );
148 $this->assertNotContains( 'nukeworld', $rights );
152 * @dataProvider provideGetGroupsWithPermission
153 * @covers User::getGroupsWithPermission
155 public function testGetGroupsWithPermission( $expected, $right ) {
156 $result = User
::getGroupsWithPermission( $right );
160 $this->assertEquals( $expected, $result, "Groups with permission $right" );
163 public static function provideGetGroupsWithPermission() {
166 [ 'unittesters', 'testwriters' ],
185 * @dataProvider provideIPs
188 public function testIsIP( $value, $result, $message ) {
189 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
192 public static function provideIPs() {
194 [ '', false, 'Empty string' ],
195 [ ' ', false, 'Blank space' ],
196 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
197 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
198 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
199 [ '203.0.113.0', true, 'IPv4 example' ],
200 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
201 // Not valid IPs but classified as such by MediaWiki for negated asserting
202 // of whether this might be the identifier of a logged-out user or whether
203 // to allow usernames like it.
204 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
205 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
210 * @dataProvider provideUserNames
211 * @covers User::isValidUserName
213 public function testIsValidUserName( $username, $result, $message ) {
214 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
217 public static function provideUserNames() {
219 [ '', false, 'Empty string' ],
220 [ ' ', false, 'Blank space' ],
221 [ 'abcd', false, 'Starts with small letter' ],
222 [ 'Ab/cd', false, 'Contains slash' ],
223 [ 'Ab cd', true, 'Whitespace' ],
224 [ '192.168.1.1', false, 'IP' ],
225 [ 'User:Abcd', false, 'Reserved Namespace' ],
226 [ '12abcd232', true, 'Starts with Numbers' ],
227 [ '?abcd', true, 'Start with ? mark' ],
228 [ '#abcd', false, 'Start with #' ],
229 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
230 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
231 [ 'Ab cd', false, ' Ideographic space' ],
232 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
233 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
234 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
239 * Test, if for all rights a right- message exist,
240 * which is used on Special:ListGroupRights as help text
241 * Extensions and core
243 public function testAllRightsWithMessage() {
244 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
245 $allRights = User
::getAllRights();
246 $allMessageKeys = Language
::getMessageKeysFor( 'en' );
248 $rightsWithMessage = [];
249 foreach ( $allMessageKeys as $message ) {
250 // === 0: must be at beginning of string (position 0)
251 if ( strpos( $message, 'right-' ) === 0 ) {
252 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
257 sort( $rightsWithMessage );
262 'Each user rights (core/extensions) has a corresponding right- message.'
267 * Test User::editCount
269 * @covers User::getEditCount
271 public function testGetEditCount() {
272 $user = $this->getMutableTestUser()->getUser();
274 // let the user have a few (3) edits
275 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
276 for ( $i = 0; $i < 3; $i++
) {
277 $page->doEditContent(
278 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
288 $user->getEditCount(),
289 'After three edits, the user edit count should be 3'
292 // increase the edit count
293 $user->incEditCount();
297 $user->getEditCount(),
298 'After increasing the edit count manually, the user edit count should be 4'
303 * Test User::editCount
305 * @covers User::getEditCount
307 public function testGetEditCountForAnons() {
308 $user = User
::newFromName( 'Anonymous' );
311 $user->getEditCount(),
312 'Edit count starts null for anonymous users.'
315 $user->incEditCount();
318 $user->getEditCount(),
319 'Edit count remains null for anonymous users despite calls to increase it.'
324 * Test User::editCount
326 * @covers User::incEditCount
328 public function testIncEditCount() {
329 $user = $this->getMutableTestUser()->getUser();
330 $user->incEditCount();
332 $reloadedUser = User
::newFromId( $user->getId() );
333 $reloadedUser->incEditCount();
337 $reloadedUser->getEditCount(),
338 'Increasing the edit count after a fresh load leaves the object up to date.'
343 * Test changing user options.
344 * @covers User::setOption
345 * @covers User::getOption
347 public function testOptions() {
348 $user = $this->getMutableTestUser()->getUser();
350 $user->setOption( 'userjs-someoption', 'test' );
351 $user->setOption( 'rclimit', 200 );
352 $user->saveSettings();
354 $user = User
::newFromName( $user->getName() );
355 $user->load( User
::READ_LATEST
);
356 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
357 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
359 $user = User
::newFromName( $user->getName() );
360 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
361 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
362 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
367 * Make sure defaults are loaded when setOption is called.
368 * @covers User::loadOptions
370 public function testAnonOptions() {
371 global $wgDefaultUserOptions;
372 $this->user
->setOption( 'userjs-someoption', 'test' );
373 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
374 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
378 * Test password validity checks. There are 3 checks in core,
379 * - ensure the password meets the minimal length
380 * - ensure the password is not the same as the username
381 * - ensure the username/password combo isn't forbidden
382 * @covers User::checkPasswordValidity()
383 * @covers User::getPasswordValidity()
384 * @covers User::isValidPassword()
386 public function testCheckPasswordValidity() {
387 $this->setMwGlobals( [
388 'wgPasswordPolicy' => [
391 'MinimalPasswordLength' => 8,
392 'MinimumPasswordLengthToLogin' => 1,
393 'PasswordCannotMatchUsername' => 1,
396 'MinimalPasswordLength' => 6,
397 'PasswordCannotMatchUsername' => true,
398 'PasswordCannotMatchBlacklist' => true,
399 'MaximalPasswordLength' => 40,
403 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
404 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
405 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
406 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
407 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
412 $user = static::getTestUser()->getUser();
415 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
418 $this->assertFalse( $user->isValidPassword( 'a' ) );
419 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
420 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
421 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
424 $longPass = str_repeat( 'a', 41 );
425 $this->assertFalse( $user->isValidPassword( $longPass ) );
426 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
427 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
428 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
431 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
432 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
433 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
435 // On the forbidden list
436 $user = User
::newFromName( 'Useruser' );
437 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
438 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
442 * @covers User::getCanonicalName()
443 * @dataProvider provideGetCanonicalName
445 public function testGetCanonicalName( $name, $expectedArray ) {
446 // fake interwiki map for the 'Interwiki prefix' testcase
447 $this->mergeMwGlobalArrayValue( 'wgHooks', [
448 'InterwikiLoadPrefix' => [
449 function ( $prefix, &$iwdata ) {
450 if ( $prefix === 'interwiki' ) {
452 'iw_url' => 'http://example.com/',
462 foreach ( $expectedArray as $validate => $expected ) {
465 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
469 public static function provideGetCanonicalName() {
471 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
472 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
473 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
474 'valid' => false, 'false' => 'Talk:Username' ] ],
475 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
476 'valid' => false, 'false' => 'Interwiki:Username' ] ],
477 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
478 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
479 'usable' => 'Multi spaces' ] ],
480 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
481 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
482 'valid' => false, 'false' => 'In[]valid' ] ],
483 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
484 'false' => 'With / slash' ] ],
489 * @covers User::equals
491 public function testEquals() {
492 $first = $this->getMutableTestUser()->getUser();
493 $second = User
::newFromName( $first->getName() );
495 $this->assertTrue( $first->equals( $first ) );
496 $this->assertTrue( $first->equals( $second ) );
497 $this->assertTrue( $second->equals( $first ) );
499 $third = $this->getMutableTestUser()->getUser();
500 $fourth = $this->getMutableTestUser()->getUser();
502 $this->assertFalse( $third->equals( $fourth ) );
503 $this->assertFalse( $fourth->equals( $third ) );
505 // Test users loaded from db with id
506 $user = $this->getMutableTestUser()->getUser();
507 $fifth = User
::newFromId( $user->getId() );
508 $sixth = User
::newFromName( $user->getName() );
509 $this->assertTrue( $fifth->equals( $sixth ) );
513 * @covers User::getId
515 public function testGetId() {
516 $user = static::getTestUser()->getUser();
517 $this->assertTrue( $user->getId() > 0 );
521 * @covers User::isLoggedIn
522 * @covers User::isAnon
524 public function testLoggedIn() {
525 $user = $this->getMutableTestUser()->getUser();
526 $this->assertTrue( $user->isLoggedIn() );
527 $this->assertFalse( $user->isAnon() );
529 // Non-existent users are perceived as anonymous
530 $user = User
::newFromName( 'UTNonexistent' );
531 $this->assertFalse( $user->isLoggedIn() );
532 $this->assertTrue( $user->isAnon() );
535 $this->assertFalse( $user->isLoggedIn() );
536 $this->assertTrue( $user->isAnon() );
540 * @covers User::checkAndSetTouched
542 public function testCheckAndSetTouched() {
543 $user = $this->getMutableTestUser()->getUser();
544 $user = TestingAccessWrapper
::newFromObject( $user );
545 $this->assertTrue( $user->isLoggedIn() );
547 $touched = $user->getDBTouched();
549 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
550 $this->assertGreaterThan(
551 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
553 $touched = $user->getDBTouched();
555 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
556 $this->assertGreaterThan(
557 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
561 * @covers User::findUsersByGroup
563 public function testFindUsersByGroup() {
564 $users = User
::findUsersByGroup( [] );
565 $this->assertEquals( 0, iterator_count( $users ) );
567 $users = User
::findUsersByGroup( 'foo' );
568 $this->assertEquals( 0, iterator_count( $users ) );
570 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
571 $users = User
::findUsersByGroup( 'foo' );
572 $this->assertEquals( 1, iterator_count( $users ) );
574 $this->assertTrue( $user->equals( $users->current() ) );
576 // arguments have OR relationship
577 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
578 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
579 $this->assertEquals( 2, iterator_count( $users ) );
581 $this->assertTrue( $user->equals( $users->current() ) );
583 $this->assertTrue( $user2->equals( $users->current() ) );
585 // users are not duplicated
586 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
587 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
588 $this->assertEquals( 1, iterator_count( $users ) );
590 $this->assertTrue( $user->equals( $users->current() ) );
594 * When a user is autoblocked a cookie is set with which to track them
595 * in case they log out and change IP addresses.
596 * @link https://phabricator.wikimedia.org/T5233
598 public function testAutoblockCookies() {
599 // Set up the bits of global configuration that we use.
600 $this->setMwGlobals( [
601 'wgCookieSetOnAutoblock' => true,
602 'wgCookiePrefix' => 'wmsitetitle',
603 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
606 // 1. Log in a test user, and block them.
607 $user1tmp = $this->getTestUser()->getUser();
608 $request1 = new FauxRequest();
609 $request1->getSession()->setUser( $user1tmp );
610 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
611 $block = new Block( [
612 'enableAutoblock' => true,
613 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
615 $block->setTarget( $user1tmp );
617 $user1 = User
::newFromSession( $request1 );
618 $user1->mBlock
= $block;
621 // Confirm that the block has been applied as required.
622 $this->assertTrue( $user1->isLoggedIn() );
623 $this->assertTrue( $user1->isBlocked() );
624 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
625 $this->assertTrue( $block->isAutoblocking() );
626 $this->assertGreaterThanOrEqual( 1, $block->getId() );
628 // Test for the desired cookie name, value, and expiry.
629 $cookies = $request1->response()->getCookies();
630 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
631 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
632 $cookieValue = Block
::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
633 $this->assertEquals( $block->getId(), $cookieValue );
635 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
636 $request2 = new FauxRequest();
637 $request2->setCookie( 'BlockID', $block->getCookieValue() );
638 $user2 = User
::newFromSession( $request2 );
640 $this->assertNotEquals( $user1->getId(), $user2->getId() );
641 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
642 $this->assertTrue( $user2->isAnon() );
643 $this->assertFalse( $user2->isLoggedIn() );
644 $this->assertTrue( $user2->isBlocked() );
645 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
646 // Can't directly compare the objects becuase of member type differences.
647 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
648 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
649 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
651 // 3. Finally, set up a request as a new user, and the block should still be applied.
652 $user3tmp = $this->getTestUser()->getUser();
653 $request3 = new FauxRequest();
654 $request3->getSession()->setUser( $user3tmp );
655 $request3->setCookie( 'BlockID', $block->getId() );
656 $user3 = User
::newFromSession( $request3 );
658 $this->assertTrue( $user3->isLoggedIn() );
659 $this->assertTrue( $user3->isBlocked() );
660 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
667 * Make sure that no cookie is set to track autoblocked users
668 * when $wgCookieSetOnAutoblock is false.
670 public function testAutoblockCookiesDisabled() {
671 // Set up the bits of global configuration that we use.
672 $this->setMwGlobals( [
673 'wgCookieSetOnAutoblock' => false,
674 'wgCookiePrefix' => 'wm_no_cookies',
675 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
678 // 1. Log in a test user, and block them.
679 $testUser = $this->getTestUser()->getUser();
680 $request1 = new FauxRequest();
681 $request1->getSession()->setUser( $testUser );
682 $block = new Block( [ 'enableAutoblock' => true ] );
683 $block->setTarget( $testUser );
685 $user = User
::newFromSession( $request1 );
686 $user->mBlock
= $block;
689 // 2. Test that the cookie IS NOT present.
690 $this->assertTrue( $user->isLoggedIn() );
691 $this->assertTrue( $user->isBlocked() );
692 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
693 $this->assertTrue( $block->isAutoblocking() );
694 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
695 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
696 $cookies = $request1->response()->getCookies();
697 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
704 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
705 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
706 * the cookie's should change with it.
708 public function testAutoblockCookieInfiniteExpiry() {
709 $this->setMwGlobals( [
710 'wgCookieSetOnAutoblock' => true,
711 'wgCookiePrefix' => 'wm_infinite_block',
712 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
714 // 1. Log in a test user, and block them indefinitely.
715 $user1Tmp = $this->getTestUser()->getUser();
716 $request1 = new FauxRequest();
717 $request1->getSession()->setUser( $user1Tmp );
718 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
719 $block->setTarget( $user1Tmp );
721 $user1 = User
::newFromSession( $request1 );
722 $user1->mBlock
= $block;
725 // 2. Test the cookie's expiry timestamp.
726 $this->assertTrue( $user1->isLoggedIn() );
727 $this->assertTrue( $user1->isBlocked() );
728 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
729 $this->assertTrue( $block->isAutoblocking() );
730 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
731 $cookies = $request1->response()->getCookies();
732 // Test the cookie's expiry to the nearest minute.
733 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
734 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
735 // Check for expiry dates in a 10-second window, to account for slow testing.
738 $cookies['wm_infinite_blockBlockID']['expire'],
743 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
744 $newExpiry = wfTimestamp() +
2 * 60 * 60;
745 $block->mExpiry
= wfTimestamp( TS_MW
, $newExpiry );
747 $user2tmp = $this->getTestUser()->getUser();
748 $request2 = new FauxRequest();
749 $request2->getSession()->setUser( $user2tmp );
750 $user2 = User
::newFromSession( $request2 );
751 $user2->mBlock
= $block;
753 $cookies = $request2->response()->getCookies();
754 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
755 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
761 public function testSoftBlockRanges() {
764 $this->setMwGlobals( [
765 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
769 // IP isn't in $wgSoftBlockRanges
770 $request = new FauxRequest();
771 $request->setIP( '192.168.0.1' );
772 $wgUser = User
::newFromSession( $request );
773 $this->assertNull( $wgUser->getBlock() );
775 // IP is in $wgSoftBlockRanges
776 $request = new FauxRequest();
777 $request->setIP( '10.20.30.40' );
778 $wgUser = User
::newFromSession( $request );
779 $block = $wgUser->getBlock();
780 $this->assertInstanceOf( Block
::class, $block );
781 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
783 // Make sure the block is really soft
784 $request->getSession()->setUser( $this->getTestUser()->getUser() );
785 $wgUser = User
::newFromSession( $request );
786 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
787 $this->assertNull( $wgUser->getBlock() );
791 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
793 public function testAutoblockCookieInauthentic() {
794 // Set up the bits of global configuration that we use.
795 $this->setMwGlobals( [
796 'wgCookieSetOnAutoblock' => true,
797 'wgCookiePrefix' => 'wmsitetitle',
798 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
801 // 1. Log in a blocked test user.
802 $user1tmp = $this->getTestUser()->getUser();
803 $request1 = new FauxRequest();
804 $request1->getSession()->setUser( $user1tmp );
805 $block = new Block( [ 'enableAutoblock' => true ] );
806 $block->setTarget( $user1tmp );
808 $user1 = User
::newFromSession( $request1 );
809 $user1->mBlock
= $block;
812 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
814 $request2 = new FauxRequest();
815 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
816 $user2 = User
::newFromSession( $request2 );
818 $this->assertTrue( $user2->isAnon() );
819 $this->assertFalse( $user2->isLoggedIn() );
820 $this->assertFalse( $user2->isBlocked() );
827 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
828 * This checks that a non-authenticated cookie still works.
830 public function testAutoblockCookieNoSecretKey() {
831 // Set up the bits of global configuration that we use.
832 $this->setMwGlobals( [
833 'wgCookieSetOnAutoblock' => true,
834 'wgCookiePrefix' => 'wmsitetitle',
835 'wgSecretKey' => null,
838 // 1. Log in a blocked test user.
839 $user1tmp = $this->getTestUser()->getUser();
840 $request1 = new FauxRequest();
841 $request1->getSession()->setUser( $user1tmp );
842 $block = new Block( [ 'enableAutoblock' => true ] );
843 $block->setTarget( $user1tmp );
845 $user1 = User
::newFromSession( $request1 );
846 $user1->mBlock
= $block;
848 $this->assertTrue( $user1->isBlocked() );
850 // 2. Create a new request, set the cookie to just the block ID, and the user should
851 // still get blocked when they log in again.
852 $request2 = new FauxRequest();
853 $request2->setCookie( 'BlockID', $block->getId() );
854 $user2 = User
::newFromSession( $request2 );
856 $this->assertNotEquals( $user1->getId(), $user2->getId() );
857 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
858 $this->assertTrue( $user2->isAnon() );
859 $this->assertFalse( $user2->isLoggedIn() );
860 $this->assertTrue( $user2->isBlocked() );
861 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
867 public function testIsPingLimitable() {
868 $request = new FauxRequest();
869 $request->setIP( '1.2.3.4' );
870 $user = User
::newFromSession( $request );
872 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
873 $this->assertTrue( $user->isPingLimitable() );
875 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
876 $this->assertFalse( $user->isPingLimitable() );
878 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
879 $this->assertFalse( $user->isPingLimitable() );
881 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
882 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
883 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
884 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
885 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
886 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
889 public function provideExperienceLevel() {
891 [ 2, 2, 'newcomer' ],
892 [ 12, 3, 'newcomer' ],
893 [ 8, 5, 'newcomer' ],
894 [ 15, 10, 'learner' ],
895 [ 450, 20, 'learner' ],
896 [ 460, 33, 'learner' ],
897 [ 525, 28, 'learner' ],
898 [ 538, 33, 'experienced' ],
903 * @dataProvider provideExperienceLevel
905 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
906 $this->setMwGlobals( [
907 'wgLearnerEdits' => 10,
908 'wgLearnerMemberSince' => 4,
909 'wgExperiencedUserEdits' => 500,
910 'wgExperiencedUserMemberSince' => 30,
913 $db = wfGetDB( DB_MASTER
);
915 $data = new stdClass();
917 $data->user_name
= 'name';
918 $data->user_real_name
= 'Real Name';
919 $data->user_touched
= 1;
920 $data->user_token
= 'token';
921 $data->user_email
= 'a@a.a';
922 $data->user_email_authenticated
= null;
923 $data->user_email_token
= 'token';
924 $data->user_email_token_expires
= null;
925 $data->user_editcount
= $editCount;
926 $data->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
927 $user = User
::newFromRow( $data );
929 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
932 public function testExperienceLevelAnon() {
933 $user = User
::newFromName( '10.11.12.13', false );
935 $this->assertFalse( $user->getExperienceLevel() );
938 public static function provideIsLocallBlockedProxy() {
940 [ '1.2.3.4', '1.2.3.4' ],
941 [ '1.2.3.4', '1.2.3.0/16' ],
946 * @dataProvider provideIsLocallBlockedProxy
947 * @covers User::isLocallyBlockedProxy
949 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
953 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
961 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
966 'test' => $blockListEntry
969 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
971 $this->hideDeprecated(
972 'IP addresses in the keys of $wgProxyList (found the following IP ' .
973 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
978 $blockListEntry => 'test'
981 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );