Debian Codegraph @

tests/phpunit/includes/Permissions/PermissionManagerTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Integration\Permissions;
4
5 use Action;
6 use MediaWiki\Api\ApiMessage;
7 use MediaWiki\Block\BlockActionInfo;
8 use MediaWiki\Block\CompositeBlock;
9 use MediaWiki\Block\DatabaseBlock;
10 use MediaWiki\Block\Restriction\ActionRestriction;
11 use MediaWiki\Block\Restriction\NamespaceRestriction;
12 use MediaWiki\Block\Restriction\PageRestriction;
13 use MediaWiki\Block\SystemBlock;
14 use MediaWiki\Cache\CacheKeyHelper;
15 use MediaWiki\Context\RequestContext;
16 use MediaWiki\MainConfigNames;
17 use MediaWiki\Message\Message;
18 use MediaWiki\Permissions\PermissionManager;
19 use MediaWiki\Request\FauxRequest;
20 use MediaWiki\Session\SessionId;
21 use MediaWiki\Tests\Session\TestUtils;
22 use MediaWiki\Tests\Unit\MockBlockTrait;
23 use MediaWiki\Tests\User\TempUser\TempUserTestTrait;
24 use MediaWiki\Title\Title;
25 use MediaWiki\User\User;
26 use MediaWiki\User\UserIdentity;
27 use MediaWiki\User\UserIdentityValue;
28 use MediaWikiLangTestCase;
29 use stdClass;
30 use TestAllServiceOptionsUsed;
31 use Wikimedia\ScopedCallback;
32 use Wikimedia\TestingAccessWrapper;
33
34 /**
35 * For the pure unit tests, see \MediaWiki\Tests\Unit\Permissions\PermissionManagerTest.
36 *
37 * @group Database
38 * @covers \MediaWiki\Permissions\PermissionManager
39 */
40 class PermissionManagerTest extends MediaWikiLangTestCase {
41 use TestAllServiceOptionsUsed;
42 use MockBlockTrait;
43 use TempUserTestTrait;
44
45 protected string $userName;
46 protected Title $title;
47 protected User $user;
48 protected User $anonUser;
49 protected User $userUser;
50 protected User $altUser;
51
52 private const USER_TALK_PAGE = '<user talk page>';
53
54 protected function setUp(): void {
55 parent::setUp();
56
57 $localZone = 'UTC';
58 $localOffset = date( 'Z' ) / 60;
59
60 $this->overrideConfigValues( [
61 MainConfigNames::BlockDisablesLogin => false,
62 MainConfigNames::Localtimezone => $localZone,
63 MainConfigNames::LocalTZoffset => $localOffset,
64 MainConfigNames::ImplicitRights => [
65 'limitabletest'
66 ],
67 MainConfigNames::RevokePermissions => [
68 'formertesters' => [
69 'runtest' => true
70 ]
71 ],
72 MainConfigNames::AvailableRights => [
73 'test',
74 'runtest',
75 'writetest',
76 'nukeworld',
77 'modifytest',
78 'editmyoptions',
79 'editinterface',
80
81 // Interface admin
82 'editsitejs',
83 'edituserjs',
84
85 // Admin
86 'delete',
87 'undelete',
88 'deletedhistory',
89 'deletedtext',
90 ]
91 ] );
92
93 $this->setGroupPermissions( 'unittesters', 'test', true );
94 $this->setGroupPermissions( 'unittesters', 'runtest', true );
95 $this->setGroupPermissions( 'unittesters', 'writetest', false );
96 $this->setGroupPermissions( 'unittesters', 'nukeworld', false );
97
98 $this->setGroupPermissions( 'testwriters', 'test', true );
99 $this->setGroupPermissions( 'testwriters', 'writetest', true );
100 $this->setGroupPermissions( 'testwriters', 'modifytest', true );
101
102 $this->setGroupPermissions( '*', 'editmyoptions', true );
103
104 $this->setGroupPermissions( 'deleted-viewer', 'deletedhistory', true );
105 $this->setGroupPermissions( 'deleted-viewer', 'deletedtext', true );
106 $this->setGroupPermissions( 'deleted-viewer', 'viewsuppressed', true );
107
108 $this->setGroupPermissions( 'interface-admin', 'editinterface', true );
109 $this->setGroupPermissions( 'interface-admin', 'editsitejs', true );
110 $this->setGroupPermissions( 'interface-admin', 'edituserjs', true );
111 $this->setGroupPermissions( 'sysop', 'editinterface', true );
112 $this->setGroupPermissions( 'sysop', 'delete', true );
113 $this->setGroupPermissions( 'sysop', 'undelete', true );
114 $this->setGroupPermissions( 'sysop', 'deletedhistory', true );
115 $this->setGroupPermissions( 'sysop', 'deletedtext', true );
116
117 // Without this testUserBlock will use a non-English context on non-English MediaWiki
118 // installations (because of how Title::checkUserBlock is implemented) and fail.
119 RequestContext::resetMain();
120
121 $this->userName = 'Useruser';
122 $altUserName = 'Altuseruser';
123 date_default_timezone_set( $localZone );
124
125 /**
126 * TODO: We should provision title object(s) via providers not in here
127 * in order for us to avoid setting mInterwiki via reflection property.
128 */
129 $this->title = Title::makeTitle( NS_MAIN, "Main Page" );
130 if ( !isset( $this->userUser ) || !( $this->userUser instanceof User ) ) {
131 $this->userUser = User::newFromName( $this->userName );
132
133 if ( !$this->userUser->getId() ) {
134 $this->userUser = User::createNew( $this->userName, [
135 "email" => "[email protected]",
136 "real_name" => "Test User" ] );
137 $this->userUser->load();
138 }
139
140 $this->altUser = User::newFromName( $altUserName );
141 if ( !$this->altUser->getId() ) {
142 $this->altUser = User::createNew( $altUserName, [
143 "email" => "[email protected]",
144 "real_name" => "Test User Alt" ] );
145 $this->altUser->load();
146 }
147
148 $this->anonUser = User::newFromId( 0 );
149
150 $this->user = $this->userUser;
151 }
152 }
153
154 protected function setTitle( $ns, $title = "Main_Page" ) {
155 $this->title = Title::makeTitle( $ns, $title );
156 }
157
158 protected function setUser( $userName = null ) {
159 if ( $userName === 'anon' ) {
160 $this->user = $this->anonUser;
161 } elseif ( $userName === null || $userName === $this->userName ) {
162 $this->user = $this->userUser;
163 } else {
164 $this->user = $this->altUser;
165 }
166 }
167
168 /**
169 * @dataProvider provideSpecialsAndNSPermissions
170 */
171 public function testSpecialsAndNSPermissions(
172 $namespace,
173 $userPerms,
174 $namespaceProtection,
175 $expectedPermErrors,
176 $expectedUserCan
177 ) {
178 $this->setUser( $this->userName );
179 $this->setTitle( $namespace );
180
181 $this->mergeMwGlobalArrayValue( 'wgNamespaceProtection', $namespaceProtection );
182 $this->overrideConfigValue(
183 MainConfigNames::NamespaceProtection,
184 $namespaceProtection + [ NS_MEDIAWIKI => 'editinterface' ]
185 );
186
187 $permissionManager = $this->getServiceContainer()->getPermissionManager();
188
189 $this->overrideUserPermissions( $this->user, $userPerms );
190
191 $this->assertEquals(
192 $expectedPermErrors,
193 $permissionManager->getPermissionErrors( 'bogus', $this->user, $this->title )
194 );
195 $this->assertSame(
196 $expectedUserCan,
197 $permissionManager->userCan( 'bogus', $this->user, $this->title )
198 );
199 }
200
201 public static function provideSpecialsAndNSPermissions() {
202 yield [
203 'namespace' => NS_SPECIAL,
204 'user permissions' => [],
205 'namespace protection' => [],
206 'expected permission errors' => [ [ 'badaccess-group0' ], [ 'ns-specialprotected' ] ],
207 'user can' => false,
208 ];
209 yield [
210 'namespace' => NS_MAIN,
211 'user permissions' => [ 'bogus' ],
212 'namespace protection' => [],
213 'expected permission errors' => [],
214 'user can' => true,
215 ];
216 yield [
217 'namespace' => NS_MAIN,
218 'user permissions' => [],
219 'namespace protection' => [],
220 'expected permission errors' => [ [ 'badaccess-group0' ] ],
221 'user can' => false,
222 ];
223 yield [
224 'namespace' => NS_USER,
225 'user permissions' => [],
226 'namespace protection' => [ NS_USER => [ 'bogus' ] ],
227 'expected permission errors' => [ [ 'badaccess-group0' ], [ 'namespaceprotected', 'User', 'bogus' ] ],
228 'user can' => false,
229 ];
230 yield [
231 'namespace' => NS_MEDIAWIKI,
232 'user permissions' => [ 'bogus' ],
233 'namespace protection' => [],
234 'expected permission errors' => [ [ 'protectedinterface', 'bogus' ] ],
235 'user can' => false,
236 ];
237 yield [
238 'namespace' => NS_MAIN,
239 'user permissions' => [ 'bogus' ],
240 'namespace protection' => [],
241 'expected permission errors' => [],
242 'user can' => true,
243 ];
244 }
245
246 public function testCascadingSourcesRestrictions() {
247 $this->setTitle( NS_MAIN, "Test page" );
248 $this->overrideUserPermissions( $this->user, [ "edit", "bogus", 'createpage' ] );
249
250 $rs = $this->getServiceContainer()->getRestrictionStore();
251 $wrapper = TestingAccessWrapper::newFromObject( $rs );
252 $wrapper->cache = [ CacheKeyHelper::getKeyForPage( $this->title ) => [
253 'cascade_sources' => [
254 [
255 Title::makeTitle( NS_MAIN, "Bogus" ),
256 Title::makeTitle( NS_MAIN, "UnBogus" )
257 ],
258 [
259 "bogus" => [ 'bogus', "sysop", "protect", "" ],
260 ],
261 [
262 Title::makeTitle( NS_MAIN, "Bogus" ),
263 Title::makeTitle( NS_MAIN, "UnBogus" )
264 ],
265 []
266 ],
267 ] ];
268
269 $permissionManager = $this->getServiceContainer()->getPermissionManager();
270
271 $this->assertFalse( $permissionManager->userCan( 'bogus', $this->user, $this->title ) );
272 $this->assertEquals( [
273 [ "cascadeprotected", 2, "* [[:Bogus]]\n* [[:UnBogus]]\n", 'bogus' ] ],
274 $permissionManager->getPermissionErrors(
275 'bogus', $this->user, $this->title ) );
276
277 $this->assertTrue( $permissionManager->userCan( 'edit', $this->user, $this->title ) );
278 $this->assertEquals(
279 [],
280 $permissionManager->getPermissionErrors( 'edit', $this->user, $this->title )
281 );
282 }
283
284 public function testCascadingSourcesRestrictionsForFile() {
285 $this->setTitle( NS_FILE, 'Test.jpg' );
286 $this->overrideUserPermissions( $this->user, [ 'edit', 'move', 'upload', 'movefile', 'createpage' ] );
287
288 $rs = $this->getServiceContainer()->getRestrictionStore();
289 $wrapper = TestingAccessWrapper::newFromObject( $rs );
290 $wrapper->cache = [ CacheKeyHelper::getKeyForPage( $this->title ) => [
291 'cascade_sources' => [
292 [
293 Title::makeTitle( NS_MAIN, 'FileTemplate' ),
294 Title::makeTitle( NS_MAIN, 'FileUser' )
295 ],
296 [
297 'edit' => [ 'sysop' ],
298 ],
299 [
300 Title::makeTitle( NS_MAIN, 'FileTemplate' )
301 ],
302 [
303 Title::makeTitle( NS_MAIN, 'FileUser' )
304 ]
305 ],
306 ] ];
307
308 $permissionManager = $this->getServiceContainer()->getPermissionManager();
309
310 $this->assertFalse( $permissionManager->userCan( 'upload', $this->user, $this->title ) );
311 $this->assertEquals( [
312 [ 'cascadeprotected', 2, "* [[:FileTemplate]]\n* [[:FileUser]]\n", 'upload' ] ],
313 $permissionManager->getPermissionErrors( 'upload', $this->user, $this->title )
314 );
315
316 $this->assertFalse( $permissionManager->userCan( 'move', $this->user, $this->title ) );
317 $this->assertEquals( [
318 [ 'cascadeprotected', 2, "* [[:FileTemplate]]\n* [[:FileUser]]\n", 'move' ] ],
319 $permissionManager->getPermissionErrors( 'move', $this->user, $this->title )
320 );
321
322 $this->assertFalse( $permissionManager->userCan( 'edit', $this->user, $this->title ) );
323 $this->assertEquals( [
324 [ 'cascadeprotected', 2, "* [[:FileTemplate]]\n* [[:FileUser]]\n", 'edit' ] ],
325 $permissionManager->getPermissionErrors( 'edit', $this->user, $this->title )
326 );
327 }
328
329 /**
330 * @dataProvider provideActionPermissions
331 */
332 public function testActionPermissions(
333 $namespace,
334 $titleOverrides,
335 $action,
336 $userPerms,
337 $expectedPermErrors,
338 $expectedUserCan
339 ) {
340 $this->setTitle( $namespace, "Test page" );
341
342 $this->overrideUserPermissions( $this->user, $userPerms );
343
344 $permissionManager = $this->getServiceContainer()->getPermissionManager();
345
346 $rs = $this->getServiceContainer()->getRestrictionStore();
347 $wrapper = TestingAccessWrapper::newFromObject( $rs );
348 $wrapper->cache = [ CacheKeyHelper::getKeyForPage( $this->title ) => [
349 'create_protection' => [
350 'permission' => $titleOverrides['protectedPermission'] ?? '',
351 'user' => $this->user->getId(),
352 'expiry' => 'infinity',
353 'reason' => 'test',
354 ],
355 'has_cascading' => false,
356 // XXX This is bogus, restrictions won't be empty if there's create protection
357 'restrictions' => [],
358 ] ];
359
360 if ( isset( $titleOverrides['interwiki'] ) ) {
361 $reflectedTitle = TestingAccessWrapper::newFromObject( $this->title );
362 $reflectedTitle->mInterwiki = $titleOverrides['interwiki'];
363 }
364
365 $this->assertEquals(
366 $expectedPermErrors,
367 $permissionManager->getPermissionErrors( $action, $this->user, $this->title )
368 );
369 $this->assertSame(
370 $expectedUserCan,
371 $permissionManager->userCan( $action, $this->user, $this->title )
372 );
373 }
374
375 public static function provideActionPermissions() {
376 // title overrides can include "protectedPermission" to override
377 // $title->mTitleProtection['permission'], and "interwiki" to override
378 // $title->mInterwiki, for the few cases those are needed
379 yield [
380 'namespace' => NS_MAIN,
381 'title overrides' => [],
382 'action' => 'create',
383 'user permissions' => [ 'createpage' ],
384 'expected permission errors' => [ [ 'titleprotected', 'Useruser', 'test' ] ],
385 'user can' => false,
386 ];
387 yield [
388 'namespace' => NS_MAIN,
389 'title overrides' => [ 'protectedPermission' => 'editprotected' ],
390 'action' => 'create',
391 'user permissions' => [ 'createpage', 'protect' ],
392 'expected permission errors' => [ [ 'titleprotected', 'Useruser', 'test' ] ],
393 'user can' => false,
394 ];
395 yield [
396 'namespace' => NS_MAIN,
397 'title overrides' => [ 'protectedPermission' => 'editprotected' ],
398 'action' => 'create',
399 'user permissions' => [ 'createpage', 'editprotected' ],
400 'expected permission errors' => [],
401 'user can' => true,
402 ];
403 yield [
404 'namespace' => NS_MEDIA,
405 'title overrides' => [],
406 'action' => 'move',
407 'user permissions' => [ 'move' ],
408 'expected permission errors' => [ [ 'immobile-source-namespace', 'Media' ] ],
409 'user can' => false,
410 ];
411 yield [
412 'namespace' => NS_HELP,
413 'title overrides' => [],
414 'action' => 'move',
415 'user permissions' => [ 'move' ],
416 'expected permission errors' => [],
417 'user can' => true,
418 ];
419 yield [
420 'namespace' => NS_HELP,
421 'title overrides' => [ 'interwiki' => 'no' ],
422 'action' => 'move',
423 'user permissions' => [ 'move' ],
424 'expected permission errors' => [ [ 'immobile-source-page' ] ],
425 'user can' => false,
426 ];
427 yield [
428 'namespace' => NS_MEDIA,
429 'title overrides' => [],
430 'action' => 'move-target',
431 'user permissions' => [ 'move' ],
432 'expected permission errors' => [ [ 'immobile-target-namespace', 'Media' ] ],
433 'user can' => false,
434 ];
435 yield [
436 'namespace' => NS_HELP,
437 'title overrides' => [],
438 'action' => 'move-target',
439 'user permissions' => [ 'move' ],
440 'expected permission errors' => [],
441 'user can' => true,
442 ];
443 yield [
444 'namespace' => NS_HELP,
445 'title overrides' => [ 'interwiki' => 'no' ],
446 'action' => 'move-target',
447 'user permissions' => [ 'move' ],
448 'expected permission errors' => [ [ 'immobile-target-page' ] ],
449 'user can' => false,
450 ];
451 yield [
452 'namespace' => NS_MAIN,
453 'title overrides' => [],
454 'action' => 'edit',
455 'user permissions' => [ 'createpage', 'edit' ],
456 'expected permission errors' => [ [ 'titleprotected', 'Useruser', 'test' ] ],
457 'user can' => false,
458 ];
459 yield [
460 'namespace' => NS_MAIN,
461 'title overrides' => [],
462 'action' => 'edit',
463 'user permissions' => [ 'edit' ],
464 'expected permission errors' => [ [ 'nocreate-loggedin' ] ],
465 'user can' => false,
466 ];
467 }
468
469 public function testEditActionPermissionWithExistingPage() {
470 $title = $this->getExistingTestPage( 'test page' )->getTitle();
471
472 $permissionManager = $this->getServiceContainer()->getPermissionManager();
473
474 $this->overrideUserPermissions( $this->user, [ 'edit' ] );
475
476 $this->assertSame( [], $permissionManager->getPermissionErrors( 'edit', $this->user, $title ) );
477 $this->assertTrue( $permissionManager->userCan( 'edit', $this->user, $title ) );
478 }
479
480 public function testAutocreatePermissionsHack() {
481 $this->enableAutoCreateTempUser();
482 $this->overrideConfigValue( MainConfigNames::GroupPermissions, [
483 '*' => [ 'edit' => false ],
484 'temp' => [ 'edit' => true, 'createpage' => true ],
485 ] );
486 $services = $this->getServiceContainer();
487 $permissionManager = $services->getPermissionManager();
488 $user = $services->getUserFactory()->newAnonymous();
489 $title = $this->getNonexistingTestPage()->getTitle();
490 $this->assertNotEmpty(
491 $permissionManager->getPermissionErrors(
492 'edit',
493 $user,
494 $title
495 )
496 );
497 $this->assertSame(
498 [],
499 $permissionManager->getPermissionErrors(
500 'edit',
501 $user,
502 $title,
503 PermissionManager::RIGOR_QUICK
504 )
505 );
506 }
507
508 /**
509 * @dataProvider provideTestCheckUserBlockActions
510 */
511 public function testCheckUserBlockActions( $block, $restriction, $expected ) {
512 $this->overrideConfigValues( [
513 MainConfigNames::EmailConfirmToEdit => false,
514 MainConfigNames::EnablePartialActionBlocks => true,
515 ] );
516
517 if ( $restriction ) {
518 $pageRestriction = new PageRestriction( 0, $this->title->getArticleID() );
519 $pageRestriction->setTitle( $this->title );
520 $block->setRestrictions( [ $pageRestriction ] );
521 }
522
523 $user = $this->createUserWithBlock( $block );
524
525 $this->overrideUserPermissions( $user, [
526 'createpage',
527 'edit',
528 'move',
529 'rollback',
530 'patrol',
531 'upload',
532 'purge'
533 ] );
534
535 $permissionManager = $this->getServiceContainer()->getPermissionManager();
536
537 // Check that user is blocked or unblocked from specific actions using getPermissionErrors
538 foreach ( $expected as $action => $blocked ) {
539 $expectedErrorCount = $blocked ? 1 : 0;
540 $this->assertCount(
541 $expectedErrorCount,
542 $permissionManager->getPermissionErrors(
543 $action,
544 $user,
545 $this->title
546 ),
547 "Number of permission errors for action \"$action\""
548 );
549 }
550
551 // Check that user is blocked or unblocked from specific actions using getApplicableBlock
552 foreach ( $expected as $action => $blocked ) {
553 $this->assertSame(
554 $blocked,
555 $permissionManager->getApplicableBlock(
556 $action,
557 $user,
558 PermissionManager::RIGOR_FULL,
559 $this->title,
560 null
561 ) !== null,
562 "Block returned by getApplicableBlock() for action \"$action\""
563 );
564 }
565
566 // quickUserCan should ignore user blocks
567 $this->assertTrue(
568 $permissionManager->quickUserCan( 'move-target', $this->user, $this->title )
569 );
570 }
571
572 /**
573 * Create a user that is blocked in global state
574 *
575 * @param array $options $block
576 * @return User
577 */
578 private function createUserWithBlock( $options = [] ) {
579 $newUser = new User();
580 $newUser->setId( 12345 );
581 $newUser->setName( 'BlockedUser' );
582
583 $this->installMockBlockManager( $options, $newUser );
584 return $newUser;
585 }
586
587 /**
588 * Regression test for T348451
589 */
590 public function testGetApplicableBlockForSpecialPage() {
591 $block = new DatabaseBlock( [
592 'address' => '127.0.8.1',
593 'by' => new UserIdentityValue( 100, 'TestUser' ),
594 'auto' => true,
595 ] );
596
597 $user = $this->createUserWithBlock( $block );
598 $title = Title::makeTitle( NS_SPECIAL, 'Blankpage' );
599
600 $this->overrideUserPermissions( $user, [
601 'createpage',
602 'edit',
603 ] );
604
605 $permissionManager = $this->getServiceContainer()->getPermissionManager();
606
607 // The block is applicable even if the target page is a special page
608 // for which we cannot instantiate an Action object.
609 $this->assertSame(
610 $block,
611 $permissionManager->getApplicableBlock(
612 'edit',
613 $user,
614 PermissionManager::RIGOR_FULL,
615 $title,
616 null
617 )
618 );
619 }
620
621 /**
622 * Regression test for T350202
623 */
624 public function testGetApplicableBlockForImplicitRight() {
625 $block = new DatabaseBlock( [
626 'address' => '127.0.8.1',
627 'by' => new UserIdentityValue( 100, 'TestUser' ),
628 'auto' => true,
629 ] );
630
631 $user = $this->createUserWithBlock( $block );
632 $title = Title::makeTitle( NS_MAIN, 'Test' );
633
634 $permissionManager = $this->getServiceContainer()->getPermissionManager();
635
636 // The block is not applicable because the purge permission is implicit.
637 $this->assertNull(
638 $permissionManager->getApplicableBlock(
639 'purge',
640 $user,
641 PermissionManager::RIGOR_FULL,
642 $title,
643 null
644 )
645 );
646 }
647
648 public static function provideTestCheckUserBlockActions() {
649 return [
650 'Sitewide autoblock' => [
651 new DatabaseBlock( [
652 'address' => '127.0.8.1',
653 'by' => new UserIdentityValue( 100, 'TestUser' ),
654 'auto' => true,
655 ] ),
656 false,
657 [
658 'edit' => true,
659 'move-target' => true,
660 'rollback' => true,
661 'patrol' => true,
662 'upload' => true,
663 'purge' => false,
664 ]
665 ],
666 'Sitewide block' => [
667 new DatabaseBlock( [
668 'address' => '127.0.8.1',
669 'by' => new UserIdentityValue( 100, 'TestUser' ),
670 ] ),
671 false,
672 [
673 'edit' => true,
674 'move-target' => true,
675 'rollback' => true,
676 'patrol' => true,
677 'upload' => true,
678 'purge' => false,
679 ]
680 ],
681 'Partial block without restriction against this page' => [
682 new DatabaseBlock( [
683 'address' => '127.0.8.1',
684 'by' => new UserIdentityValue( 100, 'TestUser' ),
685 'sitewide' => false,
686 ] ),
687 false,
688 [
689 'edit' => false,
690 'move-target' => false,
691 'rollback' => false,
692 'patrol' => false,
693 'upload' => false,
694 'purge' => false,
695 ]
696 ],
697 'Partial block with restriction against this page' => [
698 new DatabaseBlock( [
699 'address' => '127.0.8.1',
700 'by' => new UserIdentityValue( 100, 'TestUser' ),
701 'sitewide' => false,
702 ] ),
703 true,
704 [
705 'edit' => true,
706 'move-target' => true,
707 'rollback' => true,
708 'patrol' => true,
709 'upload' => false,
710 'purge' => false,
711 ]
712 ],
713 'Partial block with action restriction against uploading' => [
714 ( new DatabaseBlock( [
715 'address' => '127.0.8.1',
716 'by' => UserIdentityValue::newRegistered( 100, 'Test' ),
717 'sitewide' => false,
718 ] ) )->setRestrictions( [
719 new ActionRestriction( 0, BlockActionInfo::ACTION_UPLOAD )
720 ] ),
721 false,
722 [
723 'edit' => false,
724 'move-target' => false,
725 'rollback' => false,
726 'patrol' => false,
727 'upload' => true,
728 'purge' => false,
729 ]
730 ],
731 'System block' => [
732 new SystemBlock( [
733 'address' => '127.0.8.1',
734 'by' => 100,
735 'systemBlock' => 'test',
736 ] ),
737 false,
738 [
739 'edit' => true,
740 'move-target' => true,
741 'rollback' => true,
742 'patrol' => true,
743 'upload' => true,
744 'purge' => false,
745 ]
746 ],
747 'No block' => [
748 null,
749 false,
750 [
751 'edit' => false,
752 'move-target' => false,
753 'rollback' => false,
754 'patrol' => false,
755 'upload' => false,
756 'purge' => false,
757 ]
758 ]
759 ];
760 }
761
762 /**
763 * A test of the filter() calls in getApplicableBlock()
764 */
765 public function testGetApplicableBlockCompositeFilter() {
766 $this->overrideConfigValues( [
767 MainConfigNames::EnablePartialActionBlocks => true,
768 ] );
769 $blockOptions = [
770 'address' => '127.0.8.1',
771 'by' => UserIdentityValue::newRegistered( 100, 'Test' ),
772 'sitewide' => false,
773 ];
774
775 $uploadBlock = new DatabaseBlock( $blockOptions );
776 $uploadBlock->setRestrictions( [
777 new ActionRestriction( 0, BlockActionInfo::ACTION_UPLOAD )
778 ] );
779
780 $emailBlock = new DatabaseBlock(
781 [
782 'blockEmail' => true,
783 'sitewide' => true
784 ] + $blockOptions
785 );
786
787 $page = $this->getExistingTestPage();
788 $page2 = $this->getExistingTestPage( __FUNCTION__ . ' page2' );
789 $pageBlock = new DatabaseBlock( $blockOptions );
790 $pageBlock->setRestrictions( [
791 new PageRestriction( 0, $page->getId() )
792 ] );
793
794 $compositeBlock = new CompositeBlock( [
795 'originalBlocks' => [
796 $uploadBlock,
797 $emailBlock,
798 $pageBlock
799 ]
800 ] );
801 $user = $this->createUserWithBlock( $compositeBlock );
802 $permissionManager = $this->getServiceContainer()->getPermissionManager();
803
804 // The email block, being a sitewide block with an additional
805 // blockEmail option, also blocks upload.
806 // assertEquals() gives nicer failure messages than assertSame().
807 $this->assertEquals(
808 [ $uploadBlock, $emailBlock ],
809 $permissionManager->getApplicableBlock(
810 'upload', $user, PermissionManager::RIGOR_FULL, null, null
811 )->toArray()
812 );
813
814 // Emailing is only blocked by the email block
815 $this->assertEquals(
816 [ $emailBlock ],
817 $permissionManager->getApplicableBlock(
818 'sendemail', $user, PermissionManager::RIGOR_FULL, null, null
819 )->toArray()
820 );
821
822 // As for upload, the email block applies to sitewide editing
823 $this->assertEquals(
824 [ $emailBlock, $pageBlock ],
825 $permissionManager->getApplicableBlock(
826 'edit', $user, PermissionManager::RIGOR_FULL, $page->getTitle(), null
827 )->toArray()
828 );
829
830 // Test filtering by page -- we use $page2 so $pageBlock does not apply
831 $this->assertEquals(
832 [ $emailBlock ],
833 $permissionManager->getApplicableBlock(
834 'edit', $user, PermissionManager::RIGOR_FULL, $page2->getTitle(), null
835 )->toArray()
836 );
837 }
838
839 /**
840 * @dataProvider provideTestCheckUserBlockMessage
841 */
842 public function testCheckUserBlockMessage( $blockType, $blockParams, $restriction, $expected ) {
843 $this->overrideConfigValue(
844 MainConfigNames::EmailConfirmToEdit, false
845 );
846 $block = new $blockType( array_merge( [
847 'address' => '127.0.8.1',
848 'by' => $this->user,
849 'reason' => 'Test reason',
850 'timestamp' => '20000101000000',
851 'expiry' => 0,
852 ], $blockParams ) );
853
854 if ( $restriction ) {
855 $pageRestriction = new PageRestriction( 0, $this->title->getArticleID() );
856 $pageRestriction->setTitle( $this->title );
857 $block->setRestrictions( [ $pageRestriction ] );
858 }
859
860 $user = $this->createUserWithBlock( $block );
861 $this->overrideUserPermissions( $user, [ 'edit', 'createpage' ] );
862
863 $permissionManager = $this->getServiceContainer()->getPermissionManager();
864 $errors = $permissionManager->getPermissionErrors(
865 'edit',
866 $user,
867 $this->title
868 );
869
870 $this->assertEquals(
871 $expected['message'],
872 $errors[0][0]
873 );
874 }
875
876 public static function provideTestCheckUserBlockMessage() {
877 return [
878 'Sitewide autoblock' => [
879 DatabaseBlock::class,
880 [ 'auto' => true ],
881 false,
882 [
883 'message' => 'autoblockedtext',
884 ],
885 ],
886 'Sitewide block' => [
887 DatabaseBlock::class,
888 [],
889 false,
890 [
891 'message' => 'blockedtext',
892 ],
893 ],
894 'Partial block with restriction against this page' => [
895 DatabaseBlock::class,
896 [ 'sitewide' => false ],
897 true,
898 [
899 'message' => 'blockedtext-partial',
900 ],
901 ],
902 'System block' => [
903 SystemBlock::class,
904 [ 'systemBlock' => 'test' ],
905 false,
906 [
907 'message' => 'systemblockedtext',
908 ],
909 ],
910 ];
911 }
912
913 /**
914 * @dataProvider provideTestCheckUserBlockEmailConfirmToEdit
915 */
916 public function testCheckUserBlockEmailConfirmToEdit( $emailConfirmToEdit, $assertion ) {
917 $this->overrideConfigValues( [
918 MainConfigNames::EmailConfirmToEdit => $emailConfirmToEdit,
919 MainConfigNames::EmailAuthentication => true,
920 ] );
921
922 $this->overrideUserPermissions( $this->user, [
923 'edit',
924 'move',
925 ] );
926
927 $permissionManager = $this->getServiceContainer()->getPermissionManager();
928
929 $this->$assertion( [ 'confirmedittext' ],
930 $permissionManager->getPermissionErrors( 'edit', $this->user, $this->title ) );
931
932 // $wgEmailConfirmToEdit only applies to 'edit' action
933 $this->assertEquals( [],
934 $permissionManager->getPermissionErrors( 'move-target', $this->user, $this->title ) );
935 }
936
937 public static function provideTestCheckUserBlockEmailConfirmToEdit() {
938 return [
939 'User must confirm email to edit' => [
940 true,
941 'assertContains',
942 ],
943 'User may edit without confirming email' => [
944 false,
945 'assertNotContains',
946 ],
947 ];
948 }
949
950 /**
951 * Determine that the passed-in permission does not get mixed up with
952 * an action of the same name.
953 */
954 public function testCheckUserBlockActionPermission() {
955 $tester = $this->createMock( Action::class );
956 $tester->method( 'getName' )
957 ->willReturn( 'tester' );
958 $tester->method( 'getRestriction' )
959 ->willReturn( 'test' );
960 $tester->method( 'requiresUnblock' )
961 ->willReturn( false );
962 $tester->method( 'requiresWrite' )
963 ->willReturn( false );
964 $tester->method( 'needsReadRights' )
965 ->willReturn( false );
966
967 $this->overrideConfigValues( [
968 MainConfigNames::Actions => [
969 'tester' => $tester,
970 ],
971 MainConfigNames::GroupPermissions => [
972 '*' => [
973 'tester' => true,
974 ],
975 ],
976 ] );
977
978 $user = $this->createUserWithBlock( new DatabaseBlock( [
979 'address' => '127.0.8.1',
980 'by' => $this->user,
981 ] ) );
982 $this->assertCount( 1, $this->getServiceContainer()->getPermissionManager()
983 ->getPermissionErrors( 'tester', $user, $this->title )
984 );
985 }
986
987 public function testBlockInstanceCache() {
988 // First, check the user isn't blocked
989 $user = $this->getMutableTestUser()->getUser();
990 $ut = Title::makeTitle( NS_USER_TALK, $user->getName() );
991 $this->assertNull( $user->getBlock( false ) );
992 $this->assertFalse( $this->getServiceContainer()->getPermissionManager()
993 ->isBlockedFrom( $user, $ut ) );
994
995 // Block the user
996 $blocker = $this->getTestSysop()->getUser();
997 $block = new DatabaseBlock( [
998 'hideName' => true,
999 'allowUsertalk' => false,
1000 'reason' => 'Because',
1001 ] );
1002 $block->setTarget( $user );
1003 $block->setBlocker( $blocker );
1004 $blockStore = $this->getServiceContainer()->getDatabaseBlockStore();
1005 $res = $blockStore->insertBlock( $block );
1006 $this->assertTrue( (bool)$res['id'], 'Failed to insert block' );
1007
1008 // Clear cache and confirm it loaded the block properly
1009 $user->clearInstanceCache();
1010 $this->assertInstanceOf( DatabaseBlock::class, $user->getBlock( false ) );
1011 $this->assertTrue( $this->getServiceContainer()->getPermissionManager()
1012 ->isBlockedFrom( $user, $ut ) );
1013
1014 // Unblock
1015 $blockStore->deleteBlock( $block );
1016
1017 // Clear cache and confirm it loaded the not-blocked properly
1018 $user->clearInstanceCache();
1019 $this->assertNull( $user->getBlock( false ) );
1020 $this->assertFalse( $this->getServiceContainer()->getPermissionManager()
1021 ->isBlockedFrom( $user, $ut ) );
1022 }
1023
1024 /**
1025 * @dataProvider provideIsBlockedFrom
1026 * @param string|null $title Title to test.
1027 * @param bool $expect Expected result from User::isBlockedFrom()
1028 * @param array $options Additional test options:
1029 * - 'blockAllowsUTEdit': (bool, default true) Value for $wgBlockAllowsUTEdit
1030 * - 'allowUsertalk': (bool, default false) Passed to DatabaseBlock::__construct()
1031 * - 'pageRestrictions': (array|null) If non-empty, page restriction titles for the block.
1032 */
1033 public function testIsBlockedFrom( $title, $expect, array $options = [] ) {
1034 $this->overrideConfigValue(
1035 MainConfigNames::BlockAllowsUTEdit,
1036 $options['blockAllowsUTEdit'] ?? true
1037 );
1038
1039 $user = $this->getTestUser()->getUser();
1040
1041 if ( $title === self::USER_TALK_PAGE ) {
1042 $title = $user->getTalkPage();
1043 } else {
1044 $title = Title::newFromText( $title );
1045 }
1046
1047 $restrictions = [];
1048 foreach ( $options['pageRestrictions'] ?? [] as $pagestr ) {
1049 $page = $this->getExistingTestPage(
1050 $pagestr === self::USER_TALK_PAGE ? $user->getTalkPage() : $pagestr
1051 );
1052 $restrictions[] = new PageRestriction( 0, $page->getId() );
1053 }
1054 foreach ( $options['namespaceRestrictions'] ?? [] as $ns ) {
1055 $restrictions[] = new NamespaceRestriction( 0, $ns );
1056 }
1057
1058 $block = new DatabaseBlock( [
1059 'expiry' => wfTimestamp( TS_MW, wfTimestamp() + ( 40 * 60 * 60 ) ),
1060 'allowUsertalk' => $options['allowUsertalk'] ?? false,
1061 'sitewide' => !$restrictions,
1062 ] );
1063 $block->setTarget( $user );
1064 $block->setBlocker( $this->getTestSysop()->getUser() );
1065 if ( $restrictions ) {
1066 $block->setRestrictions( $restrictions );
1067 }
1068 $blockStore = $this->getServiceContainer()->getDatabaseBlockStore();
1069 $blockStore->insertBlock( $block );
1070
1071 $this->assertSame( $expect, $this->getServiceContainer()->getPermissionManager()
1072 ->isBlockedFrom( $user, $title ) );
1073 }
1074
1075 public static function provideIsBlockedFrom() {
1076 return [
1077 'Sitewide block, basic operation' => [ 'Test page', true ],
1078 'Sitewide block, not allowing user talk' => [
1079 self::USER_TALK_PAGE, true, [
1080 'allowUsertalk' => false,
1081 ]
1082 ],
1083 'Sitewide block, allowing user talk' => [
1084 self::USER_TALK_PAGE, false, [
1085 'allowUsertalk' => true,
1086 ]
1087 ],
1088 'Sitewide block, allowing user talk but $wgBlockAllowsUTEdit is false' => [
1089 self::USER_TALK_PAGE, true, [
1090 'allowUsertalk' => true,
1091 'blockAllowsUTEdit' => false,
1092 ]
1093 ],
1094 'Partial block, blocking the page' => [
1095 'Test page', true, [
1096 'pageRestrictions' => [ 'Test page' ],
1097 ]
1098 ],
1099 'Partial block, not blocking the page' => [
1100 'Test page 2', false, [
1101 'pageRestrictions' => [ 'Test page' ],
1102 ]
1103 ],
1104 'Partial block, not allowing user talk but user talk page is not blocked' => [
1105 self::USER_TALK_PAGE, false, [
1106 'allowUsertalk' => false,
1107 'pageRestrictions' => [ 'Test page' ],
1108 ]
1109 ],
1110 'Partial block, allowing user talk but user talk page is blocked' => [
1111 self::USER_TALK_PAGE, true, [
1112 'allowUsertalk' => true,
1113 'pageRestrictions' => [ self::USER_TALK_PAGE ],
1114 ]
1115 ],
1116 'Partial block, user talk page is not blocked but $wgBlockAllowsUTEdit is false' => [
1117 self::USER_TALK_PAGE, false, [
1118 'allowUsertalk' => false,
1119 'pageRestrictions' => [ 'Test page' ],
1120 'blockAllowsUTEdit' => false,
1121 ]
1122 ],
1123 'Partial block, user talk page is blocked and $wgBlockAllowsUTEdit is false' => [
1124 self::USER_TALK_PAGE, true, [
1125 'allowUsertalk' => true,
1126 'pageRestrictions' => [ self::USER_TALK_PAGE ],
1127 'blockAllowsUTEdit' => false,
1128 ]
1129 ],
1130 'Partial user talk namespace block, not allowing user talk' => [
1131 self::USER_TALK_PAGE, true, [
1132 'allowUsertalk' => false,
1133 'namespaceRestrictions' => [ NS_USER_TALK ],
1134 ]
1135 ],
1136 'Partial user talk namespace block, allowing user talk' => [
1137 self::USER_TALK_PAGE, false, [
1138 'allowUsertalk' => true,
1139 'namespaceRestrictions' => [ NS_USER_TALK ],
1140 ]
1141 ],
1142 'Partial user talk namespace block, where $wgBlockAllowsUTEdit is false' => [
1143 self::USER_TALK_PAGE, true, [
1144 'allowUsertalk' => true,
1145 'namespaceRestrictions' => [ NS_USER_TALK ],
1146 'blockAllowsUTEdit' => false,
1147 ]
1148 ],
1149 ];
1150 }
1151
1152 public function testGetUserPermissions() {
1153 $user = $this->getTestUser( [ 'unittesters' ] )->getUser();
1154 $rights = $this->getServiceContainer()->getPermissionManager()
1155 ->getUserPermissions( $user );
1156 $this->assertContains( 'runtest', $rights );
1157 $this->assertNotContains( 'writetest', $rights );
1158 $this->assertNotContains( 'modifytest', $rights );
1159 $this->assertNotContains( 'nukeworld', $rights );
1160 }
1161
1162 public function testGetUserPermissionsHooks() {
1163 $user = $this->getTestUser( [ 'unittesters', 'testwriters' ] )->getUser();
1164 $userWrapper = TestingAccessWrapper::newFromObject( $user );
1165
1166 $permissionManager = $this->getServiceContainer()->getPermissionManager();
1167 $rights = $permissionManager->getUserPermissions( $user );
1168 $this->assertContains( 'test', $rights );
1169 $this->assertContains( 'runtest', $rights );
1170 $this->assertContains( 'writetest', $rights );
1171 $this->assertNotContains( 'nukeworld', $rights );
1172
1173 // Add a hook manipluating the rights
1174 $this->setTemporaryHook( 'UserGetRights', static function ( $user, &$rights ) {
1175 $rights[] = 'nukeworld';
1176 $rights = array_diff( $rights, [ 'writetest' ] );
1177 } );
1178
1179 $permissionManager->invalidateUsersRightsCache( $user );
1180 $rights = $permissionManager->getUserPermissions( $user );
1181 $this->assertContains( 'test', $rights );
1182 $this->assertContains( 'runtest', $rights );
1183 $this->assertNotContains( 'writetest', $rights );
1184 $this->assertContains( 'nukeworld', $rights );
1185
1186 // Add a Session that limits rights. We're mocking a stdClass because the Session
1187 // class is final, and thus not mockable.
1188 $mock = $this->getMockBuilder( stdClass::class )
1189 ->addMethods( [ 'getAllowedUserRights', 'deregisterSession', 'getSessionId' ] )
1190 ->getMock();
1191 $mock->method( 'getAllowedUserRights' )->willReturn( [ 'test', 'writetest' ] );
1192 $mock->method( 'getSessionId' )->willReturn(
1193 new SessionId( str_repeat( 'X', 32 ) )
1194 );
1195 $session = TestUtils::getDummySession( $mock );
1196 $mockRequest = $this->getMockBuilder( FauxRequest::class )
1197 ->onlyMethods( [ 'getSession' ] )
1198 ->getMock();
1199 $mockRequest->method( 'getSession' )->willReturn( $session );
1200 $userWrapper->mRequest = $mockRequest;
1201
1202 $this->resetServices();
1203 $rights = $this->getServiceContainer()
1204 ->getPermissionManager()
1205 ->getUserPermissions( $user );
1206 $this->assertContains( 'test', $rights );
1207 $this->assertNotContains( 'runtest', $rights );
1208 $this->assertNotContains( 'writetest', $rights );
1209 $this->assertNotContains( 'nukeworld', $rights );
1210 }
1211
1212 public function testUserHasRight() {
1213 $permissionManager = $this->getServiceContainer()->getPermissionManager();
1214
1215 $result = $permissionManager->userHasRight(
1216 $this->getTestUser( 'unittesters' )->getUser(),
1217 'test'
1218 );
1219 $this->assertTrue( $result, 'right was granted to group, so should be allowed' );
1220
1221 $result = $permissionManager->userHasRight(
1222 $this->getTestUser( 'unittesters' )->getUser(),
1223 'limitabletest'
1224 );
1225 $this->assertTrue( $result, 'not granted, but listed as implicit' );
1226
1227 $result = $permissionManager->userHasRight(
1228 $this->getTestUser( 'unittesters' )->getUser(),
1229 'mailpassword'
1230 );
1231 $this->assertTrue( $result, 'not granted, but has a limit, so should be allowed' );
1232
1233 $result = $permissionManager->userHasRight(
1234 $this->getTestUser( 'unittesters' )->getUser(),
1235 'rollback'
1236 );
1237 $this->assertFalse( $result, 'not granted, has a limit but is listed as available, so should not be allowed' );
1238
1239 $result = $permissionManager->userHasRight(
1240 $this->getTestUser( 'formertesters' )->getUser(),
1241 'runtest'
1242 );
1243 $this->assertFalse( $result, 'not granted, should not be allowed' );
1244
1245 $result = $permissionManager->userHasRight(
1246 $this->getTestUser( 'formertesters' )->getUser(),
1247 ''
1248 );
1249 $this->assertTrue( $result, 'empty action should always be granted' );
1250 }
1251
1252 public function testIsEveryoneAllowed() {
1253 $permissionManager = $this->getServiceContainer()->getPermissionManager();
1254
1255 $result = $permissionManager->isEveryoneAllowed( 'editmyoptions' );
1256 $this->assertTrue( $result );
1257
1258 $result = $permissionManager->isEveryoneAllowed( 'test' );
1259 $this->assertFalse( $result );
1260 }
1261
1262 public function testAddTemporaryUserRights() {
1263 $permissionManager = $this->getServiceContainer()->getPermissionManager();
1264 $this->overrideUserPermissions( $this->user, [ 'read', 'edit' ] );
1265
1266 $this->assertEquals( [ 'read', 'edit' ], $permissionManager->getUserPermissions( $this->user ) );
1267 $this->assertFalse( $permissionManager->userHasRight( $this->user, 'move' ) );
1268
1269 $scope = $permissionManager->addTemporaryUserRights( $this->user, [ 'move', 'delete' ] );
1270 $this->assertEquals( [ 'read', 'edit', 'move', 'delete' ],
1271 $permissionManager->getUserPermissions( $this->user ) );
1272 $this->assertTrue( $permissionManager->userHasRight( $this->user, 'move' ) );
1273
1274 $scope2 = $permissionManager->addTemporaryUserRights( $this->user, [ 'delete', 'upload' ] );
1275 $this->assertEquals( [ 'read', 'edit', 'move', 'delete', 'upload' ],
1276 $permissionManager->getUserPermissions( $this->user ) );
1277
1278 ScopedCallback::consume( $scope );
1279 $this->assertEquals( [ 'read', 'edit', 'delete', 'upload' ],
1280 $permissionManager->getUserPermissions( $this->user ) );
1281 ScopedCallback::consume( $scope2 );
1282 $this->assertEquals( [ 'read', 'edit' ],
1283 $permissionManager->getUserPermissions( $this->user ) );
1284 $this->assertFalse( $permissionManager->userHasRight( $this->user, 'move' ) );
1285
1286 ( function () use ( $permissionManager ) {
1287 $scope = $permissionManager->addTemporaryUserRights( $this->user, 'move' );
1288 $this->assertTrue( $permissionManager->userHasRight( $this->user, 'move' ) );
1289 } )();
1290 $this->assertFalse( $permissionManager->userHasRight( $this->user, 'move' ) );
1291 }
1292
1293 public static function provideGetRestrictionLevels() {
1294 return [
1295 'No namespace restriction' => [ [ '', 'autoconfirmed', 'sysop' ], NS_TALK ],
1296 'Restricted to autoconfirmed' => [ [ '', 'sysop' ], NS_MAIN ],
1297 'Restricted to sysop' => [ [ '' ], NS_USER ],
1298 'Restricted to someone in two groups' => [ [ '', 'sysop' ], 101 ],
1299 'No special permissions' => [
1300 [ '' ],
1301 NS_TALK,
1302 []
1303 ],
1304 'autoconfirmed' => [
1305 [ '', 'autoconfirmed' ],
1306 NS_TALK,
1307 [ 'autoconfirmed' ]
1308 ],
1309 'autoconfirmed revoked' => [
1310 [ '' ],
1311 NS_TALK,
1312 [ 'autoconfirmed', 'noeditsemiprotected' ]
1313 ],
1314 'sysop' => [
1315 [ '', 'autoconfirmed', 'sysop' ],
1316 NS_TALK,
1317 [ 'sysop' ]
1318 ],
1319 'sysop with autoconfirmed revoked (a bit silly)' => [
1320 [ '', 'sysop' ],
1321 NS_TALK,
1322 [ 'sysop', 'noeditsemiprotected' ]
1323 ],
1324 ];
1325 }
1326
1327 /**
1328 * @dataProvider provideGetRestrictionLevels
1329 */
1330 public function testGetRestrictionLevels( array $expected, $ns, ?array $userGroups = null ) {
1331 $this->overrideConfigValues( [
1332 MainConfigNames::GroupPermissions => [
1333 '*' => [ 'edit' => true ],
1334 'autoconfirmed' => [ 'editsemiprotected' => true ],
1335 'sysop' => [
1336 'editsemiprotected' => true,
1337 'editprotected' => true,
1338 ],
1339 'privileged' => [ 'privileged' => true ],
1340 ],
1341 MainConfigNames::RevokePermissions => [
1342 'noeditsemiprotected' => [ 'editsemiprotected' => true ],
1343 ],
1344 MainConfigNames::NamespaceProtection => [
1345 NS_MAIN => 'autoconfirmed',
1346 NS_USER => 'sysop',
1347 101 => [ 'editsemiprotected', 'privileged' ],
1348 ],
1349 MainConfigNames::RestrictionLevels => [ '', 'autoconfirmed', 'sysop' ],
1350 MainConfigNames::Autopromote => []
1351 ] );
1352 $user = $userGroups === null ? null : $this->getTestUser( $userGroups )->getUser();
1353 $this->assertSame( $expected, $this->getServiceContainer()
1354 ->getPermissionManager()
1355 ->getNamespaceRestrictionLevels( $ns, $user ) );
1356 }
1357
1358 public function testGetAllPermissions() {
1359 $this->overrideConfigValue( MainConfigNames::AvailableRights, [ 'test_right' ] );
1360 $this->assertContains(
1361 'test_right',
1362 $this->getServiceContainer()
1363 ->getPermissionManager()
1364 ->getAllPermissions()
1365 );
1366 }
1367
1368 public function testAnonPermissionsNotClash() {
1369 $user1 = User::newFromName( 'User1' );
1370 $user2 = User::newFromName( 'User2' );
1371 $pm = $this->getServiceContainer()->getPermissionManager();
1372 $pm->overrideUserRightsForTesting( $user2, [] );
1373 $this->assertNotSame( $pm->getUserPermissions( $user1 ), $pm->getUserPermissions( $user2 ) );
1374 }
1375
1376 public function testAnonPermissionsNotClashOneRegistered() {
1377 $user1 = User::newFromName( 'User1' );
1378 $user2 = $this->getTestSysop()->getUser();
1379 $pm = $this->getServiceContainer()->getPermissionManager();
1380 $this->assertNotSame( $pm->getUserPermissions( $user1 ), $pm->getUserPermissions( $user2 ) );
1381 }
1382
1383 /**
1384 * Test delete-redirect checks for Special:MovePage
1385 */
1386 public function testDeleteRedirect() {
1387 $this->editPage( 'ExistentRedirect3', '#REDIRECT [[Existent]]' );
1388 $page = Title::makeTitle( NS_MAIN, 'ExistentRedirect3' );
1389 $pm = $this->getServiceContainer()->getPermissionManager();
1390
1391 $user = $this->getTestUser()->getUser();
1392
1393 $this->assertFalse( $pm->quickUserCan( 'delete-redirect', $user, $page ) );
1394
1395 $pm->overrideUserRightsForTesting( $user, 'delete-redirect' );
1396
1397 $this->assertTrue( $pm->quickUserCan( 'delete-redirect', $user, $page ) );
1398 $this->assertArrayEquals( [], $pm->getPermissionErrors( 'delete-redirect', $user, $page ) );
1399 }
1400
1401 /**
1402 * Ensure normal admins can view deleted javascript, but not restore it
1403 * See T202989
1404 */
1405 public function testSysopInterfaceAdminRights() {
1406 $interfaceAdmin = $this->getTestUser( [ 'interface-admin', 'sysop' ] )->getUser();
1407 $admin = $this->getTestSysop()->getUser();
1408
1409 $permManager = $this->getServiceContainer()->getPermissionManager();
1410 $userJs = Title::makeTitle( NS_USER, 'Example/common.js' );
1411
1412 $this->assertTrue( $permManager->userCan( 'delete', $admin, $userJs ) );
1413 $this->assertTrue( $permManager->userCan( 'delete', $interfaceAdmin, $userJs ) );
1414 $this->assertTrue( $permManager->userCan( 'deletedhistory', $admin, $userJs ) );
1415 $this->assertTrue( $permManager->userCan( 'deletedhistory', $interfaceAdmin, $userJs ) );
1416 $this->assertTrue( $permManager->userCan( 'deletedtext', $admin, $userJs ) );
1417 $this->assertTrue( $permManager->userCan( 'deletedtext', $interfaceAdmin, $userJs ) );
1418 $this->assertFalse( $permManager->userCan( 'undelete', $admin, $userJs ) );
1419 $this->assertTrue( $permManager->userCan( 'undelete', $interfaceAdmin, $userJs ) );
1420 }
1421
1422 /**
1423 * Ensure specific users can view deleted contents regardless of Namespace
1424 * Protection, but not restore it
1425 * See T362536
1426 *
1427 * @dataProvider provideDeletedViewerRights
1428 */
1429 public function testDeletedViewerRights(
1430 $userGroup,
1431 $userPerms,
1432 $expectedUserCan
1433 ) {
1434 $currentUser = $this->getTestUser( $userGroup )->getUser();
1435 $permManager = $this->getServiceContainer()->getPermissionManager();
1436 $targetPage = Title::makeTitle( NS_MEDIAWIKI, 'Example' );
1437 foreach ( $userPerms as $userPerm ) {
1438 $this->assertSame(
1439 $expectedUserCan,
1440 $permManager->userCan( $userPerm, $currentUser, $targetPage )
1441 );
1442 }
1443 }
1444
1445 public static function provideDeletedViewerRights() {
1446 yield [
1447 'usergroup' => '*',
1448 'user permissions' => [
1449 'delete',
1450 'deletedhistory',
1451 'deletedtext',
1452 'suppressrevision',
1453 'undelete',
1454 'viewsuppressed'
1455 ],
1456 'user can' => false
1457 ];
1458 yield [
1459 'usergroup' => 'deleted-viewer',
1460 'user permissions' => [
1461 'delete',
1462 'suppressrevision',
1463 'undelete'
1464 ],
1465 'user can' => false
1466 ];
1467 yield [
1468 'usergroup' => 'deleted-viewer',
1469 'user permissions' => [
1470 'deletedhistory',
1471 'deletedtext',
1472 'viewsuppressed'
1473 ],
1474 'user can' => true
1475 ];
1476 }
1477
1478 /**
1479 * Regression test for T306358 -- proper page assertion when checking
1480 * blocked status on a special page
1481 */
1482 public function testBlockedFromNonProperPage() {
1483 $page = Title::makeTitle( NS_SPECIAL, 'Blankpage' );
1484 $pm = $this->getServiceContainer()->getPermissionManager();
1485 $user = $this->getMockBuilder( User::class )
1486 ->onlyMethods( [ 'getBlock' ] )
1487 ->getMock();
1488 $user->method( 'getBlock' )
1489 ->willReturn( new DatabaseBlock( [
1490 'address' => '127.0.8.1',
1491 'by' => $this->user,
1492 ] ) );
1493 $errors = $pm->getPermissionErrors( 'test', $user, $page );
1494 $this->assertNotEmpty( $errors );
1495 }
1496
1497 /**
1498 * Test interaction with $wgWhitelistRead.
1499 *
1500 * @dataProvider provideWhitelistRead
1501 */
1502 public function testWhitelistRead( array $whitelist, string $title, bool $shouldAllow ) {
1503 $this->overrideConfigValues( [
1504 MainConfigNames::LanguageCode => 'es',
1505 MainConfigNames::WhitelistRead => $whitelist,
1506 ] );
1507 $this->setGroupPermissions( '*', 'read', false );
1508
1509 $title = Title::newFromText( $title );
1510 $pm = $this->getServiceContainer()->getPermissionManager();
1511 $errors = $pm->getPermissionErrors( 'read', new User, $title );
1512 if ( $shouldAllow ) {
1513 $this->assertSame( [], $errors );
1514 } else {
1515 $this->assertNotEmpty( $errors );
1516 }
1517 }
1518
1519 public static function provideWhitelistRead() {
1520 yield 'no match' => [ [ 'Bar', 'Baz' ], 'Foo', false ];
1521 yield 'match' => [ [ 'Bar', 'Foo', 'Baz' ], 'Foo', true ];
1522 yield 'text form' => [ [ 'Foo bar' ], 'Foo_bar', true ];
1523 yield 'dbkey form' => [ [ 'Foo_bar' ], 'Foo bar', true ];
1524 yield 'local namespace' => [ [ 'Usuario:Foo' ], 'User:Foo', true ];
1525 yield 'legacy mainspace' => [ [ ':Foo' ], 'Foo', true ];
1526 yield 'local special' => [ [ 'Especial:Todas' ], 'Special:Allpages', true ];
1527 }
1528
1529 /**
1530 * @covers \MediaWiki\Permissions\PermissionManager::getPermissionErrors
1531 */
1532 public function testGetPermissionErrors_ignoreErrors() {
1533 $hookCallback = static function ( $title, $user, $action, &$result ) {
1534 $result = [
1535 [ 'ignore', 'param' ],
1536 [ 'noignore', 'param' ],
1537 'ignore',
1538 'noignore',
1539 new Message( 'ignore' ),
1540 ];
1541 return false;
1542 };
1543 $this->setTemporaryHook( 'getUserPermissionsErrors', $hookCallback );
1544
1545 $pm = $this->getServiceContainer()->getPermissionManager();
1546 $errors = $pm->getPermissionErrors(
1547 'read',
1548 $this->user,
1549 $this->title,
1550 $pm::RIGOR_QUICK,
1551 [ 'ignore' ]
1552 );
1553
1554 $this->assertSame( [
1555 [ 'noignore', 'param' ],
1556 [ 'noignore' ],
1557 ], $errors );
1558 }
1559
1560 /**
1561 * @covers \MediaWiki\Permissions\PermissionManager::checkQuickPermissions
1562 */
1563 public function testGetPermissionErrors_objectFromHookResult() {
1564 $msg = ApiMessage::create( 'mymessage', 'mymessagecode', [ 'mydata' => true ] );
1565 $this->setTemporaryHook(
1566 'TitleQuickPermissions',
1567 static function ( $hookTitle, $hookUser, $hookAction, &$errors, $doExpensiveQueries, $short ) use ( $msg ) {
1568 $errors[] = [ $msg ];
1569 return false;
1570 }
1571 );
1572
1573 $pm = $this->getServiceContainer()->getPermissionManager();
1574
1575 $errorsStatus = $pm->getPermissionStatus( 'create', $this->user, $this->title );
1576 $errorsArray = $pm->getPermissionErrors( 'create', $this->user, $this->title );
1577
1578 $this->assertSame(
1579 [ $msg ],
1580 $errorsStatus->getMessages(),
1581 'getPermissionStatus() preserves ApiMessage objects'
1582 );
1583 }
1584
1585 public function testShouldLimitPermissionsForBlockedUserWhenBlockDisablesLogin(): void {
1586 $this->overrideConfigValues( [
1587 MainConfigNames::BlockDisablesLogin => true,
1588 MainConfigNames::GroupPermissions => [
1589 '*' => [ 'edit' => true ],
1590 'user' => [ 'edit' => true, 'move' => true ],
1591 'sysop' => [ 'block' => true ],
1592 ],
1593 ] );
1594
1595 $testUser = $this->getTestUser()->getUserIdentity();
1596 $this->blockUser( $testUser );
1597
1598 $permissions = $this->getServiceContainer()->getPermissionManager()->getUserPermissions( $testUser );
1599
1600 $this->assertSame( [ 'edit' ], $permissions );
1601 }
1602
1603 public function testShouldLimitPermissionsForBlockedUserShouldAllowPermissionChecksInGetUserBlock(): void {
1604 $this->overrideConfigValues( [
1605 MainConfigNames::BlockDisablesLogin => true,
1606 MainConfigNames::GroupPermissions => [
1607 '*' => [ 'edit' => true ],
1608 'user' => [ 'edit' => true, 'move' => true ],
1609 'sysop' => [ 'block' => true ],
1610 ],
1611 ] );
1612
1613 $testUser = $this->getTestUser()->getUserIdentity();
1614 $hookRan = false;
1615
1616 $this->setTemporaryHook(
1617 'GetUserBlock',
1618 function ( UserIdentity $user ) use ( $testUser, &$hookRan ): void {
1619 if ( $user->equals( $testUser ) ) {
1620 // Trigger an arbitrary permissions check to verify that they do not cause an infinite loop
1621 // when BlockDisablesLogin = true (T384197).
1622 $this->getServiceContainer()->getPermissionManager()
1623 ->userHasRight( $user, 'test' );
1624
1625 $hookRan = true;
1626 }
1627 }
1628 );
1629
1630 $testUser = $this->getTestUser()->getUserIdentity();
1631 $this->blockUser( $testUser );
1632
1633 $permissions = $this->getServiceContainer()->getPermissionManager()->getUserPermissions( $testUser );
1634
1635 $this->assertSame( [ 'edit' ], $permissions );
1636 $this->assertTrue( $hookRan );
1637 }
1638
1639 /**
1640 * Convenience function to block a given user.
1641 * @param UserIdentity $user
1642 * @return void
1643 */
1644 private function blockUser( UserIdentity $user ): void {
1645 $status = $this->getServiceContainer()
1646 ->getBlockUserFactory()
1647 ->newBlockUser( $user, $this->getTestSysop()->getAuthority(), 'infinity' )
1648 ->placeBlock();
1649
1650 $this->assertStatusGood( $status );
1651 }
1652 }