Add @coversNothing in places where @covers does not apply
[lhc/web/wiklou.git] / tests / phpunit / includes / user / UserTest.php
1 <?php
2
3 define( 'NS_UNITTEST', 5600 );
4 define( 'NS_UNITTEST_TALK', 5601 );
5
6 use MediaWiki\MediaWikiServices;
7 use Wikimedia\TestingAccessWrapper;
8
9 /**
10 * @group Database
11 */
12 class UserTest extends MediaWikiTestCase {
13 /**
14 * @var User
15 */
16 protected $user;
17
18 protected function setUp() {
19 parent::setUp();
20
21 $this->setMwGlobals( [
22 'wgGroupPermissions' => [],
23 'wgRevokePermissions' => [],
24 ] );
25
26 $this->setUpPermissionGlobals();
27
28 $this->user = $this->getTestUser( [ 'unittesters' ] )->getUser();
29 }
30
31 private function setUpPermissionGlobals() {
32 global $wgGroupPermissions, $wgRevokePermissions;
33
34 # Data for regular $wgGroupPermissions test
35 $wgGroupPermissions['unittesters'] = [
36 'test' => true,
37 'runtest' => true,
38 'writetest' => false,
39 'nukeworld' => false,
40 ];
41 $wgGroupPermissions['testwriters'] = [
42 'test' => true,
43 'writetest' => true,
44 'modifytest' => true,
45 ];
46
47 # Data for regular $wgRevokePermissions test
48 $wgRevokePermissions['formertesters'] = [
49 'runtest' => true,
50 ];
51
52 # For the options test
53 $wgGroupPermissions['*'] = [
54 'editmyoptions' => true,
55 ];
56 }
57
58 /**
59 * @covers User::getGroupPermissions
60 */
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 );
67
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 );
73 }
74
75 /**
76 * @covers User::getGroupPermissions
77 */
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 );
84 }
85
86 /**
87 * @covers User::getRights
88 */
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 );
95 }
96
97 /**
98 * @covers User::getRights
99 */
100 public function testUserGetRightsHooks() {
101 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
102 $userWrapper = TestingAccessWrapper::newFromObject( $user );
103
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' );
109
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 } ] ] );
115
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 );
122
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 ) )
130 );
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;
137
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 );
144 }
145
146 /**
147 * @dataProvider provideGetGroupsWithPermission
148 * @covers User::getGroupsWithPermission
149 */
150 public function testGetGroupsWithPermission( $expected, $right ) {
151 $result = User::getGroupsWithPermission( $right );
152 sort( $result );
153 sort( $expected );
154
155 $this->assertEquals( $expected, $result, "Groups with permission $right" );
156 }
157
158 public static function provideGetGroupsWithPermission() {
159 return [
160 [
161 [ 'unittesters', 'testwriters' ],
162 'test'
163 ],
164 [
165 [ 'unittesters' ],
166 'runtest'
167 ],
168 [
169 [ 'testwriters' ],
170 'writetest'
171 ],
172 [
173 [ 'testwriters' ],
174 'modifytest'
175 ],
176 ];
177 }
178
179 /**
180 * @dataProvider provideIPs
181 * @covers User::isIP
182 */
183 public function testIsIP( $value, $result, $message ) {
184 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
185 }
186
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' ],
201 ];
202 }
203
204 /**
205 * @dataProvider provideUserNames
206 * @covers User::isValidUserName
207 */
208 public function testIsValidUserName( $username, $result, $message ) {
209 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
210 }
211
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 [ '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' ],
232 ];
233 }
234
235 /**
236 * Test, if for all rights a right- message exist,
237 * which is used on Special:ListGroupRights as help text
238 * Extensions and core
239 *
240 * @coversNothing
241 */
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' );
246
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-' ) );
252 }
253 }
254
255 sort( $allRights );
256 sort( $rightsWithMessage );
257
258 $this->assertEquals(
259 $allRights,
260 $rightsWithMessage,
261 'Each user rights (core/extensions) has a corresponding right- message.'
262 );
263 }
264
265 /**
266 * Test User::editCount
267 * @group medium
268 * @covers User::getEditCount
269 */
270 public function testGetEditCount() {
271 $user = $this->getMutableTestUser()->getUser();
272
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() ),
278 'test',
279 0,
280 false,
281 $user
282 );
283 }
284
285 $this->assertEquals(
286 3,
287 $user->getEditCount(),
288 'After three edits, the user edit count should be 3'
289 );
290
291 // increase the edit count
292 $user->incEditCount();
293
294 $this->assertEquals(
295 4,
296 $user->getEditCount(),
297 'After increasing the edit count manually, the user edit count should be 4'
298 );
299 }
300
301 /**
302 * Test User::editCount
303 * @group medium
304 * @covers User::getEditCount
305 */
306 public function testGetEditCountForAnons() {
307 $user = User::newFromName( 'Anonymous' );
308
309 $this->assertNull(
310 $user->getEditCount(),
311 'Edit count starts null for anonymous users.'
312 );
313
314 $user->incEditCount();
315
316 $this->assertNull(
317 $user->getEditCount(),
318 'Edit count remains null for anonymous users despite calls to increase it.'
319 );
320 }
321
322 /**
323 * Test User::editCount
324 * @group medium
325 * @covers User::incEditCount
326 */
327 public function testIncEditCount() {
328 $user = $this->getMutableTestUser()->getUser();
329 $user->incEditCount();
330
331 $reloadedUser = User::newFromId( $user->getId() );
332 $reloadedUser->incEditCount();
333
334 $this->assertEquals(
335 2,
336 $reloadedUser->getEditCount(),
337 'Increasing the edit count after a fresh load leaves the object up to date.'
338 );
339 }
340
341 /**
342 * Test changing user options.
343 * @covers User::setOption
344 * @covers User::getOption
345 */
346 public function testOptions() {
347 $user = $this->getMutableTestUser()->getUser();
348
349 $user->setOption( 'userjs-someoption', 'test' );
350 $user->setOption( 'rclimit', 200 );
351 $user->saveSettings();
352
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' ) );
357
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' ) );
362 }
363
364 /**
365 * T39963
366 * Make sure defaults are loaded when setOption is called.
367 * @covers User::loadOptions
368 */
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' ) );
374 }
375
376 /**
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()
384 */
385 public function testCheckPasswordValidity() {
386 $this->setMwGlobals( [
387 'wgPasswordPolicy' => [
388 'policies' => [
389 'sysop' => [
390 'MinimalPasswordLength' => 8,
391 'MinimumPasswordLengthToLogin' => 1,
392 'PasswordCannotMatchUsername' => 1,
393 ],
394 'default' => [
395 'MinimalPasswordLength' => 6,
396 'PasswordCannotMatchUsername' => true,
397 'PasswordCannotMatchBlacklist' => true,
398 'MaximalPasswordLength' => 40,
399 ],
400 ],
401 'checks' => [
402 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
403 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
404 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
405 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
406 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
407 ],
408 ],
409 ] );
410
411 $user = static::getTestUser()->getUser();
412
413 // Sanity
414 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
415
416 // Minimum length
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' ) );
421
422 // Maximum length
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 ) );
428
429 // Matches username
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() ) );
433
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' ) );
438 }
439
440 /**
441 * @covers User::getCanonicalName()
442 * @dataProvider provideGetCanonicalName
443 */
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' ) {
450 $iwdata = [
451 'iw_url' => 'http://example.com/',
452 'iw_local' => 0,
453 'iw_trans' => 0,
454 ];
455 return false;
456 }
457 },
458 ],
459 ] );
460
461 foreach ( $expectedArray as $validate => $expected ) {
462 $this->assertEquals(
463 $expected,
464 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
465 }
466 }
467
468 public static function provideGetCanonicalName() {
469 return [
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' ] ],
484 ];
485 }
486
487 /**
488 * @covers User::equals
489 */
490 public function testEquals() {
491 $first = $this->getMutableTestUser()->getUser();
492 $second = User::newFromName( $first->getName() );
493
494 $this->assertTrue( $first->equals( $first ) );
495 $this->assertTrue( $first->equals( $second ) );
496 $this->assertTrue( $second->equals( $first ) );
497
498 $third = $this->getMutableTestUser()->getUser();
499 $fourth = $this->getMutableTestUser()->getUser();
500
501 $this->assertFalse( $third->equals( $fourth ) );
502 $this->assertFalse( $fourth->equals( $third ) );
503
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 ) );
509 }
510
511 /**
512 * @covers User::getId
513 */
514 public function testGetId() {
515 $user = static::getTestUser()->getUser();
516 $this->assertTrue( $user->getId() > 0 );
517 }
518
519 /**
520 * @covers User::isLoggedIn
521 * @covers User::isAnon
522 */
523 public function testLoggedIn() {
524 $user = $this->getMutableTestUser()->getUser();
525 $this->assertTrue( $user->isLoggedIn() );
526 $this->assertFalse( $user->isAnon() );
527
528 // Non-existent users are perceived as anonymous
529 $user = User::newFromName( 'UTNonexistent' );
530 $this->assertFalse( $user->isLoggedIn() );
531 $this->assertTrue( $user->isAnon() );
532
533 $user = new User;
534 $this->assertFalse( $user->isLoggedIn() );
535 $this->assertTrue( $user->isAnon() );
536 }
537
538 /**
539 * @covers User::checkAndSetTouched
540 */
541 public function testCheckAndSetTouched() {
542 $user = $this->getMutableTestUser()->getUser();
543 $user = TestingAccessWrapper::newFromObject( $user );
544 $this->assertTrue( $user->isLoggedIn() );
545
546 $touched = $user->getDBTouched();
547 $this->assertTrue(
548 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
549 $this->assertGreaterThan(
550 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
551
552 $touched = $user->getDBTouched();
553 $this->assertTrue(
554 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
555 $this->assertGreaterThan(
556 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
557 }
558
559 /**
560 * @covers User::findUsersByGroup
561 */
562 public function testFindUsersByGroup() {
563 $users = User::findUsersByGroup( [] );
564 $this->assertEquals( 0, iterator_count( $users ) );
565
566 $users = User::findUsersByGroup( 'foo' );
567 $this->assertEquals( 0, iterator_count( $users ) );
568
569 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
570 $users = User::findUsersByGroup( 'foo' );
571 $this->assertEquals( 1, iterator_count( $users ) );
572 $users->rewind();
573 $this->assertTrue( $user->equals( $users->current() ) );
574
575 // arguments have OR relationship
576 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
577 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
578 $this->assertEquals( 2, iterator_count( $users ) );
579 $users->rewind();
580 $this->assertTrue( $user->equals( $users->current() ) );
581 $users->next();
582 $this->assertTrue( $user2->equals( $users->current() ) );
583
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 ) );
588 $users->rewind();
589 $this->assertTrue( $user->equals( $users->current() ) );
590 }
591
592 /**
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
596 */
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 ),
603 ] );
604
605 // Unregister the hooks for proper unit testing
606 $this->mergeMwGlobalArrayValue( 'wgHooks', [
607 'PerformRetroactiveAutoblock' => []
608 ] );
609
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 ),
619 ] );
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;
626 $user1->load();
627
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() );
634
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 );
641
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 );
646 $user2->load();
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() );
658
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 );
665 $user3->load();
666 $this->assertTrue( $user3->isLoggedIn() );
667 $this->assertTrue( $user3->isBlocked() );
668 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
669
670 // Clean up.
671 $block->delete();
672 }
673
674 /**
675 * Make sure that no cookie is set to track autoblocked users
676 * when $wgCookieSetOnAutoblock is false.
677 */
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 ),
684 ] );
685
686 // Unregister the hooks for proper unit testing
687 $this->mergeMwGlobalArrayValue( 'wgHooks', [
688 'PerformRetroactiveAutoblock' => []
689 ] );
690
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;
703 $user->load();
704
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 );
714
715 // Clean up.
716 $block->delete();
717 }
718
719 /**
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.
723 */
724 public function testAutoblockCookieInfiniteExpiry() {
725 $this->setMwGlobals( [
726 'wgCookieSetOnAutoblock' => true,
727 'wgCookiePrefix' => 'wm_infinite_block',
728 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
729 ] );
730
731 // Unregister the hooks for proper unit testing
732 $this->mergeMwGlobalArrayValue( 'wgHooks', [
733 'PerformRetroactiveAutoblock' => []
734 ] );
735
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;
748 $user1->load();
749
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.
761 $this->assertEquals(
762 $expOneDay,
763 $cookies['wm_infinite_blockBlockID']['expire'],
764 'Expiry date',
765 5.0
766 );
767
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 );
771 $block->update();
772 $user2tmp = $this->getTestUser()->getUser();
773 $request2 = new FauxRequest();
774 $request2->getSession()->setUser( $user2tmp );
775 $user2 = User::newFromSession( $request2 );
776 $user2->mBlock = $block;
777 $user2->load();
778 $cookies = $request2->response()->getCookies();
779 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
780 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
781
782 // Clean up.
783 $block->delete();
784 }
785
786 public function testSoftBlockRanges() {
787 global $wgUser;
788
789 $this->setMwGlobals( [
790 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
791 'wgUser' => null,
792 ] );
793
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() );
799
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() );
807
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() );
813 }
814
815 /**
816 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
817 */
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 ),
824 ] );
825
826 // Unregister the hooks for proper unit testing
827 $this->mergeMwGlobalArrayValue( 'wgHooks', [
828 'PerformRetroactiveAutoblock' => []
829 ] );
830
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;
843 $user1->load();
844
845 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
846 // user not blocked.
847 $request2 = new FauxRequest();
848 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
849 $user2 = User::newFromSession( $request2 );
850 $user2->load();
851 $this->assertTrue( $user2->isAnon() );
852 $this->assertFalse( $user2->isLoggedIn() );
853 $this->assertFalse( $user2->isBlocked() );
854
855 // Clean up.
856 $block->delete();
857 }
858
859 /**
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.
862 */
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,
869 ] );
870
871 // Unregister the hooks for proper unit testing
872 $this->mergeMwGlobalArrayValue( 'wgHooks', [
873 'PerformRetroactiveAutoblock' => []
874 ] );
875
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;
888 $user1->load();
889 $this->assertTrue( $user1->isBlocked() );
890
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 );
896 $user2->load();
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.
903
904 // Clean up.
905 $block->delete();
906 }
907
908 /**
909 * @covers User::isPingLimitable
910 */
911 public function testIsPingLimitable() {
912 $request = new FauxRequest();
913 $request->setIP( '1.2.3.4' );
914 $user = User::newFromSession( $request );
915
916 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
917 $this->assertTrue( $user->isPingLimitable() );
918
919 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
920 $this->assertFalse( $user->isPingLimitable() );
921
922 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
923 $this->assertFalse( $user->isPingLimitable() );
924
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() );
931 }
932
933 public function provideExperienceLevel() {
934 return [
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' ],
943 ];
944 }
945
946 /**
947 * @covers User::getExperienceLevel
948 * @dataProvider provideExperienceLevel
949 */
950 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
951 $this->setMwGlobals( [
952 'wgLearnerEdits' => 10,
953 'wgLearnerMemberSince' => 4,
954 'wgExperiencedUserEdits' => 500,
955 'wgExperiencedUserMemberSince' => 30,
956 ] );
957
958 $db = wfGetDB( DB_MASTER );
959
960 $data = new stdClass();
961 $data->user_id = 1;
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 );
973
974 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
975 }
976
977 /**
978 * @covers User::getExperienceLevel
979 */
980 public function testExperienceLevelAnon() {
981 $user = User::newFromName( '10.11.12.13', false );
982
983 $this->assertFalse( $user->getExperienceLevel() );
984 }
985
986 public static function provideIsLocallBlockedProxy() {
987 return [
988 [ '1.2.3.4', '1.2.3.4' ],
989 [ '1.2.3.4', '1.2.3.0/16' ],
990 ];
991 }
992
993 /**
994 * @dataProvider provideIsLocallBlockedProxy
995 * @covers User::isLocallyBlockedProxy
996 */
997 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
998 $this->setMwGlobals(
999 'wgProxyList', []
1000 );
1001 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
1002
1003 $this->setMwGlobals(
1004 'wgProxyList',
1005 [
1006 $blockListEntry
1007 ]
1008 );
1009 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1010
1011 $this->setMwGlobals(
1012 'wgProxyList',
1013 [
1014 'test' => $blockListEntry
1015 ]
1016 );
1017 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1018
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)'
1022 );
1023 $this->setMwGlobals(
1024 'wgProxyList',
1025 [
1026 $blockListEntry => 'test'
1027 ]
1028 );
1029 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1030 }
1031 }