Merge "Embed TinyRGB color profile when JPG EXIF Color Space = sRGB but no profile...
[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 = new User;
29 $this->user->addToDatabase();
30 $this->user->addGroup( 'unittesters' );
31 }
32
33 private function setUpPermissionGlobals() {
34 global $wgGroupPermissions, $wgRevokePermissions;
35
36 # Data for regular $wgGroupPermissions test
37 $wgGroupPermissions['unittesters'] = [
38 'test' => true,
39 'runtest' => true,
40 'writetest' => false,
41 'nukeworld' => false,
42 ];
43 $wgGroupPermissions['testwriters'] = [
44 'test' => true,
45 'writetest' => true,
46 'modifytest' => true,
47 ];
48
49 # Data for regular $wgRevokePermissions test
50 $wgRevokePermissions['formertesters'] = [
51 'runtest' => true,
52 ];
53
54 # For the options test
55 $wgGroupPermissions['*'] = [
56 'editmyoptions' => true,
57 ];
58 }
59
60 /**
61 * @covers User::getGroupPermissions
62 */
63 public function testGroupPermissions() {
64 $rights = User::getGroupPermissions( [ 'unittesters' ] );
65 $this->assertContains( 'runtest', $rights );
66 $this->assertNotContains( 'writetest', $rights );
67 $this->assertNotContains( 'modifytest', $rights );
68 $this->assertNotContains( 'nukeworld', $rights );
69
70 $rights = User::getGroupPermissions( [ 'unittesters', 'testwriters' ] );
71 $this->assertContains( 'runtest', $rights );
72 $this->assertContains( 'writetest', $rights );
73 $this->assertContains( 'modifytest', $rights );
74 $this->assertNotContains( 'nukeworld', $rights );
75 }
76
77 /**
78 * @covers User::getGroupPermissions
79 */
80 public function testRevokePermissions() {
81 $rights = User::getGroupPermissions( [ 'unittesters', 'formertesters' ] );
82 $this->assertNotContains( 'runtest', $rights );
83 $this->assertNotContains( 'writetest', $rights );
84 $this->assertNotContains( 'modifytest', $rights );
85 $this->assertNotContains( 'nukeworld', $rights );
86 }
87
88 /**
89 * @covers User::getRights
90 */
91 public function testUserPermissions() {
92 $rights = $this->user->getRights();
93 $this->assertContains( 'runtest', $rights );
94 $this->assertNotContains( 'writetest', $rights );
95 $this->assertNotContains( 'modifytest', $rights );
96 $this->assertNotContains( 'nukeworld', $rights );
97 }
98
99 /**
100 * @covers User::getRights
101 */
102 public function testUserGetRightsHooks() {
103 $user = new User;
104 $user->addToDatabase();
105 $user->addGroup( 'unittesters' );
106 $user->addGroup( 'testwriters' );
107 $userWrapper = TestingAccessWrapper::newFromObject( $user );
108
109 $rights = $user->getRights();
110 $this->assertContains( 'test', $rights, 'sanity check' );
111 $this->assertContains( 'runtest', $rights, 'sanity check' );
112 $this->assertContains( 'writetest', $rights, 'sanity check' );
113 $this->assertNotContains( 'nukeworld', $rights, 'sanity check' );
114
115 // Add a hook manipluating the rights
116 $this->mergeMwGlobalArrayValue( 'wgHooks', [ 'UserGetRights' => [ function ( $user, &$rights ) {
117 $rights[] = 'nukeworld';
118 $rights = array_diff( $rights, [ 'writetest' ] );
119 } ] ] );
120
121 $userWrapper->mRights = null;
122 $rights = $user->getRights();
123 $this->assertContains( 'test', $rights );
124 $this->assertContains( 'runtest', $rights );
125 $this->assertNotContains( 'writetest', $rights );
126 $this->assertContains( 'nukeworld', $rights );
127
128 // Add a Session that limits rights
129 $mock = $this->getMockBuilder( stdclass::class )
130 ->setMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
131 ->getMock();
132 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
133 $mock->method( 'getSessionId' )->willReturn(
134 new MediaWiki\Session\SessionId( str_repeat( 'X', 32 ) )
135 );
136 $session = MediaWiki\Session\TestUtils::getDummySession( $mock );
137 $mockRequest = $this->getMockBuilder( FauxRequest::class )
138 ->setMethods( [ 'getSession' ] )
139 ->getMock();
140 $mockRequest->method( 'getSession' )->willReturn( $session );
141 $userWrapper->mRequest = $mockRequest;
142
143 $userWrapper->mRights = null;
144 $rights = $user->getRights();
145 $this->assertContains( 'test', $rights );
146 $this->assertNotContains( 'runtest', $rights );
147 $this->assertNotContains( 'writetest', $rights );
148 $this->assertNotContains( 'nukeworld', $rights );
149 }
150
151 /**
152 * @dataProvider provideGetGroupsWithPermission
153 * @covers User::getGroupsWithPermission
154 */
155 public function testGetGroupsWithPermission( $expected, $right ) {
156 $result = User::getGroupsWithPermission( $right );
157 sort( $result );
158 sort( $expected );
159
160 $this->assertEquals( $expected, $result, "Groups with permission $right" );
161 }
162
163 public static function provideGetGroupsWithPermission() {
164 return [
165 [
166 [ 'unittesters', 'testwriters' ],
167 'test'
168 ],
169 [
170 [ 'unittesters' ],
171 'runtest'
172 ],
173 [
174 [ 'testwriters' ],
175 'writetest'
176 ],
177 [
178 [ 'testwriters' ],
179 'modifytest'
180 ],
181 ];
182 }
183
184 /**
185 * @dataProvider provideIPs
186 * @covers User::isIP
187 */
188 public function testIsIP( $value, $result, $message ) {
189 $this->assertEquals( $this->user->isIP( $value ), $result, $message );
190 }
191
192 public static function provideIPs() {
193 return [
194 [ '', false, 'Empty string' ],
195 [ ' ', false, 'Blank space' ],
196 [ '10.0.0.0', true, 'IPv4 private 10/8' ],
197 [ '10.255.255.255', true, 'IPv4 private 10/8' ],
198 [ '192.168.1.1', true, 'IPv4 private 192.168/16' ],
199 [ '203.0.113.0', true, 'IPv4 example' ],
200 [ '2002:ffff:ffff:ffff:ffff:ffff:ffff:ffff', true, 'IPv6 example' ],
201 // Not valid IPs but classified as such by MediaWiki for negated asserting
202 // of whether this might be the identifier of a logged-out user or whether
203 // to allow usernames like it.
204 [ '300.300.300.300', true, 'Looks too much like an IPv4 address' ],
205 [ '203.0.113.xxx', true, 'Assigned by UseMod to cloaked logged-out users' ],
206 ];
207 }
208
209 /**
210 * @dataProvider provideUserNames
211 * @covers User::isValidUserName
212 */
213 public function testIsValidUserName( $username, $result, $message ) {
214 $this->assertEquals( $this->user->isValidUserName( $username ), $result, $message );
215 }
216
217 public static function provideUserNames() {
218 return [
219 [ '', false, 'Empty string' ],
220 [ ' ', false, 'Blank space' ],
221 [ 'abcd', false, 'Starts with small letter' ],
222 [ 'Ab/cd', false, 'Contains slash' ],
223 [ 'Ab cd', true, 'Whitespace' ],
224 [ '192.168.1.1', false, 'IP' ],
225 [ 'User:Abcd', false, 'Reserved Namespace' ],
226 [ '12abcd232', true, 'Starts with Numbers' ],
227 [ '?abcd', true, 'Start with ? mark' ],
228 [ '#abcd', false, 'Start with #' ],
229 [ 'Abcdകഖഗഘ', true, ' Mixed scripts' ],
230 [ 'ജോസ്‌തോമസ്', false, 'ZWNJ- Format control character' ],
231 [ 'Ab cd', false, ' Ideographic space' ],
232 [ '300.300.300.300', false, 'Looks too much like an IPv4 address' ],
233 [ '302.113.311.900', false, 'Looks too much like an IPv4 address' ],
234 [ '203.0.113.xxx', false, 'Reserved for usage by UseMod for cloaked logged-out users' ],
235 ];
236 }
237
238 /**
239 * Test, if for all rights a right- message exist,
240 * which is used on Special:ListGroupRights as help text
241 * Extensions and core
242 */
243 public function testAllRightsWithMessage() {
244 // Getting all user rights, for core: User::$mCoreRights, for extensions: $wgAvailableRights
245 $allRights = User::getAllRights();
246 $allMessageKeys = Language::getMessageKeysFor( 'en' );
247
248 $rightsWithMessage = [];
249 foreach ( $allMessageKeys as $message ) {
250 // === 0: must be at beginning of string (position 0)
251 if ( strpos( $message, 'right-' ) === 0 ) {
252 $rightsWithMessage[] = substr( $message, strlen( 'right-' ) );
253 }
254 }
255
256 sort( $allRights );
257 sort( $rightsWithMessage );
258
259 $this->assertEquals(
260 $allRights,
261 $rightsWithMessage,
262 'Each user rights (core/extensions) has a corresponding right- message.'
263 );
264 }
265
266 /**
267 * Test User::editCount
268 * @group medium
269 * @covers User::getEditCount
270 */
271 public function testGetEditCount() {
272 $user = $this->getMutableTestUser()->getUser();
273
274 // let the user have a few (3) edits
275 $page = WikiPage::factory( Title::newFromText( 'Help:UserTest_EditCount' ) );
276 for ( $i = 0; $i < 3; $i++ ) {
277 $page->doEditContent(
278 ContentHandler::makeContent( (string)$i, $page->getTitle() ),
279 'test',
280 0,
281 false,
282 $user
283 );
284 }
285
286 $this->assertEquals(
287 3,
288 $user->getEditCount(),
289 'After three edits, the user edit count should be 3'
290 );
291
292 // increase the edit count
293 $user->incEditCount();
294
295 $this->assertEquals(
296 4,
297 $user->getEditCount(),
298 'After increasing the edit count manually, the user edit count should be 4'
299 );
300 }
301
302 /**
303 * Test User::editCount
304 * @group medium
305 * @covers User::getEditCount
306 */
307 public function testGetEditCountForAnons() {
308 $user = User::newFromName( 'Anonymous' );
309
310 $this->assertNull(
311 $user->getEditCount(),
312 'Edit count starts null for anonymous users.'
313 );
314
315 $user->incEditCount();
316
317 $this->assertNull(
318 $user->getEditCount(),
319 'Edit count remains null for anonymous users despite calls to increase it.'
320 );
321 }
322
323 /**
324 * Test User::editCount
325 * @group medium
326 * @covers User::incEditCount
327 */
328 public function testIncEditCount() {
329 $user = $this->getMutableTestUser()->getUser();
330 $user->incEditCount();
331
332 $reloadedUser = User::newFromId( $user->getId() );
333 $reloadedUser->incEditCount();
334
335 $this->assertEquals(
336 2,
337 $reloadedUser->getEditCount(),
338 'Increasing the edit count after a fresh load leaves the object up to date.'
339 );
340 }
341
342 /**
343 * Test changing user options.
344 * @covers User::setOption
345 * @covers User::getOption
346 */
347 public function testOptions() {
348 $user = $this->getMutableTestUser()->getUser();
349
350 $user->setOption( 'userjs-someoption', 'test' );
351 $user->setOption( 'rclimit', 200 );
352 $user->saveSettings();
353
354 $user = User::newFromName( $user->getName() );
355 $user->load( User::READ_LATEST );
356 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
357 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
358
359 $user = User::newFromName( $user->getName() );
360 MediaWikiServices::getInstance()->getMainWANObjectCache()->clearProcessCache();
361 $this->assertEquals( 'test', $user->getOption( 'userjs-someoption' ) );
362 $this->assertEquals( 200, $user->getOption( 'rclimit' ) );
363 }
364
365 /**
366 * T39963
367 * Make sure defaults are loaded when setOption is called.
368 * @covers User::loadOptions
369 */
370 public function testAnonOptions() {
371 global $wgDefaultUserOptions;
372 $this->user->setOption( 'userjs-someoption', 'test' );
373 $this->assertEquals( $wgDefaultUserOptions['rclimit'], $this->user->getOption( 'rclimit' ) );
374 $this->assertEquals( 'test', $this->user->getOption( 'userjs-someoption' ) );
375 }
376
377 /**
378 * Test password validity checks. There are 3 checks in core,
379 * - ensure the password meets the minimal length
380 * - ensure the password is not the same as the username
381 * - ensure the username/password combo isn't forbidden
382 * @covers User::checkPasswordValidity()
383 * @covers User::getPasswordValidity()
384 * @covers User::isValidPassword()
385 */
386 public function testCheckPasswordValidity() {
387 $this->setMwGlobals( [
388 'wgPasswordPolicy' => [
389 'policies' => [
390 'sysop' => [
391 'MinimalPasswordLength' => 8,
392 'MinimumPasswordLengthToLogin' => 1,
393 'PasswordCannotMatchUsername' => 1,
394 ],
395 'default' => [
396 'MinimalPasswordLength' => 6,
397 'PasswordCannotMatchUsername' => true,
398 'PasswordCannotMatchBlacklist' => true,
399 'MaximalPasswordLength' => 40,
400 ],
401 ],
402 'checks' => [
403 'MinimalPasswordLength' => 'PasswordPolicyChecks::checkMinimalPasswordLength',
404 'MinimumPasswordLengthToLogin' => 'PasswordPolicyChecks::checkMinimumPasswordLengthToLogin',
405 'PasswordCannotMatchUsername' => 'PasswordPolicyChecks::checkPasswordCannotMatchUsername',
406 'PasswordCannotMatchBlacklist' => 'PasswordPolicyChecks::checkPasswordCannotMatchBlacklist',
407 'MaximalPasswordLength' => 'PasswordPolicyChecks::checkMaximalPasswordLength',
408 ],
409 ],
410 ] );
411
412 $user = static::getTestUser()->getUser();
413
414 // Sanity
415 $this->assertTrue( $user->isValidPassword( 'Password1234' ) );
416
417 // Minimum length
418 $this->assertFalse( $user->isValidPassword( 'a' ) );
419 $this->assertFalse( $user->checkPasswordValidity( 'a' )->isGood() );
420 $this->assertTrue( $user->checkPasswordValidity( 'a' )->isOK() );
421 $this->assertEquals( 'passwordtooshort', $user->getPasswordValidity( 'a' ) );
422
423 // Maximum length
424 $longPass = str_repeat( 'a', 41 );
425 $this->assertFalse( $user->isValidPassword( $longPass ) );
426 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isGood() );
427 $this->assertFalse( $user->checkPasswordValidity( $longPass )->isOK() );
428 $this->assertEquals( 'passwordtoolong', $user->getPasswordValidity( $longPass ) );
429
430 // Matches username
431 $this->assertFalse( $user->checkPasswordValidity( $user->getName() )->isGood() );
432 $this->assertTrue( $user->checkPasswordValidity( $user->getName() )->isOK() );
433 $this->assertEquals( 'password-name-match', $user->getPasswordValidity( $user->getName() ) );
434
435 // On the forbidden list
436 $user = User::newFromName( 'Useruser' );
437 $this->assertFalse( $user->checkPasswordValidity( 'Passpass' )->isGood() );
438 $this->assertEquals( 'password-login-forbidden', $user->getPasswordValidity( 'Passpass' ) );
439 }
440
441 /**
442 * @covers User::getCanonicalName()
443 * @dataProvider provideGetCanonicalName
444 */
445 public function testGetCanonicalName( $name, $expectedArray ) {
446 // fake interwiki map for the 'Interwiki prefix' testcase
447 $this->mergeMwGlobalArrayValue( 'wgHooks', [
448 'InterwikiLoadPrefix' => [
449 function ( $prefix, &$iwdata ) {
450 if ( $prefix === 'interwiki' ) {
451 $iwdata = [
452 'iw_url' => 'http://example.com/',
453 'iw_local' => 0,
454 'iw_trans' => 0,
455 ];
456 return false;
457 }
458 },
459 ],
460 ] );
461
462 foreach ( $expectedArray as $validate => $expected ) {
463 $this->assertEquals(
464 $expected,
465 User::getCanonicalName( $name, $validate === 'false' ? false : $validate ), $validate );
466 }
467 }
468
469 public static function provideGetCanonicalName() {
470 return [
471 'Leading space' => [ ' Leading space', [ 'creatable' => 'Leading space' ] ],
472 'Trailing space ' => [ 'Trailing space ', [ 'creatable' => 'Trailing space' ] ],
473 'Namespace prefix' => [ 'Talk:Username', [ 'creatable' => false, 'usable' => false,
474 'valid' => false, 'false' => 'Talk:Username' ] ],
475 'Interwiki prefix' => [ 'interwiki:Username', [ 'creatable' => false, 'usable' => false,
476 'valid' => false, 'false' => 'Interwiki:Username' ] ],
477 'With hash' => [ 'name with # hash', [ 'creatable' => false, 'usable' => false ] ],
478 'Multi spaces' => [ 'Multi spaces', [ 'creatable' => 'Multi spaces',
479 'usable' => 'Multi spaces' ] ],
480 'Lowercase' => [ 'lowercase', [ 'creatable' => 'Lowercase' ] ],
481 'Invalid character' => [ 'in[]valid', [ 'creatable' => false, 'usable' => false,
482 'valid' => false, 'false' => 'In[]valid' ] ],
483 'With slash' => [ 'with / slash', [ 'creatable' => false, 'usable' => false, 'valid' => false,
484 'false' => 'With / slash' ] ],
485 ];
486 }
487
488 /**
489 * @covers User::equals
490 */
491 public function testEquals() {
492 $first = $this->getMutableTestUser()->getUser();
493 $second = User::newFromName( $first->getName() );
494
495 $this->assertTrue( $first->equals( $first ) );
496 $this->assertTrue( $first->equals( $second ) );
497 $this->assertTrue( $second->equals( $first ) );
498
499 $third = $this->getMutableTestUser()->getUser();
500 $fourth = $this->getMutableTestUser()->getUser();
501
502 $this->assertFalse( $third->equals( $fourth ) );
503 $this->assertFalse( $fourth->equals( $third ) );
504
505 // Test users loaded from db with id
506 $user = $this->getMutableTestUser()->getUser();
507 $fifth = User::newFromId( $user->getId() );
508 $sixth = User::newFromName( $user->getName() );
509 $this->assertTrue( $fifth->equals( $sixth ) );
510 }
511
512 /**
513 * @covers User::getId
514 */
515 public function testGetId() {
516 $user = static::getTestUser()->getUser();
517 $this->assertTrue( $user->getId() > 0 );
518 }
519
520 /**
521 * @covers User::isLoggedIn
522 * @covers User::isAnon
523 */
524 public function testLoggedIn() {
525 $user = $this->getMutableTestUser()->getUser();
526 $this->assertTrue( $user->isLoggedIn() );
527 $this->assertFalse( $user->isAnon() );
528
529 // Non-existent users are perceived as anonymous
530 $user = User::newFromName( 'UTNonexistent' );
531 $this->assertFalse( $user->isLoggedIn() );
532 $this->assertTrue( $user->isAnon() );
533
534 $user = new User;
535 $this->assertFalse( $user->isLoggedIn() );
536 $this->assertTrue( $user->isAnon() );
537 }
538
539 /**
540 * @covers User::checkAndSetTouched
541 */
542 public function testCheckAndSetTouched() {
543 $user = $this->getMutableTestUser()->getUser();
544 $user = TestingAccessWrapper::newFromObject( $user );
545 $this->assertTrue( $user->isLoggedIn() );
546
547 $touched = $user->getDBTouched();
548 $this->assertTrue(
549 $user->checkAndSetTouched(), "checkAndSetTouched() succeded" );
550 $this->assertGreaterThan(
551 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched()" );
552
553 $touched = $user->getDBTouched();
554 $this->assertTrue(
555 $user->checkAndSetTouched(), "checkAndSetTouched() succeded #2" );
556 $this->assertGreaterThan(
557 $touched, $user->getDBTouched(), "user_touched increased with casOnTouched() #2" );
558 }
559
560 /**
561 * @covers User::findUsersByGroup
562 */
563 public function testFindUsersByGroup() {
564 $users = User::findUsersByGroup( [] );
565 $this->assertEquals( 0, iterator_count( $users ) );
566
567 $users = User::findUsersByGroup( 'foo' );
568 $this->assertEquals( 0, iterator_count( $users ) );
569
570 $user = $this->getMutableTestUser( [ 'foo' ] )->getUser();
571 $users = User::findUsersByGroup( 'foo' );
572 $this->assertEquals( 1, iterator_count( $users ) );
573 $users->rewind();
574 $this->assertTrue( $user->equals( $users->current() ) );
575
576 // arguments have OR relationship
577 $user2 = $this->getMutableTestUser( [ 'bar' ] )->getUser();
578 $users = User::findUsersByGroup( [ 'foo', 'bar' ] );
579 $this->assertEquals( 2, iterator_count( $users ) );
580 $users->rewind();
581 $this->assertTrue( $user->equals( $users->current() ) );
582 $users->next();
583 $this->assertTrue( $user2->equals( $users->current() ) );
584
585 // users are not duplicated
586 $user = $this->getMutableTestUser( [ 'baz', 'boom' ] )->getUser();
587 $users = User::findUsersByGroup( [ 'baz', 'boom' ] );
588 $this->assertEquals( 1, iterator_count( $users ) );
589 $users->rewind();
590 $this->assertTrue( $user->equals( $users->current() ) );
591 }
592
593 /**
594 * When a user is autoblocked a cookie is set with which to track them
595 * in case they log out and change IP addresses.
596 * @link https://phabricator.wikimedia.org/T5233
597 */
598 public function testAutoblockCookies() {
599 // Set up the bits of global configuration that we use.
600 $this->setMwGlobals( [
601 'wgCookieSetOnAutoblock' => true,
602 'wgCookiePrefix' => 'wmsitetitle',
603 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
604 ] );
605
606 // 1. Log in a test user, and block them.
607 $user1tmp = $this->getTestUser()->getUser();
608 $request1 = new FauxRequest();
609 $request1->getSession()->setUser( $user1tmp );
610 $expiryFiveHours = wfTimestamp() + ( 5 * 60 * 60 );
611 $block = new Block( [
612 'enableAutoblock' => true,
613 'expiry' => wfTimestamp( TS_MW, $expiryFiveHours ),
614 ] );
615 $block->setTarget( $user1tmp );
616 $block->insert();
617 $user1 = User::newFromSession( $request1 );
618 $user1->mBlock = $block;
619 $user1->load();
620
621 // Confirm that the block has been applied as required.
622 $this->assertTrue( $user1->isLoggedIn() );
623 $this->assertTrue( $user1->isBlocked() );
624 $this->assertEquals( Block::TYPE_USER, $block->getType() );
625 $this->assertTrue( $block->isAutoblocking() );
626 $this->assertGreaterThanOrEqual( 1, $block->getId() );
627
628 // Test for the desired cookie name, value, and expiry.
629 $cookies = $request1->response()->getCookies();
630 $this->assertArrayHasKey( 'wmsitetitleBlockID', $cookies );
631 $this->assertEquals( $expiryFiveHours, $cookies['wmsitetitleBlockID']['expire'] );
632 $cookieValue = Block::getIdFromCookieValue( $cookies['wmsitetitleBlockID']['value'] );
633 $this->assertEquals( $block->getId(), $cookieValue );
634
635 // 2. Create a new request, set the cookies, and see if the (anon) user is blocked.
636 $request2 = new FauxRequest();
637 $request2->setCookie( 'BlockID', $block->getCookieValue() );
638 $user2 = User::newFromSession( $request2 );
639 $user2->load();
640 $this->assertNotEquals( $user1->getId(), $user2->getId() );
641 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
642 $this->assertTrue( $user2->isAnon() );
643 $this->assertFalse( $user2->isLoggedIn() );
644 $this->assertTrue( $user2->isBlocked() );
645 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
646 // Can't directly compare the objects becuase of member type differences.
647 // One day this will work: $this->assertEquals( $block, $user2->getBlock() );
648 $this->assertEquals( $block->getId(), $user2->getBlock()->getId() );
649 $this->assertEquals( $block->getExpiry(), $user2->getBlock()->getExpiry() );
650
651 // 3. Finally, set up a request as a new user, and the block should still be applied.
652 $user3tmp = $this->getTestUser()->getUser();
653 $request3 = new FauxRequest();
654 $request3->getSession()->setUser( $user3tmp );
655 $request3->setCookie( 'BlockID', $block->getId() );
656 $user3 = User::newFromSession( $request3 );
657 $user3->load();
658 $this->assertTrue( $user3->isLoggedIn() );
659 $this->assertTrue( $user3->isBlocked() );
660 $this->assertEquals( true, $user3->getBlock()->isAutoblocking() ); // Non-strict type-check.
661
662 // Clean up.
663 $block->delete();
664 }
665
666 /**
667 * Make sure that no cookie is set to track autoblocked users
668 * when $wgCookieSetOnAutoblock is false.
669 */
670 public function testAutoblockCookiesDisabled() {
671 // Set up the bits of global configuration that we use.
672 $this->setMwGlobals( [
673 'wgCookieSetOnAutoblock' => false,
674 'wgCookiePrefix' => 'wm_no_cookies',
675 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
676 ] );
677
678 // 1. Log in a test user, and block them.
679 $testUser = $this->getTestUser()->getUser();
680 $request1 = new FauxRequest();
681 $request1->getSession()->setUser( $testUser );
682 $block = new Block( [ 'enableAutoblock' => true ] );
683 $block->setTarget( $testUser );
684 $block->insert();
685 $user = User::newFromSession( $request1 );
686 $user->mBlock = $block;
687 $user->load();
688
689 // 2. Test that the cookie IS NOT present.
690 $this->assertTrue( $user->isLoggedIn() );
691 $this->assertTrue( $user->isBlocked() );
692 $this->assertEquals( Block::TYPE_USER, $block->getType() );
693 $this->assertTrue( $block->isAutoblocking() );
694 $this->assertGreaterThanOrEqual( 1, $user->getBlockId() );
695 $this->assertGreaterThanOrEqual( $block->getId(), $user->getBlockId() );
696 $cookies = $request1->response()->getCookies();
697 $this->assertArrayNotHasKey( 'wm_no_cookiesBlockID', $cookies );
698
699 // Clean up.
700 $block->delete();
701 }
702
703 /**
704 * When a user is autoblocked and a cookie is set to track them, the expiry time of the cookie
705 * should match the block's expiry, to a maximum of 24 hours. If the expiry time is changed,
706 * the cookie's should change with it.
707 */
708 public function testAutoblockCookieInfiniteExpiry() {
709 $this->setMwGlobals( [
710 'wgCookieSetOnAutoblock' => true,
711 'wgCookiePrefix' => 'wm_infinite_block',
712 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
713 ] );
714 // 1. Log in a test user, and block them indefinitely.
715 $user1Tmp = $this->getTestUser()->getUser();
716 $request1 = new FauxRequest();
717 $request1->getSession()->setUser( $user1Tmp );
718 $block = new Block( [ 'enableAutoblock' => true, 'expiry' => 'infinity' ] );
719 $block->setTarget( $user1Tmp );
720 $block->insert();
721 $user1 = User::newFromSession( $request1 );
722 $user1->mBlock = $block;
723 $user1->load();
724
725 // 2. Test the cookie's expiry timestamp.
726 $this->assertTrue( $user1->isLoggedIn() );
727 $this->assertTrue( $user1->isBlocked() );
728 $this->assertEquals( Block::TYPE_USER, $block->getType() );
729 $this->assertTrue( $block->isAutoblocking() );
730 $this->assertGreaterThanOrEqual( 1, $user1->getBlockId() );
731 $cookies = $request1->response()->getCookies();
732 // Test the cookie's expiry to the nearest minute.
733 $this->assertArrayHasKey( 'wm_infinite_blockBlockID', $cookies );
734 $expOneDay = wfTimestamp() + ( 24 * 60 * 60 );
735 // Check for expiry dates in a 10-second window, to account for slow testing.
736 $this->assertEquals(
737 $expOneDay,
738 $cookies['wm_infinite_blockBlockID']['expire'],
739 'Expiry date',
740 5.0
741 );
742
743 // 3. Change the block's expiry (to 2 hours), and the cookie's should be changed also.
744 $newExpiry = wfTimestamp() + 2 * 60 * 60;
745 $block->mExpiry = wfTimestamp( TS_MW, $newExpiry );
746 $block->update();
747 $user2tmp = $this->getTestUser()->getUser();
748 $request2 = new FauxRequest();
749 $request2->getSession()->setUser( $user2tmp );
750 $user2 = User::newFromSession( $request2 );
751 $user2->mBlock = $block;
752 $user2->load();
753 $cookies = $request2->response()->getCookies();
754 $this->assertEquals( wfTimestamp( TS_MW, $newExpiry ), $block->getExpiry() );
755 $this->assertEquals( $newExpiry, $cookies['wm_infinite_blockBlockID']['expire'] );
756
757 // Clean up.
758 $block->delete();
759 }
760
761 public function testSoftBlockRanges() {
762 global $wgUser;
763
764 $this->setMwGlobals( [
765 'wgSoftBlockRanges' => [ '10.0.0.0/8' ],
766 'wgUser' => null,
767 ] );
768
769 // IP isn't in $wgSoftBlockRanges
770 $request = new FauxRequest();
771 $request->setIP( '192.168.0.1' );
772 $wgUser = User::newFromSession( $request );
773 $this->assertNull( $wgUser->getBlock() );
774
775 // IP is in $wgSoftBlockRanges
776 $request = new FauxRequest();
777 $request->setIP( '10.20.30.40' );
778 $wgUser = User::newFromSession( $request );
779 $block = $wgUser->getBlock();
780 $this->assertInstanceOf( Block::class, $block );
781 $this->assertSame( 'wgSoftBlockRanges', $block->getSystemBlockType() );
782
783 // Make sure the block is really soft
784 $request->getSession()->setUser( $this->getTestUser()->getUser() );
785 $wgUser = User::newFromSession( $request );
786 $this->assertFalse( $wgUser->isAnon(), 'sanity check' );
787 $this->assertNull( $wgUser->getBlock() );
788 }
789
790 /**
791 * Test that a modified BlockID cookie doesn't actually load the relevant block (T152951).
792 */
793 public function testAutoblockCookieInauthentic() {
794 // Set up the bits of global configuration that we use.
795 $this->setMwGlobals( [
796 'wgCookieSetOnAutoblock' => true,
797 'wgCookiePrefix' => 'wmsitetitle',
798 'wgSecretKey' => MWCryptRand::generateHex( 64, true ),
799 ] );
800
801 // 1. Log in a blocked test user.
802 $user1tmp = $this->getTestUser()->getUser();
803 $request1 = new FauxRequest();
804 $request1->getSession()->setUser( $user1tmp );
805 $block = new Block( [ 'enableAutoblock' => true ] );
806 $block->setTarget( $user1tmp );
807 $block->insert();
808 $user1 = User::newFromSession( $request1 );
809 $user1->mBlock = $block;
810 $user1->load();
811
812 // 2. Create a new request, set the cookie to an invalid value, and make sure the (anon)
813 // user not blocked.
814 $request2 = new FauxRequest();
815 $request2->setCookie( 'BlockID', $block->getId() . '!zzzzzzz' );
816 $user2 = User::newFromSession( $request2 );
817 $user2->load();
818 $this->assertTrue( $user2->isAnon() );
819 $this->assertFalse( $user2->isLoggedIn() );
820 $this->assertFalse( $user2->isBlocked() );
821
822 // Clean up.
823 $block->delete();
824 }
825
826 /**
827 * The BlockID cookie is normally verified with a HMAC, but not if wgSecretKey is not set.
828 * This checks that a non-authenticated cookie still works.
829 */
830 public function testAutoblockCookieNoSecretKey() {
831 // Set up the bits of global configuration that we use.
832 $this->setMwGlobals( [
833 'wgCookieSetOnAutoblock' => true,
834 'wgCookiePrefix' => 'wmsitetitle',
835 'wgSecretKey' => null,
836 ] );
837
838 // 1. Log in a blocked test user.
839 $user1tmp = $this->getTestUser()->getUser();
840 $request1 = new FauxRequest();
841 $request1->getSession()->setUser( $user1tmp );
842 $block = new Block( [ 'enableAutoblock' => true ] );
843 $block->setTarget( $user1tmp );
844 $block->insert();
845 $user1 = User::newFromSession( $request1 );
846 $user1->mBlock = $block;
847 $user1->load();
848 $this->assertTrue( $user1->isBlocked() );
849
850 // 2. Create a new request, set the cookie to just the block ID, and the user should
851 // still get blocked when they log in again.
852 $request2 = new FauxRequest();
853 $request2->setCookie( 'BlockID', $block->getId() );
854 $user2 = User::newFromSession( $request2 );
855 $user2->load();
856 $this->assertNotEquals( $user1->getId(), $user2->getId() );
857 $this->assertNotEquals( $user1->getToken(), $user2->getToken() );
858 $this->assertTrue( $user2->isAnon() );
859 $this->assertFalse( $user2->isLoggedIn() );
860 $this->assertTrue( $user2->isBlocked() );
861 $this->assertEquals( true, $user2->getBlock()->isAutoblocking() ); // Non-strict type-check.
862
863 // Clean up.
864 $block->delete();
865 }
866
867 public function testIsPingLimitable() {
868 $request = new FauxRequest();
869 $request->setIP( '1.2.3.4' );
870 $user = User::newFromSession( $request );
871
872 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
873 $this->assertTrue( $user->isPingLimitable() );
874
875 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.4' ] );
876 $this->assertFalse( $user->isPingLimitable() );
877
878 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [ '1.2.3.0/8' ] );
879 $this->assertFalse( $user->isPingLimitable() );
880
881 $this->setMwGlobals( 'wgRateLimitsExcludedIPs', [] );
882 $noRateLimitUser = $this->getMockBuilder( User::class )->disableOriginalConstructor()
883 ->setMethods( [ 'getIP', 'getRights' ] )->getMock();
884 $noRateLimitUser->expects( $this->any() )->method( 'getIP' )->willReturn( '1.2.3.4' );
885 $noRateLimitUser->expects( $this->any() )->method( 'getRights' )->willReturn( [ 'noratelimit' ] );
886 $this->assertFalse( $noRateLimitUser->isPingLimitable() );
887 }
888
889 public function provideExperienceLevel() {
890 return [
891 [ 2, 2, 'newcomer' ],
892 [ 12, 3, 'newcomer' ],
893 [ 8, 5, 'newcomer' ],
894 [ 15, 10, 'learner' ],
895 [ 450, 20, 'learner' ],
896 [ 460, 33, 'learner' ],
897 [ 525, 28, 'learner' ],
898 [ 538, 33, 'experienced' ],
899 ];
900 }
901
902 /**
903 * @dataProvider provideExperienceLevel
904 */
905 public function testExperienceLevel( $editCount, $memberSince, $expLevel ) {
906 $this->setMwGlobals( [
907 'wgLearnerEdits' => 10,
908 'wgLearnerMemberSince' => 4,
909 'wgExperiencedUserEdits' => 500,
910 'wgExperiencedUserMemberSince' => 30,
911 ] );
912
913 $db = wfGetDB( DB_MASTER );
914
915 $data = new stdClass();
916 $data->user_id = 1;
917 $data->user_name = 'name';
918 $data->user_real_name = 'Real Name';
919 $data->user_touched = 1;
920 $data->user_token = 'token';
921 $data->user_email = 'a@a.a';
922 $data->user_email_authenticated = null;
923 $data->user_email_token = 'token';
924 $data->user_email_token_expires = null;
925 $data->user_editcount = $editCount;
926 $data->user_registration = $db->timestamp( time() - $memberSince * 86400 );
927 $user = User::newFromRow( $data );
928
929 $this->assertEquals( $expLevel, $user->getExperienceLevel() );
930 }
931
932 public function testExperienceLevelAnon() {
933 $user = User::newFromName( '10.11.12.13', false );
934
935 $this->assertFalse( $user->getExperienceLevel() );
936 }
937
938 public static function provideIsLocallBlockedProxy() {
939 return [
940 [ '1.2.3.4', '1.2.3.4' ],
941 [ '1.2.3.4', '1.2.3.0/16' ],
942 ];
943 }
944
945 /**
946 * @dataProvider provideIsLocallBlockedProxy
947 * @covers User::isLocallyBlockedProxy
948 */
949 public function testIsLocallyBlockedProxy( $ip, $blockListEntry ) {
950 $this->setMwGlobals(
951 'wgProxyList', []
952 );
953 $this->assertFalse( User::isLocallyBlockedProxy( $ip ) );
954
955 $this->setMwGlobals(
956 'wgProxyList',
957 [
958 $blockListEntry
959 ]
960 );
961 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
962
963 $this->setMwGlobals(
964 'wgProxyList',
965 [
966 'test' => $blockListEntry
967 ]
968 );
969 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
970
971 $this->hideDeprecated(
972 'IP addresses in the keys of $wgProxyList (found the following IP ' .
973 'addresses in keys: ' . $blockListEntry . ', please move them to values)'
974 );
975 $this->setMwGlobals(
976 'wgProxyList',
977 [
978 $blockListEntry => 'test'
979 ]
980 );
981 $this->assertTrue( User::isLocallyBlockedProxy( $ip ) );
982 }
983 }