File: PermissionManagerTest.php

package info (click to toggle)
mediawiki 1%3A1.43.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 417,464 kB
  • sloc: php: 1,062,949; javascript: 664,290; sql: 9,714; python: 5,458; xml: 3,489; sh: 1,131; makefile: 64
file content (513 lines) | stat: -rw-r--r-- 17,132 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
<?php

namespace MediaWiki\Tests\Unit\Permissions;

use MediaWiki\Actions\ActionFactory;
use MediaWiki\Block\BlockErrorFormatter;
use MediaWiki\Block\BlockManager;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\HookContainer\HookContainer;
use MediaWiki\MainConfigNames;
use MediaWiki\Page\RedirectLookup;
use MediaWiki\Permissions\GroupPermissionsLookup;
use MediaWiki\Permissions\PermissionManager;
use MediaWiki\Permissions\PermissionStatus;
use MediaWiki\Permissions\RestrictionStore;
use MediaWiki\SpecialPage\SpecialPageFactory;
use MediaWiki\Tests\Unit\DummyServicesTrait;
use MediaWiki\Title\Title;
use MediaWiki\Title\TitleFormatter;
use MediaWiki\User\TempUser\RealTempUserConfig;
use MediaWiki\User\User;
use MediaWiki\User\UserFactory;
use MediaWiki\User\UserGroupManager;
use MediaWiki\User\UserIdentityLookup;
use MediaWikiUnitTestCase;
use Wikimedia\TestingAccessWrapper;

/**
 * For the integration tests, see \MediaWiki\Tests\Integration\Permissions\PermissionManagerTest.
 *
 * @author DannyS712
 * @covers \MediaWiki\Permissions\PermissionManager
 */
class PermissionManagerTest extends MediaWikiUnitTestCase {
	use DummyServicesTrait;

	private function getPermissionManager( $options = [] ) {
		$overrideConfig = $options['config'] ?? [];
		$baseConfig = [
			MainConfigNames::WhitelistRead => false,
			MainConfigNames::WhitelistReadRegexp => false,
			MainConfigNames::EmailConfirmToEdit => false,
			MainConfigNames::BlockDisablesLogin => false,
			MainConfigNames::EnablePartialActionBlocks => false,
			MainConfigNames::GroupPermissions => [],
			MainConfigNames::RevokePermissions => [],
			MainConfigNames::GroupInheritsPermissions => [],
			MainConfigNames::AvailableRights => [],
			MainConfigNames::NamespaceProtection => [ NS_MEDIAWIKI => 'editinterface' ],
			MainConfigNames::RestrictionLevels => [ '', 'autoconfirmed', 'sysop' ],
			MainConfigNames::DeleteRevisionsLimit => false,
			MainConfigNames::RateLimits => [],
			MainConfigNames::ImplicitRights => [],
		];
		$config = $overrideConfig + $baseConfig;

		$hookContainer = $options['hookContainer'] ??
			$this->createMock( HookContainer::class );
		$redirectLookup = $options['redirectLookup'] ??
			$this->createMock( RedirectLookup::class );
		$restrictionStore = $options['restrictionStore'] ??
			$this->createMock( RestrictionStore::class );

		$permissionManager = new PermissionManager(
			new ServiceOptions( PermissionManager::CONSTRUCTOR_OPTIONS, $config ),
			$this->createMock( SpecialPageFactory::class ),
			$this->getDummyNamespaceInfo(),
			new GroupPermissionsLookup(
				new ServiceOptions( GroupPermissionsLookup::CONSTRUCTOR_OPTIONS, $config )
			),
			$this->createMock( UserGroupManager::class ),
			$this->createMock( BlockManager::class ),
			$this->createMock( BlockErrorFormatter::class ),
			$hookContainer,
			$this->createMock( UserIdentityLookup::class ),
			$redirectLookup,
			$restrictionStore,
			$this->createMock( TitleFormatter::class ),
			new RealTempUserConfig( [] ),
			$this->createMock( UserFactory::class ),
			$this->createMock( ActionFactory::class )
		);

		return TestingAccessWrapper::newFromObject( $permissionManager );
	}

