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