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