	/**
	 * Does not cover the `editmyuserjsredirect` functionality, which is covered
	 * in testCheckUserConfigPermissionsForRedirect
	 *
	 * @dataProvider provideTestCheckUserConfigPermissions
	 * @param string $pageTitle Does not include the namespace prefix
	 * @param array $rights What rights the user should be given
	 * @param string $action
	 * @param string|bool $pageType 'css', 'js', 'json', or false for none of those
	 * @param array $expectedErrors
	 */
	public function testCheckUserConfigPermissions(
		string $pageTitle,
		array $rights,
		string $action,
		$pageType,
		array $expectedErrors
	) {
		$user = $this->createMock( User::class );
		$user->method( 'getId' )->willReturn( 123 );
		$user->method( 'getName' )->willReturn( 'NameOfActingUser' );

		$title = $this->createMock( Title::class );
		$title->method( 'getText' )->willReturn( $pageTitle );
		$title->method( 'isUserCssConfigPage' )->willReturn( $pageType === 'css' );
		$title->method( 'isUserJsonConfigPage' )->willReturn( $pageType === 'json' );
		$title->method( 'isUserJsConfigPage' )->willReturn( $pageType === 'js' );

		$permissionManager = $this->getPermissionManager();
		// Override user rights
		$permissionManager->overrideUserRightsForTesting( $user, $rights );

		$result = PermissionStatus::newEmpty();
		$permissionManager->checkUserConfigPermissions(
			$action,
			$user,
			$result,
			PermissionManager::RIGOR_QUICK, // unused
			true, // $short, unused
			$title
		);
		$this->assertEquals( $expectedErrors, $result->toLegacyErrorArray() );
	}

	public static function provideTestCheckUserConfigPermissions() {
		yield 'Patrol ignored' => [ 'NameOfActingUser/subpage', [], 'patrol', false, [] ];
		yield 'Own non-config' => [ 'NameOfActingUser/subpage', [], 'edit', false, [] ];
		yield 'Other non-config' => [ 'NameOfAnotherUser/subpage', [], 'edit', false, [] ];
		yield 'Delete other subpage' => [ 'NameOfAnotherUser/subpage', [], 'delete', false, [] ];

		foreach ( [ 'css', 'json', 'js' ] as $type ) {
			// User editing their own subpages, everything okay
			// ensure that we don't run the checks for redirects now, those are done separately
			yield "Own $type with editmyuser*" => [
				'NameOfActingUser/subpage.' . $type,
				[ "editmyuser{$type}", 'editmyuserjsredirect' ],
				'edit',
				$type,
				[]
			];

			// Interface admin editing own subpages, everything okay
			yield "Own $type with edituser*" => [
				'NameOfActingUser/subpage.' . $type,
				[ "edituser{$type}" ],
				'edit',
				$type,
				[]
			];

			// User with no rights editing own subpages, problematic
			yield "Own $type with no rights" => [
				'NameOfActingUser/subpage.' . $type,
				[],
				'edit',
				$type,
				[ [ "mycustom{$type}protected", 'edit' ] ]
			];

			// Interface admin editing other user's subpages, everything okay
			yield "Other $type with edituser*" => [
				'NameOfAnotherUser/subpage.' . $type,
				[ "edituser{$type}" ],
				'edit',
				$type,
				[]
			];

			// Normal user editing other user's subpages, problematic
			yield "Other $type with no rights" => [
				'NameOfAnotherUser/subpage.' . $type,
				[],
				'edit',
				$type,
				[ [ "custom{$type}protected", 'edit' ] ]
			];
		}
	}

