rdbms: Rename "memCache" to "memStash" in LBFactory
[mediawiki.git] / tests / phpunit / includes / user / UserTest.php
blobb58d71cfa180f6919783b5e8b0b5d677e61647b0
1 <?php
3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
6 use MediaWiki\MediaWikiServices;
7 use Wikimedia\TestingAccessWrapper;
9 /**
10 * @group Database
12 class UserTest extends MediaWikiTestCase {
13 /**
14 * @var User
16 protected $user;
18 protected function setUp() {
19 parent::setUp();
21 $this->setMwGlobals( [
22 'wgGroupPermissions' => [],
23 'wgRevokePermissions' => [],
24 ] );
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'] = [
36 'test' => true,
37 'runtest' => true,
38 'writetest' => false,
39 'nukeworld' => false,
41 $wgGroupPermissions['testwriters'] = [
42 'test' => true,
43 'writetest' => true,
44 'modifytest' => true,
47 # Data for regular $wgRevokePermissions test
48 $wgRevokePermissions['formertesters'] = [
49 'runtest' => true,
52 # For the options test
53 $wgGroupPermissions['*'] = [
54 'editmyoptions' => true,
58 /**
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 );
75 /**
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 );
86 /**
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 );
97 /**
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' ] );
114 } ] ] );
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' ] )
126 ->getMock();
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' ] )
134 ->getMock();
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 );
152 sort( $result );
153 sort( $expected );
155 $this->assertEquals( $expected, $result, "Groups with permission $right" );
158 public static function provideGetGroupsWithPermission() {
159 return [
161 [ 'unittesters', 'testwriters' ],
162 'test'
165 [ 'unittesters' ],
166 'runtest'
169 [ 'testwriters' ],
170 'writetest'
173 [ 'testwriters' ],
174 'modifytest'
180 * @dataProvider provideIPs
181 * @covers User::isIP
183 public function testIsIP( $value, $result, $message ) {
184 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
187 public static function provideIPs() {
188 return [
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() {
213 return [
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 [ 'User:Abcd', false, 'Reserved Namespace' ],
221 [ '12abcd232', true, 'Starts with Numbers' ],
222 [ '?abcd', true, 'Start with ? mark' ],
223 [ '#abcd', false, 'Start with #' ],
224 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
225 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
226 [ 'Ab cd', false, ' Ideographic space' ],
227 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
228 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
229 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
234 * Test, if for all rights a right- message exist,
235 * which is used on Special:ListGroupRights as help text
236 * Extensions and core
238 public function testAllRightsWithMessage() {
239 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
240 $allRights = User::getAllRights();
241 $allMessageKeys = Language::getMessageKeysFor( 'en' );
243 $rightsWithMessage = [];
244 foreach ( $allMessageKeys as $message ) {
245 // === 0: must be at beginning of string (position 0)
246 if ( strpos( $message, 'right-' ) === 0 ) {
247 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
251 sort( $allRights );
252 sort( $rightsWithMessage );
254 $this->assertEquals(
255 $allRights,
256 $rightsWithMessage,
257 'Each user rights (core/extensions) has a corresponding right- message.'
262 * Test User::editCount
263 * @group medium
264 * @covers User::getEditCount
266 public function testGetEditCount() {
267 $user = $this->getMutableTestUser()->getUser();
269 // let the user have a few (3) edits
270 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
271 for ( $i = 0; $i < 3; $i++ ) {
272 $page->doEditContent(
273 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
274 'test',
276 false,
277 $user
281 $this->assertEquals(
283 $user->getEditCount(),
284 'After three edits, the user edit count should be 3'
287 // increase the edit count
288 $user->incEditCount();
290 $this->assertEquals(
292 $user->getEditCount(),
293 'After increasing the edit count manually, the user edit count should be 4'
298 * Test User::editCount
299 * @group medium
300 * @covers User::getEditCount
302 public function testGetEditCountForAnons() {
303 $user = User::newFromName( 'Anonymous' );
305 $this->assertNull(
306 $user->getEditCount(),
307 'Edit count starts null for anonymous users.'
310 $user->incEditCount();
312 $this->assertNull(
313 $user->getEditCount(),
314 'Edit count remains null for anonymous users despite calls to increase it.'
319 * Test User::editCount
320 * @group medium
321 * @covers User::incEditCount
323 public function testIncEditCount() {
324 $user = $this->getMutableTestUser()->getUser();
325 $user->incEditCount();
327 $reloadedUser = User::newFromId( $user->getId() );
328 $reloadedUser->incEditCount();
330 $this->assertEquals(
332 $reloadedUser->getEditCount(),
333 'Increasing the edit count after a fresh load leaves the object up to date.'
338 * Test changing user options.
339 * @covers User::setOption
340 * @covers User::getOption
342 public function testOptions() {
343 $user = $this->getMutableTestUser()->getUser();
345 $user->setOption( 'userjs-someoption', 'test' );
346 $user->setOption( 'rclimit', 200 );
347 $user->saveSettings();
349 $user = User::newFromName( $user->getName() );
350 $user->load( User::READ_LATEST );
351 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
352 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
354 $user = User::newFromName( $user->getName() );
355 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
356 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
357 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
361 * T39963
362 * Make sure defaults are loaded when setOption is called.
363 * @covers User::loadOptions
365 public function testAnonOptions() {
366 global $wgDefaultUserOptions;
367 $this->user->setOption( 'userjs-someoption', 'test' );
368 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
369 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
373 * Test password validity checks. There are 3 checks in core,
374 * - ensure the password meets the minimal length
375 * - ensure the password is not the same as the username
376 * - ensure the username/password combo isn't forbidden
377 * @covers User::checkPasswordValidity()
378 * @covers User::getPasswordValidity()
379 * @covers User::isValidPassword()
381 public function testCheckPasswordValidity() {
382 $this->setMwGlobals( [
383 'wgPasswordPolicy' => [
384 'policies' => [
385 'sysop' => [
386 'MinimalPasswordLength' => 8,
387 'MinimumPasswordLengthToLogin' => 1,
388 'PasswordCannotMatchUsername' => 1,
390 'default' => [
391 'MinimalPasswordLength' => 6,
392 'PasswordCannotMatchUsername' => true,
393 'PasswordCannotMatchBlacklist' => true,
394 'MaximalPasswordLength' => 40,
397 'checks' => [
398 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
399 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
400 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
401 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
402 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
405 ] );
407 $user = static::getTestUser()->getUser();
409 // Sanity
410 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
412 // Minimum length
413 $this->assertFalse( $user->isValidPassword( 'a' ) );
414 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
415 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
416 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
418 // Maximum length
419 $longPass = str_repeat( 'a', 41 );
420 $this->assertFalse( $user->isValidPassword( $longPass ) );
421 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
422 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
423 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
425 // Matches username
426 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
427 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
428 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
430 // On the forbidden list
431 $user = User::newFromName( 'Useruser' );
432 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
433 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
437 * @covers User::getCanonicalName()
438 * @dataProvider provideGetCanonicalName
440 public function testGetCanonicalName( $name, $expectedArray ) {
441 // fake interwiki map for the 'Interwiki prefix' testcase
442 $this->mergeMwGlobalArrayValue( 'wgHooks', [
443 'InterwikiLoadPrefix' => [
444 function ( $prefix, &$iwdata ) {
445 if ( $prefix === 'interwiki' ) {
446 $iwdata = [
447 'iw_url' => 'http://example.com/',
448 'iw_local' => 0,
449 'iw_trans' => 0,
451 return false;
455 ] );
457 foreach ( $expectedArray as $validate => $expected ) {
458 $this->assertEquals(
459 $expected,
460 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
464 public static function provideGetCanonicalName() {
465 return [
466 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
467 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
468 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
469 'valid' => false, 'false' => 'Talk:Username' ] ],
470 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
471 'valid' => false, 'false' => 'Interwiki:Username' ] ],
472 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
473 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
474 'usable' => 'Multi spaces' ] ],
475 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
476 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
477 'valid' => false, 'false' => 'In[]valid' ] ],
478 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
479 'false' => 'With / slash' ] ],
484 * @covers User::equals
486 public function testEquals() {
487 $first = $this->getMutableTestUser()->getUser();
488 $second = User::newFromName( $first->getName() );
490 $this->assertTrue( $first->equals( $first ) );
491 $this->assertTrue( $first->equals( $second ) );
492 $this->assertTrue( $second->equals( $first ) );
494 $third = $this->getMutableTestUser()->getUser();
495 $fourth = $this->getMutableTestUser()->getUser();
497 $this->assertFalse( $third->equals( $fourth ) );
498 $this->assertFalse( $fourth->equals( $third ) );
500 // Test users loaded from db with id
501 $user = $this->getMutableTestUser()->getUser();
502 $fifth = User::newFromId( $user->getId() );
503 $sixth = User::newFromName( $user->getName() );
504 $this->assertTrue( $fifth->equals( $sixth ) );
508 * @covers User::getId
510 public function testGetId() {
511 $user = static::getTestUser()->getUser();
512 $this->assertTrue( $user->getId() > 0 );
516 * @covers User::isLoggedIn
517 * @covers User::isAnon
519 public function testLoggedIn() {
520 $user = $this->getMutableTestUser()->getUser();
521 $this->assertTrue( $user->isLoggedIn() );
522 $this->assertFalse( $user->isAnon() );
524 // Non-existent users are perceived as anonymous
525 $user = User::newFromName( 'UTNonexistent' );
526 $this->assertFalse( $user->isLoggedIn() );
527 $this->assertTrue( $user->isAnon() );
529 $user = new User;
530 $this->assertFalse( $user->isLoggedIn() );
531 $this->assertTrue( $user->isAnon() );
535 * @covers User::checkAndSetTouched
537 public function testCheckAndSetTouched() {
538 $user = $this->getMutableTestUser()->getUser();
539 $user = TestingAccessWrapper::newFromObject( $user );
540 $this->assertTrue( $user->isLoggedIn() );
542 $touched = $user->getDBTouched();
543 $this->assertTrue(
544 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
545 $this->assertGreaterThan(
546 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
548 $touched = $user->getDBTouched();
549 $this->assertTrue(
550 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
551 $this->assertGreaterThan(
552 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
556 * @covers User::findUsersByGroup
558 public function testFindUsersByGroup() {
559 $users = User::findUsersByGroup( [] );
560 $this->assertEquals( 0, iterator_count( $users ) );
562 $users = User::findUsersByGroup( 'foo' );
563 $this->assertEquals( 0, iterator_count( $users ) );
565 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
566 $users = User::findUsersByGroup( 'foo' );
567 $this->assertEquals( 1, iterator_count( $users ) );
568 $users->rewind();
569 $this->assertTrue( $user->equals( $users->current() ) );
571 // arguments have OR relationship
572 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
573 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
574 $this->assertEquals( 2, iterator_count( $users ) );
575 $users->rewind();
576 $this->assertTrue( $user->equals( $users->current() ) );
577 $users->next();
578 $this->assertTrue( $user2->equals( $users->current() ) );
580 // users are not duplicated
581 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
582 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
583 $this->assertEquals( 1, iterator_count( $users ) );
584 $users->rewind();
585 $this->assertTrue( $user->equals( $users->current() ) );
589 * When a user is autoblocked a cookie is set with which to track them
590 * in case they log out and change IP addresses.
591 * @link https://phabricator.wikimedia.org/T5233
593 public function testAutoblockCookies() {
594 // Set up the bits of global configuration that we use.
595 $this->setMwGlobals( [
596 'wgCookieSetOnAutoblock' => true,
597 'wgCookiePrefix' => 'wmsitetitle',
598 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
599 ] );
601 // 1. Log in a test user, and block them.
602 $user1tmp = $this->getTestUser()->getUser();
603 $request1 = new FauxRequest();
604 $request1->getSession()->setUser( $user1tmp );
605 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
606 $block = new Block( [
607 'enableAutoblock' => true,
608 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
609 ] );
610 $block->setTarget( $user1tmp );
611 $block->insert();
612 $user1 = User::newFromSession( $request1 );
613 $user1->mBlock = $block;
614 $user1->load();
616 // Confirm that the block has been applied as required.
617 $this->assertTrue( $user1->isLoggedIn() );
618 $this->assertTrue( $user1->isBlocked() );
619 $this->assertEquals( Block::TYPE_USER, $block->getType() );
620 $this->assertTrue( $block->isAutoblocking() );
621 $this->assertGreaterThanOrEqual( 1, $block->getId() );
623 // Test for the desired cookie name, value, and expiry.
624 $cookies = $request1->response()->getCookies();
625 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
626 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
627 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
628 $this->assertEquals( $block->getId(), $cookieValue );
630 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
631 $request2 = new FauxRequest();
632 $request2->setCookie( 'BlockID', $block->getCookieValue() );
633 $user2 = User::newFromSession( $request2 );
634 $user2->load();
635 $this->assertNotEquals( $user1->getId(), $user2->getId() );
636 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
637 $this->assertTrue( $user2->isAnon() );
638 $this->assertFalse( $user2->isLoggedIn() );
639 $this->assertTrue( $user2->isBlocked() );
640 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
641 // Can't directly compare the objects becuase of member type differences.
642 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
643 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
644 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
646 // 3. Finally, set up a request as a new user, and the block should still be applied.
647 $user3tmp = $this->getTestUser()->getUser();
648 $request3 = new FauxRequest();
649 $request3->getSession()->setUser( $user3tmp );
650 $request3->setCookie( 'BlockID', $block->getId() );
651 $user3 = User::newFromSession( $request3 );
652 $user3->load();
653 $this->assertTrue( $user3->isLoggedIn() );
654 $this->assertTrue( $user3->isBlocked() );
655 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
657 // Clean up.
658 $block->delete();
662 * Make sure that no cookie is set to track autoblocked users
663 * when $wgCookieSetOnAutoblock is false.
665 public function testAutoblockCookiesDisabled() {
666 // Set up the bits of global configuration that we use.
667 $this->setMwGlobals( [
668 'wgCookieSetOnAutoblock' => false,
669 'wgCookiePrefix' => 'wm_no_cookies',
670 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
671 ] );
673 // 1. Log in a test user, and block them.
674 $testUser = $this->getTestUser()->getUser();
675 $request1 = new FauxRequest();
676 $request1->getSession()->setUser( $testUser );
677 $block = new Block( [ 'enableAutoblock' => true ] );
678 $block->setTarget( $testUser );
679 $block->insert();
680 $user = User::newFromSession( $request1 );
681 $user->mBlock = $block;
682 $user->load();
684 // 2. Test that the cookie IS NOT present.
685 $this->assertTrue( $user->isLoggedIn() );
686 $this->assertTrue( $user->isBlocked() );
687 $this->assertEquals( Block::TYPE_USER, $block->getType() );
688 $this->assertTrue( $block->isAutoblocking() );
689 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
690 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
691 $cookies = $request1->response()->getCookies();
692 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
694 // Clean up.
695 $block->delete();
699 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
700 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
701 * the cookie's should change with it.
703 public function testAutoblockCookieInfiniteExpiry() {
704 $this->setMwGlobals( [
705 'wgCookieSetOnAutoblock' => true,
706 'wgCookiePrefix' => 'wm_infinite_block',
707 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
708 ] );
709 // 1. Log in a test user, and block them indefinitely.
710 $user1Tmp = $this->getTestUser()->getUser();
711 $request1 = new FauxRequest();
712 $request1->getSession()->setUser( $user1Tmp );
713 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
714 $block->setTarget( $user1Tmp );
715 $block->insert();
716 $user1 = User::newFromSession( $request1 );
717 $user1->mBlock = $block;
718 $user1->load();
720 // 2. Test the cookie's expiry timestamp.
721 $this->assertTrue( $user1->isLoggedIn() );
722 $this->assertTrue( $user1->isBlocked() );
723 $this->assertEquals( Block::TYPE_USER, $block->getType() );
724 $this->assertTrue( $block->isAutoblocking() );
725 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
726 $cookies = $request1->response()->getCookies();
727 // Test the cookie's expiry to the nearest minute.
728 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
729 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
730 // Check for expiry dates in a 10-second window, to account for slow testing.
731 $this->assertEquals(
732 $expOneDay,
733 $cookies['wm_infinite_blockBlockID']['expire'],
734 'Expiry date',
738 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
739 $newExpiry = wfTimestamp() + 2 * 60 * 60;
740 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
741 $block->update();
742 $user2tmp = $this->getTestUser()->getUser();
743 $request2 = new FauxRequest();
744 $request2->getSession()->setUser( $user2tmp );
745 $user2 = User::newFromSession( $request2 );
746 $user2->mBlock = $block;
747 $user2->load();
748 $cookies = $request2->response()->getCookies();
749 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
750 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
752 // Clean up.
753 $block->delete();
756 public function testSoftBlockRanges() {
757 global $wgUser;
759 $this->setMwGlobals( [
760 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
761 'wgUser' => null,
762 ] );
764 // IP isn't in $wgSoftBlockRanges
765 $request = new FauxRequest();
766 $request->setIP( '192.168.0.1' );
767 $wgUser = User::newFromSession( $request );
768 $this->assertNull( $wgUser->getBlock() );
770 // IP is in $wgSoftBlockRanges
771 $request = new FauxRequest();
772 $request->setIP( '10.20.30.40' );
773 $wgUser = User::newFromSession( $request );
774 $block = $wgUser->getBlock();
775 $this->assertInstanceOf( Block::class, $block );
776 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
778 // Make sure the block is really soft
779 $request->getSession()->setUser( $this->getTestUser()->getUser() );
780 $wgUser = User::newFromSession( $request );
781 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
782 $this->assertNull( $wgUser->getBlock() );
786 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
788 public function testAutoblockCookieInauthentic() {
789 // Set up the bits of global configuration that we use.
790 $this->setMwGlobals( [
791 'wgCookieSetOnAutoblock' => true,
792 'wgCookiePrefix' => 'wmsitetitle',
793 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
794 ] );
796 // 1. Log in a blocked test user.
797 $user1tmp = $this->getTestUser()->getUser();
798 $request1 = new FauxRequest();
799 $request1->getSession()->setUser( $user1tmp );
800 $block = new Block( [ 'enableAutoblock' => true ] );
801 $block->setTarget( $user1tmp );
802 $block->insert();
803 $user1 = User::newFromSession( $request1 );
804 $user1->mBlock = $block;
805 $user1->load();
807 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
808 // user not blocked.
809 $request2 = new FauxRequest();
810 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
811 $user2 = User::newFromSession( $request2 );
812 $user2->load();
813 $this->assertTrue( $user2->isAnon() );
814 $this->assertFalse( $user2->isLoggedIn() );
815 $this->assertFalse( $user2->isBlocked() );
817 // Clean up.
818 $block->delete();
822 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
823 * This checks that a non-authenticated cookie still works.
825 public function testAutoblockCookieNoSecretKey() {
826 // Set up the bits of global configuration that we use.
827 $this->setMwGlobals( [
828 'wgCookieSetOnAutoblock' => true,
829 'wgCookiePrefix' => 'wmsitetitle',
830 'wgSecretKey' => null,
831 ] );
833 // 1. Log in a blocked test user.
834 $user1tmp = $this->getTestUser()->getUser();
835 $request1 = new FauxRequest();
836 $request1->getSession()->setUser( $user1tmp );
837 $block = new Block( [ 'enableAutoblock' => true ] );
838 $block->setTarget( $user1tmp );
839 $block->insert();
840 $user1 = User::newFromSession( $request1 );
841 $user1->mBlock = $block;
842 $user1->load();
843 $this->assertTrue( $user1->isBlocked() );
845 // 2. Create a new request, set the cookie to just the block ID, and the user should
846 // still get blocked when they log in again.
847 $request2 = new FauxRequest();
848 $request2->setCookie( 'BlockID', $block->getId() );
849 $user2 = User::newFromSession( $request2 );
850 $user2->load();
851 $this->assertNotEquals( $user1->getId(), $user2->getId() );
852 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
853 $this->assertTrue( $user2->isAnon() );
854 $this->assertFalse( $user2->isLoggedIn() );
855 $this->assertTrue( $user2->isBlocked() );
856 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
858 // Clean up.
859 $block->delete();
862 public function testIsPingLimitable() {
863 $request = new FauxRequest();
864 $request->setIP( '1.2.3.4' );
865 $user = User::newFromSession( $request );
867 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
868 $this->assertTrue( $user->isPingLimitable() );
870 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
871 $this->assertFalse( $user->isPingLimitable() );
873 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
874 $this->assertFalse( $user->isPingLimitable() );
876 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
877 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
878 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
879 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
880 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
881 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
884 public function provideExperienceLevel() {
885 return [
886 [ 2, 2, 'newcomer' ],
887 [ 12, 3, 'newcomer' ],
888 [ 8, 5, 'newcomer' ],
889 [ 15, 10, 'learner' ],
890 [ 450, 20, 'learner' ],
891 [ 460, 33, 'learner' ],
892 [ 525, 28, 'learner' ],
893 [ 538, 33, 'experienced' ],
898 * @dataProvider provideExperienceLevel
900 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
901 $this->setMwGlobals( [
902 'wgLearnerEdits' => 10,
903 'wgLearnerMemberSince' => 4,
904 'wgExperiencedUserEdits' => 500,
905 'wgExperiencedUserMemberSince' => 30,
906 ] );
908 $db = wfGetDB( DB_MASTER );
910 $data = new stdClass();
911 $data->user_id = 1;
912 $data->user_name = 'name';
913 $data->user_real_name = 'Real Name';
914 $data->user_touched = 1;
915 $data->user_token = 'token';
916 $data->user_email = 'a@a.a';
917 $data->user_email_authenticated = null;
918 $data->user_email_token = 'token';
919 $data->user_email_token_expires = null;
920 $data->user_editcount = $editCount;
921 $data->user_registration = $db->timestamp( time() - $memberSince * 86400 );
922 $user = User::newFromRow( $data );
924 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
927 public function testExperienceLevelAnon() {
928 $user = User::newFromName( '10.11.12.13', false );
930 $this->assertFalse( $user->getExperienceLevel() );
933 public static function provideIsLocallBlockedProxy() {
934 return [
935 [ '1.2.3.4', '1.2.3.4' ],
936 [ '1.2.3.4', '1.2.3.0/16' ],
941 * @dataProvider provideIsLocallBlockedProxy
942 * @covers User::isLocallyBlockedProxy
944 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
945 $this->setMwGlobals(
946 'wgProxyList', []
948 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
950 $this->setMwGlobals(
951 'wgProxyList',
953 $blockListEntry
956 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
958 $this->setMwGlobals(
959 'wgProxyList',
961 'test' => $blockListEntry
964 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
966 $this->hideDeprecated(
967 'IP addresses in the keys of $wgProxyList (found the following IP ' .
968 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
970 $this->setMwGlobals(
971 'wgProxyList',
973 $blockListEntry => 'test'
976 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );