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
= $this->getTestUser( [ 'unittesters' ] )->getUser();
31 private function setUpPermissionGlobals() {
32 global $wgGroupPermissions, $wgRevokePermissions;
34 # Data for regular $wgGroupPermissions test
35 $wgGroupPermissions['unittesters'] = [
41 $wgGroupPermissions['testwriters'] = [
47 # Data for regular $wgRevokePermissions test
48 $wgRevokePermissions['formertesters'] = [
52 # For the options test
53 $wgGroupPermissions['*'] = [
54 'editmyoptions' => true,
59 * @covers User::getGroupPermissions
61 public function testGroupPermissions() {
62 $rights = User
::getGroupPermissions( [ 'unittesters' ] );
63 $this->assertContains( 'runtest', $rights );
64 $this->assertNotContains( 'writetest', $rights );
65 $this->assertNotContains( 'modifytest', $rights );
66 $this->assertNotContains( 'nukeworld', $rights );
68 $rights = User
::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
69 $this->assertContains( 'runtest', $rights );
70 $this->assertContains( 'writetest', $rights );
71 $this->assertContains( 'modifytest', $rights );
72 $this->assertNotContains( 'nukeworld', $rights );
76 * @covers User::getGroupPermissions
78 public function testRevokePermissions() {
79 $rights = User
::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
80 $this->assertNotContains( 'runtest', $rights );
81 $this->assertNotContains( 'writetest', $rights );
82 $this->assertNotContains( 'modifytest', $rights );
83 $this->assertNotContains( 'nukeworld', $rights );
87 * @covers User::getRights
89 public function testUserPermissions() {
90 $rights = $this->user
->getRights();
91 $this->assertContains( 'runtest', $rights );
92 $this->assertNotContains( 'writetest', $rights );
93 $this->assertNotContains( 'modifytest', $rights );
94 $this->assertNotContains( 'nukeworld', $rights );
98 * @covers User::getRights
100 public function testUserGetRightsHooks() {
101 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
102 $userWrapper = TestingAccessWrapper
::newFromObject( $user );
104 $rights = $user->getRights();
105 $this->assertContains( 'test', $rights, 'sanity check' );
106 $this->assertContains( 'runtest', $rights, 'sanity check' );
107 $this->assertContains( 'writetest', $rights, 'sanity check' );
108 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
110 // Add a hook manipluating the rights
111 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
112 $rights[] = 'nukeworld';
113 $rights = array_diff( $rights, [ 'writetest' ] );
116 $userWrapper->mRights
= null;
117 $rights = $user->getRights();
118 $this->assertContains( 'test', $rights );
119 $this->assertContains( 'runtest', $rights );
120 $this->assertNotContains( 'writetest', $rights );
121 $this->assertContains( 'nukeworld', $rights );
123 // Add a Session that limits rights
124 $mock = $this->getMockBuilder( stdclass
::class )
125 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
127 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
128 $mock->method( 'getSessionId' )->willReturn(
129 new MediaWiki\Session\
SessionId( str_repeat( 'X', 32 ) )
131 $session = MediaWiki\Session\TestUtils
::getDummySession( $mock );
132 $mockRequest = $this->getMockBuilder( FauxRequest
::class )
133 ->setMethods( [ 'getSession' ] )
135 $mockRequest->method( 'getSession' )->willReturn( $session );
136 $userWrapper->mRequest
= $mockRequest;
138 $userWrapper->mRights
= null;
139 $rights = $user->getRights();
140 $this->assertContains( 'test', $rights );
141 $this->assertNotContains( 'runtest', $rights );
142 $this->assertNotContains( 'writetest', $rights );
143 $this->assertNotContains( 'nukeworld', $rights );
147 * @dataProvider provideGetGroupsWithPermission
148 * @covers User::getGroupsWithPermission
150 public function testGetGroupsWithPermission( $expected, $right ) {
151 $result = User
::getGroupsWithPermission( $right );
155 $this->assertEquals( $expected, $result, "Groups with permission $right" );
158 public static function provideGetGroupsWithPermission() {
161 [ 'unittesters', 'testwriters' ],
180 * @dataProvider provideIPs
183 public function testIsIP( $value, $result, $message ) {
184 $this->assertEquals( $this->user
->isIP( $value ), $result, $message );
187 public static function provideIPs() {
189 [ '', false, 'Empty string' ],
190 [ ' ', false, 'Blank space' ],
191 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
192 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
193 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
194 [ '203.0.113.0', true, 'IPv4 example' ],
195 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
196 // Not valid IPs but classified as such by MediaWiki for negated asserting
197 // of whether this might be the identifier of a logged-out user or whether
198 // to allow usernames like it.
199 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
200 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
205 * @dataProvider provideUserNames
206 * @covers User::isValidUserName
208 public function testIsValidUserName( $username, $result, $message ) {
209 $this->assertEquals( $this->user
->isValidUserName( $username ), $result, $message );
212 public static function provideUserNames() {
214 [ '', false, 'Empty string' ],
215 [ ' ', false, 'Blank space' ],
216 [ 'abcd', false, 'Starts with small letter' ],
217 [ 'Ab/cd', false, 'Contains slash' ],
218 [ 'Ab cd', true, 'Whitespace' ],
219 [ '192.168.1.1', false, 'IP' ],
220 [ '116.17.184.5/32', false, 'IP range' ],
221 [ '::e:f:2001/96', false, 'IPv6 range' ],
222 [ 'User:Abcd', false, 'Reserved Namespace' ],
223 [ '12abcd232', true, 'Starts with Numbers' ],
224 [ '?abcd', true, 'Start with ? mark' ],
225 [ '#abcd', false, 'Start with #' ],
226 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
227 [ 'ജോസ്തോമസ്', false, 'ZWNJ- Format control character' ],
228 [ 'Ab cd', false, ' Ideographic space' ],
229 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
230 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
231 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
236 * Test, if for all rights a right- message exist,
237 * which is used on Special:ListGroupRights as help text
238 * Extensions and core
242 public function testAllRightsWithMessage() {
243 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
244 $allRights = User
::getAllRights();
245 $allMessageKeys = Language
::getMessageKeysFor( 'en' );
247 $rightsWithMessage = [];
248 foreach ( $allMessageKeys as $message ) {
249 // === 0: must be at beginning of string (position 0)
250 if ( strpos( $message, 'right-' ) === 0 ) {
251 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
256 sort( $rightsWithMessage );
261 'Each user rights (core/extensions) has a corresponding right- message.'
266 * Test User::editCount
268 * @covers User::getEditCount
270 public function testGetEditCount() {
271 $user = $this->getMutableTestUser()->getUser();
273 // let the user have a few (3) edits
274 $page = WikiPage
::factory( Title
::newFromText( 'Help:UserTest_EditCount' ) );
275 for ( $i = 0; $i < 3; $i++
) {
276 $page->doEditContent(
277 ContentHandler
::makeContent( (string)$i, $page->getTitle() ),
287 $user->getEditCount(),
288 'After three edits, the user edit count should be 3'
291 // increase the edit count
292 $user->incEditCount();
296 $user->getEditCount(),
297 'After increasing the edit count manually, the user edit count should be 4'
302 * Test User::editCount
304 * @covers User::getEditCount
306 public function testGetEditCountForAnons() {
307 $user = User
::newFromName( 'Anonymous' );
310 $user->getEditCount(),
311 'Edit count starts null for anonymous users.'
314 $user->incEditCount();
317 $user->getEditCount(),
318 'Edit count remains null for anonymous users despite calls to increase it.'
323 * Test User::editCount
325 * @covers User::incEditCount
327 public function testIncEditCount() {
328 $user = $this->getMutableTestUser()->getUser();
329 $user->incEditCount();
331 $reloadedUser = User
::newFromId( $user->getId() );
332 $reloadedUser->incEditCount();
336 $reloadedUser->getEditCount(),
337 'Increasing the edit count after a fresh load leaves the object up to date.'
342 * Test changing user options.
343 * @covers User::setOption
344 * @covers User::getOption
346 public function testOptions() {
347 $user = $this->getMutableTestUser()->getUser();
349 $user->setOption( 'userjs-someoption', 'test' );
350 $user->setOption( 'rclimit', 200 );
351 $user->saveSettings();
353 $user = User
::newFromName( $user->getName() );
354 $user->load( User
::READ_LATEST
);
355 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
356 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
358 $user = User
::newFromName( $user->getName() );
359 MediaWikiServices
::getInstance()->getMainWANObjectCache()->clearProcessCache();
360 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
361 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
366 * Make sure defaults are loaded when setOption is called.
367 * @covers User::loadOptions
369 public function testAnonOptions() {
370 global $wgDefaultUserOptions;
371 $this->user
->setOption( 'userjs-someoption', 'test' );
372 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user
->getOption( 'rclimit' ) );
373 $this->assertEquals( 'test', $this->user
->getOption( 'userjs-someoption' ) );
377 * Test password validity checks. There are 3 checks in core,
378 * - ensure the password meets the minimal length
379 * - ensure the password is not the same as the username
380 * - ensure the username/password combo isn't forbidden
381 * @covers User::checkPasswordValidity()
382 * @covers User::getPasswordValidity()
383 * @covers User::isValidPassword()
385 public function testCheckPasswordValidity() {
386 $this->setMwGlobals( [
387 'wgPasswordPolicy' => [
390 'MinimalPasswordLength' => 8,
391 'MinimumPasswordLengthToLogin' => 1,
392 'PasswordCannotMatchUsername' => 1,
395 'MinimalPasswordLength' => 6,
396 'PasswordCannotMatchUsername' => true,
397 'PasswordCannotMatchBlacklist' => true,
398 'MaximalPasswordLength' => 40,
402 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
403 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
404 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
405 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
406 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
411 $user = static::getTestUser()->getUser();
414 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
417 $this->assertFalse( $user->isValidPassword( 'a' ) );
418 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
419 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
420 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
423 $longPass = str_repeat( 'a', 41 );
424 $this->assertFalse( $user->isValidPassword( $longPass ) );
425 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
426 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
427 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
430 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
431 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
432 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
434 // On the forbidden list
435 $user = User
::newFromName( 'Useruser' );
436 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
437 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
441 * @covers User::getCanonicalName()
442 * @dataProvider provideGetCanonicalName
444 public function testGetCanonicalName( $name, $expectedArray ) {
445 // fake interwiki map for the 'Interwiki prefix' testcase
446 $this->mergeMwGlobalArrayValue( 'wgHooks', [
447 'InterwikiLoadPrefix' => [
448 function ( $prefix, &$iwdata ) {
449 if ( $prefix === 'interwiki' ) {
451 'iw_url' => 'http://example.com/',
461 foreach ( $expectedArray as $validate => $expected ) {
464 User
::getCanonicalName( $name, $validate === 'false' ?
false : $validate ), $validate );
468 public static function provideGetCanonicalName() {
470 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
471 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
472 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
473 'valid' => false, 'false' => 'Talk:Username' ] ],
474 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
475 'valid' => false, 'false' => 'Interwiki:Username' ] ],
476 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
477 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
478 'usable' => 'Multi spaces' ] ],
479 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
480 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
481 'valid' => false, 'false' => 'In[]valid' ] ],
482 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
483 'false' => 'With / slash' ] ],
488 * @covers User::equals
490 public function testEquals() {
491 $first = $this->getMutableTestUser()->getUser();
492 $second = User
::newFromName( $first->getName() );
494 $this->assertTrue( $first->equals( $first ) );
495 $this->assertTrue( $first->equals( $second ) );
496 $this->assertTrue( $second->equals( $first ) );
498 $third = $this->getMutableTestUser()->getUser();
499 $fourth = $this->getMutableTestUser()->getUser();
501 $this->assertFalse( $third->equals( $fourth ) );
502 $this->assertFalse( $fourth->equals( $third ) );
504 // Test users loaded from db with id
505 $user = $this->getMutableTestUser()->getUser();
506 $fifth = User
::newFromId( $user->getId() );
507 $sixth = User
::newFromName( $user->getName() );
508 $this->assertTrue( $fifth->equals( $sixth ) );
512 * @covers User::getId
514 public function testGetId() {
515 $user = static::getTestUser()->getUser();
516 $this->assertTrue( $user->getId() > 0 );
520 * @covers User::isLoggedIn
521 * @covers User::isAnon
523 public function testLoggedIn() {
524 $user = $this->getMutableTestUser()->getUser();
525 $this->assertTrue( $user->isLoggedIn() );
526 $this->assertFalse( $user->isAnon() );
528 // Non-existent users are perceived as anonymous
529 $user = User
::newFromName( 'UTNonexistent' );
530 $this->assertFalse( $user->isLoggedIn() );
531 $this->assertTrue( $user->isAnon() );
534 $this->assertFalse( $user->isLoggedIn() );
535 $this->assertTrue( $user->isAnon() );
539 * @covers User::checkAndSetTouched
541 public function testCheckAndSetTouched() {
542 $user = $this->getMutableTestUser()->getUser();
543 $user = TestingAccessWrapper
::newFromObject( $user );
544 $this->assertTrue( $user->isLoggedIn() );
546 $touched = $user->getDBTouched();
548 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
549 $this->assertGreaterThan(
550 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
552 $touched = $user->getDBTouched();
554 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
555 $this->assertGreaterThan(
556 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
560 * @covers User::findUsersByGroup
562 public function testFindUsersByGroup() {
563 $users = User
::findUsersByGroup( [] );
564 $this->assertEquals( 0, iterator_count( $users ) );
566 $users = User
::findUsersByGroup( 'foo' );
567 $this->assertEquals( 0, iterator_count( $users ) );
569 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
570 $users = User
::findUsersByGroup( 'foo' );
571 $this->assertEquals( 1, iterator_count( $users ) );
573 $this->assertTrue( $user->equals( $users->current() ) );
575 // arguments have OR relationship
576 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
577 $users = User
::findUsersByGroup( [ 'foo', 'bar' ] );
578 $this->assertEquals( 2, iterator_count( $users ) );
580 $this->assertTrue( $user->equals( $users->current() ) );
582 $this->assertTrue( $user2->equals( $users->current() ) );
584 // users are not duplicated
585 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
586 $users = User
::findUsersByGroup( [ 'baz', 'boom' ] );
587 $this->assertEquals( 1, iterator_count( $users ) );
589 $this->assertTrue( $user->equals( $users->current() ) );
593 * When a user is autoblocked a cookie is set with which to track them
594 * in case they log out and change IP addresses.
595 * @link https://phabricator.wikimedia.org/T5233
597 public function testAutoblockCookies() {
598 // Set up the bits of global configuration that we use.
599 $this->setMwGlobals( [
600 'wgCookieSetOnAutoblock' => true,
601 'wgCookiePrefix' => 'wmsitetitle',
602 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
605 // Unregister the hooks for proper unit testing
606 $this->mergeMwGlobalArrayValue( 'wgHooks', [
607 'PerformRetroactiveAutoblock' => []
610 // 1. Log in a test user, and block them.
611 $userBlocker = $this->getTestSysop()->getUser();
612 $user1tmp = $this->getTestUser()->getUser();
613 $request1 = new FauxRequest();
614 $request1->getSession()->setUser( $user1tmp );
615 $expiryFiveHours = wfTimestamp() +
( 5 * 60 * 60 );
616 $block = new Block( [
617 'enableAutoblock' => true,
618 'expiry' => wfTimestamp( TS_MW
, $expiryFiveHours ),
620 $block->setTarget( $user1tmp );
621 $block->setBlocker( $userBlocker );
622 $res = $block->insert();
623 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
624 $user1 = User
::newFromSession( $request1 );
625 $user1->mBlock
= $block;
628 // Confirm that the block has been applied as required.
629 $this->assertTrue( $user1->isLoggedIn() );
630 $this->assertTrue( $user1->isBlocked() );
631 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
632 $this->assertTrue( $block->isAutoblocking() );
633 $this->assertGreaterThanOrEqual( 1, $block->getId() );
635 // Test for the desired cookie name, value, and expiry.
636 $cookies = $request1->response()->getCookies();
637 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
638 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
639 $cookieValue = Block
::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
640 $this->assertEquals( $block->getId(), $cookieValue );
642 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
643 $request2 = new FauxRequest();
644 $request2->setCookie( 'BlockID', $block->getCookieValue() );
645 $user2 = User
::newFromSession( $request2 );
647 $this->assertNotEquals( $user1->getId(), $user2->getId() );
648 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
649 $this->assertTrue( $user2->isAnon() );
650 $this->assertFalse( $user2->isLoggedIn() );
651 $this->assertTrue( $user2->isBlocked() );
652 // Non-strict type-check.
653 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
654 // Can't directly compare the objects becuase of member type differences.
655 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
656 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
657 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
659 // 3. Finally, set up a request as a new user, and the block should still be applied.
660 $user3tmp = $this->getTestUser()->getUser();
661 $request3 = new FauxRequest();
662 $request3->getSession()->setUser( $user3tmp );
663 $request3->setCookie( 'BlockID', $block->getId() );
664 $user3 = User
::newFromSession( $request3 );
666 $this->assertTrue( $user3->isLoggedIn() );
667 $this->assertTrue( $user3->isBlocked() );
668 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
675 * Make sure that no cookie is set to track autoblocked users
676 * when $wgCookieSetOnAutoblock is false.
678 public function testAutoblockCookiesDisabled() {
679 // Set up the bits of global configuration that we use.
680 $this->setMwGlobals( [
681 'wgCookieSetOnAutoblock' => false,
682 'wgCookiePrefix' => 'wm_no_cookies',
683 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
686 // Unregister the hooks for proper unit testing
687 $this->mergeMwGlobalArrayValue( 'wgHooks', [
688 'PerformRetroactiveAutoblock' => []
691 // 1. Log in a test user, and block them.
692 $userBlocker = $this->getTestSysop()->getUser();
693 $testUser = $this->getTestUser()->getUser();
694 $request1 = new FauxRequest();
695 $request1->getSession()->setUser( $testUser );
696 $block = new Block( [ 'enableAutoblock' => true ] );
697 $block->setTarget( $testUser );
698 $block->setBlocker( $userBlocker );
699 $res = $block->insert();
700 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
701 $user = User
::newFromSession( $request1 );
702 $user->mBlock
= $block;
705 // 2. Test that the cookie IS NOT present.
706 $this->assertTrue( $user->isLoggedIn() );
707 $this->assertTrue( $user->isBlocked() );
708 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
709 $this->assertTrue( $block->isAutoblocking() );
710 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
711 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
712 $cookies = $request1->response()->getCookies();
713 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
720 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
721 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
722 * the cookie's should change with it.
724 public function testAutoblockCookieInfiniteExpiry() {
725 $this->setMwGlobals( [
726 'wgCookieSetOnAutoblock' => true,
727 'wgCookiePrefix' => 'wm_infinite_block',
728 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
731 // Unregister the hooks for proper unit testing
732 $this->mergeMwGlobalArrayValue( 'wgHooks', [
733 'PerformRetroactiveAutoblock' => []
736 // 1. Log in a test user, and block them indefinitely.
737 $userBlocker = $this->getTestSysop()->getUser();
738 $user1Tmp = $this->getTestUser()->getUser();
739 $request1 = new FauxRequest();
740 $request1->getSession()->setUser( $user1Tmp );
741 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
742 $block->setTarget( $user1Tmp );
743 $block->setBlocker( $userBlocker );
744 $res = $block->insert();
745 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
746 $user1 = User
::newFromSession( $request1 );
747 $user1->mBlock
= $block;
750 // 2. Test the cookie's expiry timestamp.
751 $this->assertTrue( $user1->isLoggedIn() );
752 $this->assertTrue( $user1->isBlocked() );
753 $this->assertEquals( Block
::TYPE_USER
, $block->getType() );
754 $this->assertTrue( $block->isAutoblocking() );
755 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
756 $cookies = $request1->response()->getCookies();
757 // Test the cookie's expiry to the nearest minute.
758 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
759 $expOneDay = wfTimestamp() +
( 24 * 60 * 60 );
760 // Check for expiry dates in a 10-second window, to account for slow testing.
763 $cookies['wm_infinite_blockBlockID']['expire'],
768 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
769 $newExpiry = wfTimestamp() +
2 * 60 * 60;
770 $block->mExpiry
= wfTimestamp( TS_MW
, $newExpiry );
772 $user2tmp = $this->getTestUser()->getUser();
773 $request2 = new FauxRequest();
774 $request2->getSession()->setUser( $user2tmp );
775 $user2 = User
::newFromSession( $request2 );
776 $user2->mBlock
= $block;
778 $cookies = $request2->response()->getCookies();
779 $this->assertEquals( wfTimestamp( TS_MW
, $newExpiry ), $block->getExpiry() );
780 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
786 public function testSoftBlockRanges() {
789 $this->setMwGlobals( [
790 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
794 // IP isn't in $wgSoftBlockRanges
795 $request = new FauxRequest();
796 $request->setIP( '192.168.0.1' );
797 $wgUser = User
::newFromSession( $request );
798 $this->assertNull( $wgUser->getBlock() );
800 // IP is in $wgSoftBlockRanges
801 $request = new FauxRequest();
802 $request->setIP( '10.20.30.40' );
803 $wgUser = User
::newFromSession( $request );
804 $block = $wgUser->getBlock();
805 $this->assertInstanceOf( Block
::class, $block );
806 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
808 // Make sure the block is really soft
809 $request->getSession()->setUser( $this->getTestUser()->getUser() );
810 $wgUser = User
::newFromSession( $request );
811 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
812 $this->assertNull( $wgUser->getBlock() );
816 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
818 public function testAutoblockCookieInauthentic() {
819 // Set up the bits of global configuration that we use.
820 $this->setMwGlobals( [
821 'wgCookieSetOnAutoblock' => true,
822 'wgCookiePrefix' => 'wmsitetitle',
823 'wgSecretKey' => MWCryptRand
::generateHex( 64, true ),
826 // Unregister the hooks for proper unit testing
827 $this->mergeMwGlobalArrayValue( 'wgHooks', [
828 'PerformRetroactiveAutoblock' => []
831 // 1. Log in a blocked test user.
832 $userBlocker = $this->getTestSysop()->getUser();
833 $user1tmp = $this->getTestUser()->getUser();
834 $request1 = new FauxRequest();
835 $request1->getSession()->setUser( $user1tmp );
836 $block = new Block( [ 'enableAutoblock' => true ] );
837 $block->setTarget( $user1tmp );
838 $block->setBlocker( $userBlocker );
839 $res = $block->insert();
840 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
841 $user1 = User
::newFromSession( $request1 );
842 $user1->mBlock
= $block;
845 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
847 $request2 = new FauxRequest();
848 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
849 $user2 = User
::newFromSession( $request2 );
851 $this->assertTrue( $user2->isAnon() );
852 $this->assertFalse( $user2->isLoggedIn() );
853 $this->assertFalse( $user2->isBlocked() );
860 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
861 * This checks that a non-authenticated cookie still works.
863 public function testAutoblockCookieNoSecretKey() {
864 // Set up the bits of global configuration that we use.
865 $this->setMwGlobals( [
866 'wgCookieSetOnAutoblock' => true,
867 'wgCookiePrefix' => 'wmsitetitle',
868 'wgSecretKey' => null,
871 // Unregister the hooks for proper unit testing
872 $this->mergeMwGlobalArrayValue( 'wgHooks', [
873 'PerformRetroactiveAutoblock' => []
876 // 1. Log in a blocked test user.
877 $userBlocker = $this->getTestSysop()->getUser();
878 $user1tmp = $this->getTestUser()->getUser();
879 $request1 = new FauxRequest();
880 $request1->getSession()->setUser( $user1tmp );
881 $block = new Block( [ 'enableAutoblock' => true ] );
882 $block->setTarget( $user1tmp );
883 $block->setBlocker( $userBlocker );
884 $res = $block->insert();
885 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
886 $user1 = User
::newFromSession( $request1 );
887 $user1->mBlock
= $block;
889 $this->assertTrue( $user1->isBlocked() );
891 // 2. Create a new request, set the cookie to just the block ID, and the user should
892 // still get blocked when they log in again.
893 $request2 = new FauxRequest();
894 $request2->setCookie( 'BlockID', $block->getId() );
895 $user2 = User
::newFromSession( $request2 );
897 $this->assertNotEquals( $user1->getId(), $user2->getId() );
898 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
899 $this->assertTrue( $user2->isAnon() );
900 $this->assertFalse( $user2->isLoggedIn() );
901 $this->assertTrue( $user2->isBlocked() );
902 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
909 * @covers User::isPingLimitable
911 public function testIsPingLimitable() {
912 $request = new FauxRequest();
913 $request->setIP( '1.2.3.4' );
914 $user = User
::newFromSession( $request );
916 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
917 $this->assertTrue( $user->isPingLimitable() );
919 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
920 $this->assertFalse( $user->isPingLimitable() );
922 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
923 $this->assertFalse( $user->isPingLimitable() );
925 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
926 $noRateLimitUser = $this->getMockBuilder( User
::class )->disableOriginalConstructor()
927 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
928 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
929 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
930 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
933 public function provideExperienceLevel() {
935 [ 2, 2, 'newcomer' ],
936 [ 12, 3, 'newcomer' ],
937 [ 8, 5, 'newcomer' ],
938 [ 15, 10, 'learner' ],
939 [ 450, 20, 'learner' ],
940 [ 460, 33, 'learner' ],
941 [ 525, 28, 'learner' ],
942 [ 538, 33, 'experienced' ],
947 * @covers User::getExperienceLevel
948 * @dataProvider provideExperienceLevel
950 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
951 $this->setMwGlobals( [
952 'wgLearnerEdits' => 10,
953 'wgLearnerMemberSince' => 4,
954 'wgExperiencedUserEdits' => 500,
955 'wgExperiencedUserMemberSince' => 30,
958 $db = wfGetDB( DB_MASTER
);
960 $data = new stdClass();
962 $data->user_name
= 'name';
963 $data->user_real_name
= 'Real Name';
964 $data->user_touched
= 1;
965 $data->user_token
= 'token';
966 $data->user_email
= 'a@a.a';
967 $data->user_email_authenticated
= null;
968 $data->user_email_token
= 'token';
969 $data->user_email_token_expires
= null;
970 $data->user_editcount
= $editCount;
971 $data->user_registration
= $db->timestamp( time() - $memberSince * 86400 );
972 $user = User
::newFromRow( $data );
974 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
978 * @covers User::getExperienceLevel
980 public function testExperienceLevelAnon() {
981 $user = User
::newFromName( '10.11.12.13', false );
983 $this->assertFalse( $user->getExperienceLevel() );
986 public static function provideIsLocallBlockedProxy() {
988 [ '1.2.3.4', '1.2.3.4' ],
989 [ '1.2.3.4', '1.2.3.0/16' ],
994 * @dataProvider provideIsLocallBlockedProxy
995 * @covers User::isLocallyBlockedProxy
997 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
1001 $this->assertFalse( User
::isLocallyBlockedProxy( $ip ) );
1003 $this->setMwGlobals(
1009 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1011 $this->setMwGlobals(
1014 'test' => $blockListEntry
1017 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );
1019 $this->hideDeprecated(
1020 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1021 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1023 $this->setMwGlobals(
1026 $blockListEntry => 'test'
1029 $this->assertTrue( User
::isLocallyBlockedProxy( $ip ) );