	/**
	 * @dataProvider provideTestCheckUserConfigPermissionsForRedirect
	 */
	public function testCheckUserConfigPermissionsForRedirect(
		bool $canEditOwnRedirect,
		bool $isRedirect,
		int $targetNamespace,
		string $targetText,
		bool $expectErrors
	) {
		$user = $this->createMock( User::class );
		$user->method( 'getId' )->willReturn( 123 );
		$user->method( 'getName' )->willReturn( 'NameOfActingUser' );

		$title = $this->createMock( Title::class );
		$title->method( 'getText' )->willReturn( 'NameOfActingUser/common.js' );
		$title->method( 'isUserCssConfigPage' )->willReturn( false );
		$title->method( 'isUserJsonConfigPage' )->willReturn( false );
		$title->method( 'isUserJsConfigPage' )->willReturn( true );

		if ( $isRedirect ) {
			$target = $this->createMock( Title::class );
			$target->method( 'inNamespace' )
				->with( NS_USER )
				->willReturn( $targetNamespace === NS_USER );

			$target->method( 'getText' )->willReturn( $targetText );
		} else {
			$target = null;
		}

		$redirectLookup = $this->createMock( RedirectLookup::class );
		$redirectLookup->method( 'getRedirectTarget' )->with( $title )
			->willReturn( $target );

		$permissionManager = $this->getPermissionManager( [
			'redirectLookup' => $redirectLookup,
		] );

		// Override user rights
		$rights = [ 'editmyuserjs' ];
		if ( $canEditOwnRedirect ) {
			$rights[] = 'editmyuserjsredirect';
		}
		$permissionManager->overrideUserRightsForTesting( $user, $rights );

		$result = PermissionStatus::newEmpty();
		$permissionManager->checkUserConfigPermissions(
			'edit',
			$user,
			$result,
			PermissionManager::RIGOR_QUICK, // unused
			true, // $short, unused
			$title
		);
		$this->assertEquals(
			$expectErrors ? [ [ 'mycustomjsredirectprotected', 'edit' ] ] : [],
			$result->toLegacyErrorArray()
		);
	}

	public static function provideTestCheckUserConfigPermissionsForRedirect() {
		yield 'With `editmyuserjsredirect`' => [ true, true, NS_USER, 'NameOfActingUser/other.js', false ];
		yield 'Not a redirect' => [ false, false, NS_USER, 'NameOfActingUser/other.js', false ];
		yield 'Redirect out of user space' => [ false, true, NS_MAIN, 'MainPage.js', true ];
		yield 'Redirect to different user' => [ false, true, NS_USER, 'NameOfAnotherUser/other.js', true ];
		yield 'Redirect to own subpage' => [ false, true, NS_USER, 'NameOfActingUser/other.js', false ];
	}

	/**
	 * @dataProvider provideTestCheckPageRestrictions
	 */
	public function testCheckPageRestrictions(
		string $action,
		array $restrictions,
		array $rights,
		bool $cascading,
		array $expectedErrors
	) {
		$user = $this->createMock( User::class );
		$user->method( 'getId' )->willReturn( 123 );
		$user->method( 'getName' )->willReturn( 'NameOfActingUser' );

		$title = $this->createMock( Title::class );

		$restrictionStore = $this->createMock( RestrictionStore::class );
		$restrictionStore->expects( $this->any() )
			->method( 'listApplicableRestrictionTypes' )
			->with( $title )
			->willReturn( [ 'other-action', $action ] );
		$restrictionStore->expects( $this->once() )
			->method( 'getRestrictions' )
			->with( $title, $action )
			->willReturn( $restrictions );
		$restrictionStore->method( 'areRestrictionsCascading' )->willReturn( $cascading );

		$permissionManager = $this->getPermissionManager( [
			'restrictionStore' => $restrictionStore,
		] );
		$permissionManager->overrideUserRightsForTesting( $user, $rights );

		$result = PermissionStatus::newEmpty();
		$permissionManager->checkPageRestrictions(
			$action,
			$user,
			$result,
			PermissionManager::RIGOR_QUICK, // unused
			true, // $short, unused
			$title
		);
		$this->assertEquals( $expectedErrors, $result->toLegacyErrorArray() );
	}

