Merge "RCFilters: Remove excluded params from URL"
[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 public function testAllRightsWithMessage() {
241 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
242 $allRights = User::getAllRights();
243 $allMessageKeys = Language::getMessageKeysFor( 'en' );
244
245 $rightsWithMessage = [];
246 foreach ( $allMessageKeys as $message ) {
247 // === 0: must be at beginning of string (position 0)
248 if ( strpos( $message, 'right-' ) === 0 ) {
249 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
250 }
251 }
252
253 sort( $allRights );
254 sort( $rightsWithMessage );
255
256 $this->assertEquals(
257 $allRights,
258 $rightsWithMessage,
259 'Each user rights (core/extensions) has a corresponding right- message.'
260 );
261 }
262
263 /**
264 * Test User::editCount
265 * @group medium
266 * @covers User::getEditCount
267 */
268 public function testGetEditCount() {
269 $user = $this->getMutableTestUser()->getUser();
270
271 // let the user have a few (3) edits
272 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
273 for ( $i = 0; $i < 3; $i++ ) {
274 $page->doEditContent(
275 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
276 'test',
277 0,
278 false,
279 $user
280 );
281 }
282
283 $this->assertEquals(
284 3,
285 $user->getEditCount(),
286 'After three edits, the user edit count should be 3'
287 );
288
289 // increase the edit count
290 $user->incEditCount();
291
292 $this->assertEquals(
293 4,
294 $user->getEditCount(),
295 'After increasing the edit count manually, the user edit count should be 4'
296 );
297 }
298
299 /**
300 * Test User::editCount
301 * @group medium
302 * @covers User::getEditCount
303 */
304 public function testGetEditCountForAnons() {
305 $user = User::newFromName( 'Anonymous' );
306
307 $this->assertNull(
308 $user->getEditCount(),
309 'Edit count starts null for anonymous users.'
310 );
311
312 $user->incEditCount();
313
314 $this->assertNull(
315 $user->getEditCount(),
316 'Edit count remains null for anonymous users despite calls to increase it.'
317 );
318 }
319
320 /**
321 * Test User::editCount
322 * @group medium
323 * @covers User::incEditCount
324 */
325 public function testIncEditCount() {
326 $user = $this->getMutableTestUser()->getUser();
327 $user->incEditCount();
328
329 $reloadedUser = User::newFromId( $user->getId() );
330 $reloadedUser->incEditCount();
331
332 $this->assertEquals(
333 2,
334 $reloadedUser->getEditCount(),
335 'Increasing the edit count after a fresh load leaves the object up to date.'
336 );
337 }
338
339 /**
340 * Test changing user options.
341 * @covers User::setOption
342 * @covers User::getOption
343 */
344 public function testOptions() {
345 $user = $this->getMutableTestUser()->getUser();
346
347 $user->setOption( 'userjs-someoption', 'test' );
348 $user->setOption( 'rclimit', 200 );
349 $user->saveSettings();
350
351 $user = User::newFromName( $user->getName() );
352 $user->load( User::READ_LATEST );
353 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
354 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
355
356 $user = User::newFromName( $user->getName() );
357 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
358 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
359 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
360 }
361
362 /**
363 * T39963
364 * Make sure defaults are loaded when setOption is called.
365 * @covers User::loadOptions
366 */
367 public function testAnonOptions() {
368 global $wgDefaultUserOptions;
369 $this->user->setOption( 'userjs-someoption', 'test' );
370 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
371 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
372 }
373
374 /**
375 * Test password validity checks. There are 3 checks in core,
376 * - ensure the password meets the minimal length
377 * - ensure the password is not the same as the username
378 * - ensure the username/password combo isn't forbidden
379 * @covers User::checkPasswordValidity()
380 * @covers User::getPasswordValidity()
381 * @covers User::isValidPassword()
382 */
383 public function testCheckPasswordValidity() {
384 $this->setMwGlobals( [
385 'wgPasswordPolicy' => [
386 'policies' => [
387 'sysop' => [
388 'MinimalPasswordLength' => 8,
389 'MinimumPasswordLengthToLogin' => 1,
390 'PasswordCannotMatchUsername' => 1,
391 ],
392 'default' => [
393 'MinimalPasswordLength' => 6,
394 'PasswordCannotMatchUsername' => true,
395 'PasswordCannotMatchBlacklist' => true,
396 'MaximalPasswordLength' => 40,
397 ],
398 ],
399 'checks' => [
400 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
401 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
402 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
403 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
404 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
405 ],
406 ],
407 ] );
408
409 $user = static::getTestUser()->getUser();
410
411 // Sanity
412 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
413
414 // Minimum length
415 $this->assertFalse( $user->isValidPassword( 'a' ) );
416 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
417 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
418 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
419
420 // Maximum length
421 $longPass = str_repeat( 'a', 41 );
422 $this->assertFalse( $user->isValidPassword( $longPass ) );
423 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
424 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
425 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
426
427 // Matches username
428 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
429 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
430 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
431
432 // On the forbidden list
433 $user = User::newFromName( 'Useruser' );
434 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
435 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
436 }
437
438 /**
439 * @covers User::getCanonicalName()
440 * @dataProvider provideGetCanonicalName
441 */
442 public function testGetCanonicalName( $name, $expectedArray ) {
443 // fake interwiki map for the 'Interwiki prefix' testcase
444 $this->mergeMwGlobalArrayValue( 'wgHooks', [
445 'InterwikiLoadPrefix' => [
446 function ( $prefix, &$iwdata ) {
447 if ( $prefix === 'interwiki' ) {
448 $iwdata = [
449 'iw_url' => 'http://example.com/',
450 'iw_local' => 0,
451 'iw_trans' => 0,
452 ];
453 return false;
454 }
455 },
456 ],
457 ] );
458
459 foreach ( $expectedArray as $validate => $expected ) {
460 $this->assertEquals(
461 $expected,
462 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
463 }
464 }
465
466 public static function provideGetCanonicalName() {
467 return [
468 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
469 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
470 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
471 'valid' => false, 'false' => 'Talk:Username' ] ],
472 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
473 'valid' => false, 'false' => 'Interwiki:Username' ] ],
474 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
475 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
476 'usable' => 'Multi spaces' ] ],
477 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
478 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
479 'valid' => false, 'false' => 'In[]valid' ] ],
480 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
481 'false' => 'With / slash' ] ],
482 ];
483 }
484
485 /**
486 * @covers User::equals
487 */
488 public function testEquals() {
489 $first = $this->getMutableTestUser()->getUser();
490 $second = User::newFromName( $first->getName() );
491
492 $this->assertTrue( $first->equals( $first ) );
493 $this->assertTrue( $first->equals( $second ) );
494 $this->assertTrue( $second->equals( $first ) );
495
496 $third = $this->getMutableTestUser()->getUser();
497 $fourth = $this->getMutableTestUser()->getUser();
498
499 $this->assertFalse( $third->equals( $fourth ) );
500 $this->assertFalse( $fourth->equals( $third ) );
501
502 // Test users loaded from db with id
503 $user = $this->getMutableTestUser()->getUser();
504 $fifth = User::newFromId( $user->getId() );
505 $sixth = User::newFromName( $user->getName() );
506 $this->assertTrue( $fifth->equals( $sixth ) );
507 }
508
509 /**
510 * @covers User::getId
511 */
512 public function testGetId() {
513 $user = static::getTestUser()->getUser();
514 $this->assertTrue( $user->getId() > 0 );
515 }
516
517 /**
518 * @covers User::isLoggedIn
519 * @covers User::isAnon
520 */
521 public function testLoggedIn() {
522 $user = $this->getMutableTestUser()->getUser();
523 $this->assertTrue( $user->isLoggedIn() );
524 $this->assertFalse( $user->isAnon() );
525
526 // Non-existent users are perceived as anonymous
527 $user = User::newFromName( 'UTNonexistent' );
528 $this->assertFalse( $user->isLoggedIn() );
529 $this->assertTrue( $user->isAnon() );
530
531 $user = new User;
532 $this->assertFalse( $user->isLoggedIn() );
533 $this->assertTrue( $user->isAnon() );
534 }
535
536 /**
537 * @covers User::checkAndSetTouched
538 */
539 public function testCheckAndSetTouched() {
540 $user = $this->getMutableTestUser()->getUser();
541 $user = TestingAccessWrapper::newFromObject( $user );
542 $this->assertTrue( $user->isLoggedIn() );
543
544 $touched = $user->getDBTouched();
545 $this->assertTrue(
546 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
547 $this->assertGreaterThan(
548 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
549
550 $touched = $user->getDBTouched();
551 $this->assertTrue(
552 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
553 $this->assertGreaterThan(
554 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
555 }
556
557 /**
558 * @covers User::findUsersByGroup
559 */
560 public function testFindUsersByGroup() {
561 $users = User::findUsersByGroup( [] );
562 $this->assertEquals( 0, iterator_count( $users ) );
563
564 $users = User::findUsersByGroup( 'foo' );
565 $this->assertEquals( 0, iterator_count( $users ) );
566
567 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
568 $users = User::findUsersByGroup( 'foo' );
569 $this->assertEquals( 1, iterator_count( $users ) );
570 $users->rewind();
571 $this->assertTrue( $user->equals( $users->current() ) );
572
573 // arguments have OR relationship
574 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
575 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
576 $this->assertEquals( 2, iterator_count( $users ) );
577 $users->rewind();
578 $this->assertTrue( $user->equals( $users->current() ) );
579 $users->next();
580 $this->assertTrue( $user2->equals( $users->current() ) );
581
582 // users are not duplicated
583 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
584 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
585 $this->assertEquals( 1, iterator_count( $users ) );
586 $users->rewind();
587 $this->assertTrue( $user->equals( $users->current() ) );
588 }
589
590 /**
591 * When a user is autoblocked a cookie is set with which to track them
592 * in case they log out and change IP addresses.
593 * @link https://phabricator.wikimedia.org/T5233
594 */
595 public function testAutoblockCookies() {
596 // Set up the bits of global configuration that we use.
597 $this->setMwGlobals( [
598 'wgCookieSetOnAutoblock' => true,
599 'wgCookiePrefix' => 'wmsitetitle',
600 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
601 ] );
602
603 // Unregister the hooks for proper unit testing
604 $this->mergeMwGlobalArrayValue( 'wgHooks', [
605 'PerformRetroactiveAutoblock' => []
606 ] );
607
608 // 1. Log in a test user, and block them.
609 $userBlocker = $this->getTestSysop()->getUser();
610 $user1tmp = $this->getTestUser()->getUser();
611 $request1 = new FauxRequest();
612 $request1->getSession()->setUser( $user1tmp );
613 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
614 $block = new Block( [
615 'enableAutoblock' => true,
616 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
617 ] );
618 $block->setTarget( $user1tmp );
619 $block->setBlocker( $userBlocker );
620 $res = $block->insert();
621 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
622 $user1 = User::newFromSession( $request1 );
623 $user1->mBlock = $block;
624 $user1->load();
625
626 // Confirm that the block has been applied as required.
627 $this->assertTrue( $user1->isLoggedIn() );
628 $this->assertTrue( $user1->isBlocked() );
629 $this->assertEquals( Block::TYPE_USER, $block->getType() );
630 $this->assertTrue( $block->isAutoblocking() );
631 $this->assertGreaterThanOrEqual( 1, $block->getId() );
632
633 // Test for the desired cookie name, value, and expiry.
634 $cookies = $request1->response()->getCookies();
635 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
636 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
637 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
638 $this->assertEquals( $block->getId(), $cookieValue );
639
640 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
641 $request2 = new FauxRequest();
642 $request2->setCookie( 'BlockID', $block->getCookieValue() );
643 $user2 = User::newFromSession( $request2 );
644 $user2->load();
645 $this->assertNotEquals( $user1->getId(), $user2->getId() );
646 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
647 $this->assertTrue( $user2->isAnon() );
648 $this->assertFalse( $user2->isLoggedIn() );
649 $this->assertTrue( $user2->isBlocked() );
650 // Non-strict type-check.
651 $this->assertEquals( true, $user2->getBlock()->isAutoblocking(), 'Autoblock does not work' );
652 // Can't directly compare the objects becuase of member type differences.
653 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
654 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
655 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
656
657 // 3. Finally, set up a request as a new user, and the block should still be applied.
658 $user3tmp = $this->getTestUser()->getUser();
659 $request3 = new FauxRequest();
660 $request3->getSession()->setUser( $user3tmp );
661 $request3->setCookie( 'BlockID', $block->getId() );
662 $user3 = User::newFromSession( $request3 );
663 $user3->load();
664 $this->assertTrue( $user3->isLoggedIn() );
665 $this->assertTrue( $user3->isBlocked() );
666 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
667
668 // Clean up.
669 $block->delete();
670 }
671
672 /**
673 * Make sure that no cookie is set to track autoblocked users
674 * when $wgCookieSetOnAutoblock is false.
675 */
676 public function testAutoblockCookiesDisabled() {
677 // Set up the bits of global configuration that we use.
678 $this->setMwGlobals( [
679 'wgCookieSetOnAutoblock' => false,
680 'wgCookiePrefix' => 'wm_no_cookies',
681 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
682 ] );
683
684 // Unregister the hooks for proper unit testing
685 $this->mergeMwGlobalArrayValue( 'wgHooks', [
686 'PerformRetroactiveAutoblock' => []
687 ] );
688
689 // 1. Log in a test user, and block them.
690 $userBlocker = $this->getTestSysop()->getUser();
691 $testUser = $this->getTestUser()->getUser();
692 $request1 = new FauxRequest();
693 $request1->getSession()->setUser( $testUser );
694 $block = new Block( [ 'enableAutoblock' => true ] );
695 $block->setTarget( $testUser );
696 $block->setBlocker( $userBlocker );
697 $res = $block->insert();
698 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
699 $user = User::newFromSession( $request1 );
700 $user->mBlock = $block;
701 $user->load();
702
703 // 2. Test that the cookie IS NOT present.
704 $this->assertTrue( $user->isLoggedIn() );
705 $this->assertTrue( $user->isBlocked() );
706 $this->assertEquals( Block::TYPE_USER, $block->getType() );
707 $this->assertTrue( $block->isAutoblocking() );
708 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
709 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
710 $cookies = $request1->response()->getCookies();
711 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
712
713 // Clean up.
714 $block->delete();
715 }
716
717 /**
718 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
719 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
720 * the cookie's should change with it.
721 */
722 public function testAutoblockCookieInfiniteExpiry() {
723 $this->setMwGlobals( [
724 'wgCookieSetOnAutoblock' => true,
725 'wgCookiePrefix' => 'wm_infinite_block',
726 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
727 ] );
728
729 // Unregister the hooks for proper unit testing
730 $this->mergeMwGlobalArrayValue( 'wgHooks', [
731 'PerformRetroactiveAutoblock' => []
732 ] );
733
734 // 1. Log in a test user, and block them indefinitely.
735 $userBlocker = $this->getTestSysop()->getUser();
736 $user1Tmp = $this->getTestUser()->getUser();
737 $request1 = new FauxRequest();
738 $request1->getSession()->setUser( $user1Tmp );
739 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
740 $block->setTarget( $user1Tmp );
741 $block->setBlocker( $userBlocker );
742 $res = $block->insert();
743 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
744 $user1 = User::newFromSession( $request1 );
745 $user1->mBlock = $block;
746 $user1->load();
747
748 // 2. Test the cookie's expiry timestamp.
749 $this->assertTrue( $user1->isLoggedIn() );
750 $this->assertTrue( $user1->isBlocked() );
751 $this->assertEquals( Block::TYPE_USER, $block->getType() );
752 $this->assertTrue( $block->isAutoblocking() );
753 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
754 $cookies = $request1->response()->getCookies();
755 // Test the cookie's expiry to the nearest minute.
756 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
757 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
758 // Check for expiry dates in a 10-second window, to account for slow testing.
759 $this->assertEquals(
760 $expOneDay,
761 $cookies['wm_infinite_blockBlockID']['expire'],
762 'Expiry date',
763 5.0
764 );
765
766 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
767 $newExpiry = wfTimestamp() + 2 * 60 * 60;
768 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
769 $block->update();
770 $user2tmp = $this->getTestUser()->getUser();
771 $request2 = new FauxRequest();
772 $request2->getSession()->setUser( $user2tmp );
773 $user2 = User::newFromSession( $request2 );
774 $user2->mBlock = $block;
775 $user2->load();
776 $cookies = $request2->response()->getCookies();
777 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
778 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
779
780 // Clean up.
781 $block->delete();
782 }
783
784 public function testSoftBlockRanges() {
785 global $wgUser;
786
787 $this->setMwGlobals( [
788 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
789 'wgUser' => null,
790 ] );
791
792 // IP isn't in $wgSoftBlockRanges
793 $request = new FauxRequest();
794 $request->setIP( '192.168.0.1' );
795 $wgUser = User::newFromSession( $request );
796 $this->assertNull( $wgUser->getBlock() );
797
798 // IP is in $wgSoftBlockRanges
799 $request = new FauxRequest();
800 $request->setIP( '10.20.30.40' );
801 $wgUser = User::newFromSession( $request );
802 $block = $wgUser->getBlock();
803 $this->assertInstanceOf( Block::class, $block );
804 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
805
806 // Make sure the block is really soft
807 $request->getSession()->setUser( $this->getTestUser()->getUser() );
808 $wgUser = User::newFromSession( $request );
809 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
810 $this->assertNull( $wgUser->getBlock() );
811 }
812
813 /**
814 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
815 */
816 public function testAutoblockCookieInauthentic() {
817 // Set up the bits of global configuration that we use.
818 $this->setMwGlobals( [
819 'wgCookieSetOnAutoblock' => true,
820 'wgCookiePrefix' => 'wmsitetitle',
821 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
822 ] );
823
824 // Unregister the hooks for proper unit testing
825 $this->mergeMwGlobalArrayValue( 'wgHooks', [
826 'PerformRetroactiveAutoblock' => []
827 ] );
828
829 // 1. Log in a blocked test user.
830 $userBlocker = $this->getTestSysop()->getUser();
831 $user1tmp = $this->getTestUser()->getUser();
832 $request1 = new FauxRequest();
833 $request1->getSession()->setUser( $user1tmp );
834 $block = new Block( [ 'enableAutoblock' => true ] );
835 $block->setTarget( $user1tmp );
836 $block->setBlocker( $userBlocker );
837 $res = $block->insert();
838 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
839 $user1 = User::newFromSession( $request1 );
840 $user1->mBlock = $block;
841 $user1->load();
842
843 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
844 // user not blocked.
845 $request2 = new FauxRequest();
846 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
847 $user2 = User::newFromSession( $request2 );
848 $user2->load();
849 $this->assertTrue( $user2->isAnon() );
850 $this->assertFalse( $user2->isLoggedIn() );
851 $this->assertFalse( $user2->isBlocked() );
852
853 // Clean up.
854 $block->delete();
855 }
856
857 /**
858 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
859 * This checks that a non-authenticated cookie still works.
860 */
861 public function testAutoblockCookieNoSecretKey() {
862 // Set up the bits of global configuration that we use.
863 $this->setMwGlobals( [
864 'wgCookieSetOnAutoblock' => true,
865 'wgCookiePrefix' => 'wmsitetitle',
866 'wgSecretKey' => null,
867 ] );
868
869 // Unregister the hooks for proper unit testing
870 $this->mergeMwGlobalArrayValue( 'wgHooks', [
871 'PerformRetroactiveAutoblock' => []
872 ] );
873
874 // 1. Log in a blocked test user.
875 $userBlocker = $this->getTestSysop()->getUser();
876 $user1tmp = $this->getTestUser()->getUser();
877 $request1 = new FauxRequest();
878 $request1->getSession()->setUser( $user1tmp );
879 $block = new Block( [ 'enableAutoblock' => true ] );
880 $block->setTarget( $user1tmp );
881 $block->setBlocker( $userBlocker );
882 $res = $block->insert();
883 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
884 $user1 = User::newFromSession( $request1 );
885 $user1->mBlock = $block;
886 $user1->load();
887 $this->assertTrue( $user1->isBlocked() );
888
889 // 2. Create a new request, set the cookie to just the block ID, and the user should
890 // still get blocked when they log in again.
891 $request2 = new FauxRequest();
892 $request2->setCookie( 'BlockID', $block->getId() );
893 $user2 = User::newFromSession( $request2 );
894 $user2->load();
895 $this->assertNotEquals( $user1->getId(), $user2->getId() );
896 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
897 $this->assertTrue( $user2->isAnon() );
898 $this->assertFalse( $user2->isLoggedIn() );
899 $this->assertTrue( $user2->isBlocked() );
900 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
901
902 // Clean up.
903 $block->delete();
904 }
905
906 public function testIsPingLimitable() {
907 $request = new FauxRequest();
908 $request->setIP( '1.2.3.4' );
909 $user = User::newFromSession( $request );
910
911 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
912 $this->assertTrue( $user->isPingLimitable() );
913
914 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
915 $this->assertFalse( $user->isPingLimitable() );
916
917 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
918 $this->assertFalse( $user->isPingLimitable() );
919
920 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
921 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
922 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
923 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
924 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
925 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
926 }
927
928 public function provideExperienceLevel() {
929 return [
930 [ 2, 2, 'newcomer' ],
931 [ 12, 3, 'newcomer' ],
932 [ 8, 5, 'newcomer' ],
933 [ 15, 10, 'learner' ],
934 [ 450, 20, 'learner' ],
935 [ 460, 33, 'learner' ],
936 [ 525, 28, 'learner' ],
937 [ 538, 33, 'experienced' ],
938 ];
939 }
940
941 /**
942 * @dataProvider provideExperienceLevel
943 */
944 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
945 $this->setMwGlobals( [
946 'wgLearnerEdits' => 10,
947 'wgLearnerMemberSince' => 4,
948 'wgExperiencedUserEdits' => 500,
949 'wgExperiencedUserMemberSince' => 30,
950 ] );
951
952 $db = wfGetDB( DB_MASTER );
953
954 $data = new stdClass();
955 $data->user_id = 1;
956 $data->user_name = 'name';
957 $data->user_real_name = 'Real Name';
958 $data->user_touched = 1;
959 $data->user_token = 'token';
960 $data->user_email = 'a@a.a';
961 $data->user_email_authenticated = null;
962 $data->user_email_token = 'token';
963 $data->user_email_token_expires = null;
964 $data->user_editcount = $editCount;
965 $data->user_registration = $db->timestamp( time() - $memberSince * 86400 );
966 $user = User::newFromRow( $data );
967
968 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
969 }
970
971 public function testExperienceLevelAnon() {
972 $user = User::newFromName( '10.11.12.13', false );
973
974 $this->assertFalse( $user->getExperienceLevel() );
975 }
976
977 public static function provideIsLocallBlockedProxy() {
978 return [
979 [ '1.2.3.4', '1.2.3.4' ],
980 [ '1.2.3.4', '1.2.3.0/16' ],
981 ];
982 }
983
984 /**
985 * @dataProvider provideIsLocallBlockedProxy
986 * @covers User::isLocallyBlockedProxy
987 */
988 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
989 $this->setMwGlobals(
990 'wgProxyList', []
991 );
992 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
993
994 $this->setMwGlobals(
995 'wgProxyList',
996 [
997 $blockListEntry
998 ]
999 );
1000 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1001
1002 $this->setMwGlobals(
1003 'wgProxyList',
1004 [
1005 'test' => $blockListEntry
1006 ]
1007 );
1008 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1009
1010 $this->hideDeprecated(
1011 'IP addresses in the keys of $wgProxyList (found the following IP ' .
1012 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
1013 );
1014 $this->setMwGlobals(
1015 'wgProxyList',
1016 [
1017 $blockListEntry => 'test'
1018 ]
1019 );
1020 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
1021 }
1022 }