Merge "Move some more classes to comply with class per file"
[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 [ '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' ],
230 ];
231 }
232
233 /**
234 * Test, if for all rights a right- message exist,
235 * which is used on Special:ListGroupRights as help text
236 * Extensions and core
237 */
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' );
242
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-' ) );
248 }
249 }
250
251 sort( $allRights );
252 sort( $rightsWithMessage );
253
254 $this->assertEquals(
255 $allRights,
256 $rightsWithMessage,
257 'Each user rights (core/extensions) has a corresponding right- message.'
258 );
259 }
260
261 /**
262 * Test User::editCount
263 * @group medium
264 * @covers User::getEditCount
265 */
266 public function testGetEditCount() {
267 $user = $this->getMutableTestUser()->getUser();
268
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',
275 0,
276 false,
277 $user
278 );
279 }
280
281 $this->assertEquals(
282 3,
283 $user->getEditCount(),
284 'After three edits, the user edit count should be 3'
285 );
286
287 // increase the edit count
288 $user->incEditCount();
289
290 $this->assertEquals(
291 4,
292 $user->getEditCount(),
293 'After increasing the edit count manually, the user edit count should be 4'
294 );
295 }
296
297 /**
298 * Test User::editCount
299 * @group medium
300 * @covers User::getEditCount
301 */
302 public function testGetEditCountForAnons() {
303 $user = User::newFromName( 'Anonymous' );
304
305 $this->assertNull(
306 $user->getEditCount(),
307 'Edit count starts null for anonymous users.'
308 );
309
310 $user->incEditCount();
311
312 $this->assertNull(
313 $user->getEditCount(),
314 'Edit count remains null for anonymous users despite calls to increase it.'
315 );
316 }
317
318 /**
319 * Test User::editCount
320 * @group medium
321 * @covers User::incEditCount
322 */
323 public function testIncEditCount() {
324 $user = $this->getMutableTestUser()->getUser();
325 $user->incEditCount();
326
327 $reloadedUser = User::newFromId( $user->getId() );
328 $reloadedUser->incEditCount();
329
330 $this->assertEquals(
331 2,
332 $reloadedUser->getEditCount(),
333 'Increasing the edit count after a fresh load leaves the object up to date.'
334 );
335 }
336
337 /**
338 * Test changing user options.
339 * @covers User::setOption
340 * @covers User::getOption
341 */
342 public function testOptions() {
343 $user = $this->getMutableTestUser()->getUser();
344
345 $user->setOption( 'userjs-someoption', 'test' );
346 $user->setOption( 'rclimit', 200 );
347 $user->saveSettings();
348
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' ) );
353
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' ) );
358 }
359
360 /**
361 * T39963
362 * Make sure defaults are loaded when setOption is called.
363 * @covers User::loadOptions
364 */
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' ) );
370 }
371
372 /**
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()
380 */
381 public function testCheckPasswordValidity() {
382 $this->setMwGlobals( [
383 'wgPasswordPolicy' => [
384 'policies' => [
385 'sysop' => [
386 'MinimalPasswordLength' => 8,
387 'MinimumPasswordLengthToLogin' => 1,
388 'PasswordCannotMatchUsername' => 1,
389 ],
390 'default' => [
391 'MinimalPasswordLength' => 6,
392 'PasswordCannotMatchUsername' => true,
393 'PasswordCannotMatchBlacklist' => true,
394 'MaximalPasswordLength' => 40,
395 ],
396 ],
397 'checks' => [
398 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
399 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
400 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
401 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
402 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
403 ],
404 ],
405 ] );
406
407 $user = static::getTestUser()->getUser();
408
409 // Sanity
410 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
411
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' ) );
417
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 ) );
424
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() ) );
429
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' ) );
434 }
435
436 /**
437 * @covers User::getCanonicalName()
438 * @dataProvider provideGetCanonicalName
439 */
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,
450 ];
451 return false;
452 }
453 },
454 ],
455 ] );
456
457 foreach ( $expectedArray as $validate => $expected ) {
458 $this->assertEquals(
459 $expected,
460 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
461 }
462 }
463
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' ] ],
480 ];
481 }
482
483 /**
484 * @covers User::equals
485 */
486 public function testEquals() {
487 $first = $this->getMutableTestUser()->getUser();
488 $second = User::newFromName( $first->getName() );
489
490 $this->assertTrue( $first->equals( $first ) );
491 $this->assertTrue( $first->equals( $second ) );
492 $this->assertTrue( $second->equals( $first ) );
493
494 $third = $this->getMutableTestUser()->getUser();
495 $fourth = $this->getMutableTestUser()->getUser();
496
497 $this->assertFalse( $third->equals( $fourth ) );
498 $this->assertFalse( $fourth->equals( $third ) );
499
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 ) );
505 }
506
507 /**
508 * @covers User::getId
509 */
510 public function testGetId() {
511 $user = static::getTestUser()->getUser();
512 $this->assertTrue( $user->getId() > 0 );
513 }
514
515 /**
516 * @covers User::isLoggedIn
517 * @covers User::isAnon
518 */
519 public function testLoggedIn() {
520 $user = $this->getMutableTestUser()->getUser();
521 $this->assertTrue( $user->isLoggedIn() );
522 $this->assertFalse( $user->isAnon() );
523
524 // Non-existent users are perceived as anonymous
525 $user = User::newFromName( 'UTNonexistent' );
526 $this->assertFalse( $user->isLoggedIn() );
527 $this->assertTrue( $user->isAnon() );
528
529 $user = new User;
530 $this->assertFalse( $user->isLoggedIn() );
531 $this->assertTrue( $user->isAnon() );
532 }
533
534 /**
535 * @covers User::checkAndSetTouched
536 */
537 public function testCheckAndSetTouched() {
538 $user = $this->getMutableTestUser()->getUser();
539 $user = TestingAccessWrapper::newFromObject( $user );
540 $this->assertTrue( $user->isLoggedIn() );
541
542 $touched = $user->getDBTouched();
543 $this->assertTrue(
544 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
545 $this->assertGreaterThan(
546 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
547
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" );
553 }
554
555 /**
556 * @covers User::findUsersByGroup
557 */
558 public function testFindUsersByGroup() {
559 $users = User::findUsersByGroup( [] );
560 $this->assertEquals( 0, iterator_count( $users ) );
561
562 $users = User::findUsersByGroup( 'foo' );
563 $this->assertEquals( 0, iterator_count( $users ) );
564
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() ) );
570
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() ) );
579
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() ) );
586 }
587
588 /**
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
592 */
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 ] );
600
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();
615
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() );
622
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 );
629
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() );
645
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.
656
657 // Clean up.
658 $block->delete();
659 }
660
661 /**
662 * Make sure that no cookie is set to track autoblocked users
663 * when $wgCookieSetOnAutoblock is false.
664 */
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 ] );
672
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();
683
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 );
693
694 // Clean up.
695 $block->delete();
696 }
697
698 /**
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.
702 */
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();
719
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',
735 5.0
736 );
737
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'] );
751
752 // Clean up.
753 $block->delete();
754 }
755
756 public function testSoftBlockRanges() {
757 global $wgUser;
758
759 $this->setMwGlobals( [
760 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
761 'wgUser' => null,
762 ] );
763
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() );
769
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() );
777
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() );
783 }
784
785 /**
786 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
787 */
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 ] );
795
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();
806
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() );
816
817 // Clean up.
818 $block->delete();
819 }
820
821 /**
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.
824 */
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 ] );
832
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() );
844
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.
857
858 // Clean up.
859 $block->delete();
860 }
861
862 public function testIsPingLimitable() {
863 $request = new FauxRequest();
864 $request->setIP( '1.2.3.4' );
865 $user = User::newFromSession( $request );
866
867 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
868 $this->assertTrue( $user->isPingLimitable() );
869
870 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
871 $this->assertFalse( $user->isPingLimitable() );
872
873 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
874 $this->assertFalse( $user->isPingLimitable() );
875
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() );
882 }
883
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' ],
894 ];
895 }
896
897 /**
898 * @dataProvider provideExperienceLevel
899 */
900 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
901 $this->setMwGlobals( [
902 'wgLearnerEdits' => 10,
903 'wgLearnerMemberSince' => 4,
904 'wgExperiencedUserEdits' => 500,
905 'wgExperiencedUserMemberSince' => 30,
906 ] );
907
908 $db = wfGetDB( DB_MASTER );
909
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 );
923
924 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
925 }
926
927 public function testExperienceLevelAnon() {
928 $user = User::newFromName( '10.11.12.13', false );
929
930 $this->assertFalse( $user->getExperienceLevel() );
931 }
932
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' ],
937 ];
938 }
939
940 /**
941 * @dataProvider provideIsLocallBlockedProxy
942 * @covers User::isLocallyBlockedProxy
943 */
944 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
945 $this->setMwGlobals(
946 'wgProxyList', []
947 );
948 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
949
950 $this->setMwGlobals(
951 'wgProxyList',
952 [
953 $blockListEntry
954 ]
955 );
956 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
957
958 $this->setMwGlobals(
959 'wgProxyList',
960 [
961 'test' => $blockListEntry
962 ]
963 );
964 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
965
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)'
969 );
970 $this->setMwGlobals(
971 'wgProxyList',
972 [
973 $blockListEntry => 'test'
974 ]
975 );
976 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
977 }
978 }