	public static function provideTestCheckPageRestrictions() {
		yield 'No restrictions' => [ 'move', [], [], true, [] ];
		yield 'Empty string' => [ 'edit', [ '' ], [], true, [] ];
		yield 'Semi-protected, with rights' => [
			'edit',
			[ 'autoconfirmed' ],
			[ 'editsemiprotected' ],
			false,
			[]
		];
		yield 'Sysop protected, no rights' => [
			'edit',
			[ 'sysop', ],
			[],
			false,
			[ [ 'protectedpagetext', 'editprotected', 'edit' ] ]
		];
		yield 'Sysop protected and cascading, no protect' => [
			'edit',
			[ 'editprotected' ],
			[ 'editprotected' ],
			true,
			[ [ 'protectedpagetext', 'protect', 'edit' ] ]
		];
		yield 'Sysop protected and cascading, with rights' => [
			'edit',
			[ 'editprotected' ],
			[ 'editprotected', 'protect' ],
			true,
			[]
		];
	}

	/**
	 * @dataProvider provideTestCheckQuickPermissions
	 */
	public function testCheckQuickPermissions(
		int $namespace,
		string $pageTitle,
		string $userType,
		string $action,
		array $rights,
		string $expectedError
	) {
		// Convert string single error to the array of errors PermissionManager uses
		$expectedErrors = ( $expectedError === '' ? [] : [ [ $expectedError ] ] );

		$userIsAnon = $userType === 'anon';
		$userIsTemp = $userType === 'temp';
		$userIsNamed = $userType === 'user';
		$user = $this->createMock( User::class );
		$user->method( 'getId' )->willReturn( $userIsAnon ? 0 : 123 );
		$user->method( 'getName' )->willReturn( $userIsAnon ? '1.1.1.1' : 'NameOfActingUser' );
		$user->method( 'isAnon' )->willReturn( $userIsAnon );
		$user->method( 'isNamed' )->willReturn( $userIsNamed );
		$user->method( 'isTemp' )->willReturn( $userIsTemp );

		// HookContainer - always return true (false tested separately)
		$hookContainer = $this->createMock( HookContainer::class );
		$hookContainer->method( 'run' )
			->willReturn( true );

		// Overrides needed in case `GroupPermissionsLookup::groupHasPermission` is called
		$config = [
			MainConfigNames::GroupPermissions => [
				'autoconfirmed' => [
					'move' => true
				]
			]
		];

		$permissionManager = $this->getPermissionManager( [
			'config' => $config,
			'hookContainer' => $hookContainer,
		] );
		$permissionManager->overrideUserRightsForTesting( $user, $rights );

		$title = $this->createMock( Title::class );
		$title->method( 'getNamespace' )->willReturn( $namespace );
		$title->method( 'getText' )->willReturn( $pageTitle );

		// Ensure that `missingPermissionError` doesn't call User::newFatalPermissionDeniedStatus
		// which uses the global state
		$short = true;

		$result = PermissionStatus::newEmpty();
		$permissionManager->checkQuickPermissions(
			$action,
			$user,
			$result,
			PermissionManager::RIGOR_QUICK, // unused
			$short,
			$title
		);
		$this->assertEquals( $expectedErrors, $result->toLegacyErrorArray() );
	}

	public static function provideTestCheckQuickPermissions() {
		// $namespace, $pageTitle, $userIsAnon, $action, $rights, $expectedError

		// Four different possible errors when trying to create
		yield 'Anon createtalk fail' => [
			NS_TALK, 'Example', 'anon', 'create', [], 'nocreatetext'
		];
		yield 'Anon createpage fail' => [
			NS_MAIN, 'Example', 'anon', 'create', [], 'nocreatetext'
		];
		yield 'User createtalk fail' => [
			NS_TALK, 'Example', 'user', 'create', [], 'nocreate-loggedin'
		];
		yield 'User createpage fail' => [
			NS_MAIN, 'Example', 'user', 'create', [], 'nocreate-loggedin'
		];
		yield 'Temp user createpage fail' => [
			NS_MAIN, 'Example', 'temp', 'create', [], 'nocreatetext'
		];

		yield 'Createpage pass' => [
			NS_MAIN, 'Example', 'anon', 'create', [ 'createpage' ], ''
		];

		// Three different namespace specific move failures, even if user has `move` rights
		yield 'Move root user page fail' => [
			NS_USER, 'Example', 'anon', 'move', [ 'move' ], 'cant-move-user-page'
		];
		yield 'Move file fail' => [
			NS_FILE, 'Example', 'anon', 'move', [ 'move' ], 'movenotallowedfile'
		];
		yield 'Move category fail' => [
			NS_CATEGORY, 'Example', 'anon', 'move', [ 'move' ], 'cant-move-category-page'
		];

		// No move rights at all. Different failures depending on who is allowed to move.
		// Test method sets group permissions to [ 'autoconfirmed' => [ 'move' => true ] ]
		yield 'Anon move fail, autoconfirmed can move' => [
			NS_TALK, 'Example', 'anon', 'move', [], 'movenologintext'
		];
		yield 'User move fail, autoconfirmed can move' => [
			NS_TALK, 'Example', 'user', 'move', [], 'movenotallowed'
		];
		yield 'Temp user move fail, autoconfirmed can move' => [
			NS_TALK, 'Example', 'temp', 'move', [], 'movenologintext'
		];
		yield 'Move pass' => [ NS_MAIN, 'Example', 'anon', 'move', [ 'move' ], '' ];

		// Three different possible failures for move target
		yield 'Move-target no rights' => [
			NS_MAIN, 'Example', 'user', 'move-target', [], 'movenotallowed'
		];
		yield 'Move-target to user root' => [
			NS_USER, 'Example', 'user', 'move-target', [ 'move' ], 'cant-move-to-user-page'
		];
		yield 'Move-target to category' => [
			NS_CATEGORY, 'Example', 'user', 'move-target', [ 'move' ], 'cant-move-to-category-page'
		];
		yield 'Move-target pass' => [
			NS_MAIN, 'Example', 'user', 'move-target', [ 'move' ], ''
		];

		// Other actions without special handling
		yield 'Missing rights for edit' => [
			NS_MAIN, 'Example', 'user', 'edit', [], 'badaccess-group0'
		];
		yield 'Having rights for edit' => [
			NS_MAIN, 'Example', 'user', 'edit', [ 'edit', ], ''
		];
	}

	/**
	 * @dataProvider provideTestCheckQuickPermissionsHook
	 */
	public function testCheckQuickPermissionsHook( array $hookErrors, array $expectedResult ) {
		$title = $this->createMock( Title::class );
		$user = $this->createMock( User::class );
		$action = 'FakeActionGoesHere';

		$hookCallback = function ( $hookTitle, $hookUser, $hookAction, &$errors, $doExpensiveQueries, $short )
			use ( $user, $title, $action, $hookErrors )
		{
			$this->assertSame( $title, $hookTitle );
			$this->assertSame( $user, $hookUser );
			$this->assertSame( $action, $hookAction );
			$errors = $hookErrors;
			return false;
		};

		$hookContainer = $this->createHookContainer( [ 'TitleQuickPermissions' => $hookCallback ] );

		$permissionManager = $this->getPermissionManager( [
			'hookContainer' => $hookContainer,
		] );
		$result = PermissionStatus::newEmpty();
		$permissionManager->checkQuickPermissions(
			$action,
			$user,
			$result,
			PermissionManager::RIGOR_QUICK, // unused
			true, // $short, unused,
			$title
		);
		$this->assertEquals(
			$expectedResult,
			$result->toLegacyErrorArray()
		);
	}

	public function provideTestCheckQuickPermissionsHook() {
		// test name => [ $result / $errors, $status->toLegacyErrorArray() ]
		yield 'Hook returns false but no errors' => [ [], [] ];
		yield 'One error' => [ [ 'error-key' ], [ [ 'error-key' ] ] ];
		yield 'One error with params as array' => [ [ 'error-key', 'param' ], [ [ 'error-key', 'param' ] ] ];
		yield 'Multiple errors' => [ [ [ 'error-key' ], [ 'error-key-2' ] ], [ [ 'error-key' ], [ 'error-key-2' ] ] ];
	}

}