MediaWiki  master
ApiUserrightsTest.php
Go to the documentation of this file.
1 <?php
2 
11 
12  protected function setUp() {
13  parent::setUp();
14  $this->tablesUsed = array_merge(
15  $this->tablesUsed,
16  [ 'change_tag', 'change_tag_def', 'logging' ]
17  );
18  }
19 
28  protected function setPermissions( $add = [], $remove = [] ) {
29  $this->setGroupPermissions( 'bureaucrat', 'userrights', false );
30 
31  if ( $add ) {
32  $this->mergeMwGlobalArrayValue( 'wgAddGroups', [ 'bureaucrat' => $add ] );
33  }
34  if ( $remove ) {
35  $this->mergeMwGlobalArrayValue( 'wgRemoveGroups', [ 'bureaucrat' => $remove ] );
36  }
37  }
38 
53  protected function doSuccessfulRightsChange(
54  $expectedGroups = 'sysop', array $params = [], User $user = null
55  ) {
56  $expectedGroups = (array)$expectedGroups;
57  $params['action'] = 'userrights';
58 
59  if ( !$user ) {
60  $user = $this->getMutableTestUser()->getUser();
61  }
62 
63  $this->assertTrue( TestUserRegistry::isMutable( $user ),
64  'Immutable user passed to doSuccessfulRightsChange!' );
65 
66  if ( !isset( $params['user'] ) && !isset( $params['userid'] ) ) {
67  $params['user'] = $user->getName();
68  }
69  if ( !isset( $params['add'] ) && !isset( $params['remove'] ) ) {
70  $params['add'] = 'sysop';
71  }
72 
74 
75  $user->clearInstanceCache();
76  $this->assertSame( $expectedGroups, $user->getGroups() );
77 
78  $this->assertArrayNotHasKey( 'warnings', $res[0] );
79  }
80 
90  protected function doFailedRightsChange(
91  $expectedException, array $params = [], User $user = null
92  ) {
93  $params['action'] = 'userrights';
94 
95  $this->setExpectedException( ApiUsageException::class, $expectedException );
96 
97  if ( !$user ) {
98  // If 'user' or 'userid' is specified and $user was not specified,
99  // the user we're creating now will have nothing to do with the API
100  // request, but that's okay, since we're just testing that it has
101  // no groups.
102  $user = $this->getMutableTestUser()->getUser();
103  }
104 
105  $this->assertTrue( TestUserRegistry::isMutable( $user ),
106  'Immutable user passed to doFailedRightsChange!' );
107 
108  if ( !isset( $params['user'] ) && !isset( $params['userid'] ) ) {
109  $params['user'] = $user->getName();
110  }
111  if ( !isset( $params['add'] ) && !isset( $params['remove'] ) ) {
112  $params['add'] = 'sysop';
113  }
114  $expectedGroups = $user->getGroups();
115 
116  try {
117  $this->doApiRequestWithToken( $params );
118  } finally {
119  $user->clearInstanceCache();
120  $this->assertSame( $expectedGroups, $user->getGroups() );
121  }
122  }
123 
124  public function testAdd() {
125  $this->doSuccessfulRightsChange();
126  }
127 
128  public function testBlockedWithUserrights() {
129  global $wgUser;
130 
131  $block = new Block( [ 'address' => $wgUser, 'by' => $wgUser->getId(), ] );
132  $block->insert();
133 
134  try {
135  $this->doSuccessfulRightsChange();
136  } finally {
137  $block->delete();
138  $wgUser->clearInstanceCache();
139  }
140  }
141 
142  public function testBlockedWithoutUserrights() {
143  $user = $this->getTestSysop()->getUser();
144 
145  $this->setPermissions( true, true );
146 
147  $block = new Block( [ 'address' => $user, 'by' => $user->getId() ] );
148  $block->insert();
149 
150  try {
151  $this->doFailedRightsChange( 'You have been blocked from editing.' );
152  } finally {
153  $block->delete();
154  $user->clearInstanceCache();
155  }
156  }
157 
158  public function testAddMultiple() {
160  [ 'bureaucrat', 'sysop' ],
161  [ 'add' => 'bureaucrat|sysop' ]
162  );
163  }
164 
165  public function testTooFewExpiries() {
166  $this->doFailedRightsChange(
167  '2 expiry timestamps were provided where 3 were needed.',
168  [ 'add' => 'sysop|bureaucrat|bot', 'expiry' => 'infinity|tomorrow' ]
169  );
170  }
171 
172  public function testTooManyExpiries() {
173  $this->doFailedRightsChange(
174  '3 expiry timestamps were provided where 2 were needed.',
175  [ 'add' => 'sysop|bureaucrat', 'expiry' => 'infinity|tomorrow|never' ]
176  );
177  }
178 
179  public function testInvalidExpiry() {
180  $this->doFailedRightsChange( 'Invalid expiry time', [ 'expiry' => 'yummy lollipops!' ] );
181  }
182 
183  public function testMultipleInvalidExpiries() {
184  $this->doFailedRightsChange(
185  'Invalid expiry time "foo".',
186  [ 'add' => 'sysop|bureaucrat', 'expiry' => 'foo|bar' ]
187  );
188  }
189 
190  public function testWithTag() {
191  ChangeTags::defineTag( 'custom tag' );
192 
193  $user = $this->getMutableTestUser()->getUser();
194 
195  $this->doSuccessfulRightsChange( 'sysop', [ 'tags' => 'custom tag' ], $user );
196 
197  $dbr = wfGetDB( DB_REPLICA );
198  $this->assertSame(
199  'custom tag',
200  $dbr->selectField(
201  [ 'change_tag', 'logging', 'change_tag_def' ],
202  'ctd_name',
203  [
204  'ct_log_id = log_id',
205  'log_namespace' => NS_USER,
206  'log_title' => strtr( $user->getName(), ' ', '_' )
207  ],
208  __METHOD__,
209  [ 'change_tag_def' => [ 'JOIN', 'ctd_id = ct_tag_id' ] ]
210  )
211  );
212  }
213 
214  public function testWithoutTagPermission() {
215  ChangeTags::defineTag( 'custom tag' );
216 
217  $this->setGroupPermissions( 'user', 'applychangetags', false );
218 
219  $this->doFailedRightsChange(
220  'You do not have permission to apply change tags along with your changes.',
221  [ 'tags' => 'custom tag' ]
222  );
223  }
224 
225  public function testNonexistentUser() {
226  $this->doFailedRightsChange(
227  'There is no user by the name "Nonexistent user". Check your spelling.',
228  [ 'user' => 'Nonexistent user' ]
229  );
230  }
231 
232  public function testWebToken() {
233  $sysop = $this->getTestSysop()->getUser();
234  $user = $this->getMutableTestUser()->getUser();
235 
236  $token = $sysop->getEditToken( $user->getName() );
237 
238  $res = $this->doApiRequest( [
239  'action' => 'userrights',
240  'user' => $user->getName(),
241  'add' => 'sysop',
242  'token' => $token,
243  ] );
244 
245  $user->clearInstanceCache();
246  $this->assertSame( [ 'sysop' ], $user->getGroups() );
247 
248  $this->assertArrayNotHasKey( 'warnings', $res[0] );
249  }
250 
259  private function getMockForProcessingExpiries( $canProcessExpiries ) {
260  $sysop = $this->getTestSysop()->getUser();
261  $user = $this->getMutableTestUser()->getUser();
262 
263  $token = $sysop->getEditToken( 'userrights' );
264 
265  $main = new ApiMain( new FauxRequest( [
266  'action' => 'userrights',
267  'user' => $user->getName(),
268  'add' => 'sysop',
269  'token' => $token,
270  ] ) );
271 
272  $mockUserRightsPage = $this->getMockBuilder( UserrightsPage::class )
273  ->setMethods( [ 'canProcessExpiries' ] )
274  ->getMock();
275  $mockUserRightsPage->method( 'canProcessExpiries' )->willReturn( $canProcessExpiries );
276 
277  $mockApi = $this->getMockBuilder( ApiUserrights::class )
278  ->setConstructorArgs( [ $main, 'userrights' ] )
279  ->setMethods( [ 'getUserRightsPage' ] )
280  ->getMock();
281  $mockApi->method( 'getUserRightsPage' )->willReturn( $mockUserRightsPage );
282 
283  return $mockApi;
284  }
285 
286  public function testCanProcessExpiries() {
287  $mock1 = $this->getMockForProcessingExpiries( true );
288  $this->assertArrayHasKey( 'expiry', $mock1->getAllowedParams() );
289 
290  $mock2 = $this->getMockForProcessingExpiries( false );
291  $this->assertArrayNotHasKey( 'expiry', $mock2->getAllowedParams() );
292  }
293 
303  public function testAddAndRemoveGroups(
304  array $permissions = null, array $groupsToChange, array $expectedGroups
305  ) {
306  if ( $permissions !== null ) {
307  $this->setPermissions( $permissions[0], $permissions[1] );
308  }
309 
310  $params = [
311  'add' => implode( '|', $groupsToChange[0] ),
312  'remove' => implode( '|', $groupsToChange[1] ),
313  ];
314 
315  // We'll take a bot so we have a group to remove
316  $user = $this->getMutableTestUser( [ 'bot' ] )->getUser();
317 
318  $this->doSuccessfulRightsChange( $expectedGroups, $params, $user );
319  }
320 
321  public function addAndRemoveGroupsProvider() {
322  return [
323  'Simple add' => [
324  [ [ 'sysop' ], [] ],
325  [ [ 'sysop' ], [] ],
326  [ 'bot', 'sysop' ]
327  ], 'Add with only remove permission' => [
328  [ [], [ 'sysop' ] ],
329  [ [ 'sysop' ], [] ],
330  [ 'bot' ],
331  ], 'Add with global remove permission' => [
332  [ [], true ],
333  [ [ 'sysop' ], [] ],
334  [ 'bot' ],
335  ], 'Simple remove' => [
336  [ [], [ 'bot' ] ],
337  [ [], [ 'bot' ] ],
338  [],
339  ], 'Remove with only add permission' => [
340  [ [ 'bot' ], [] ],
341  [ [], [ 'bot' ] ],
342  [ 'bot' ],
343  ], 'Remove with global add permission' => [
344  [ true, [] ],
345  [ [], [ 'bot' ] ],
346  [ 'bot' ],
347  ], 'Add and remove same new group' => [
348  null,
349  [ [ 'sysop' ], [ 'sysop' ] ],
350  // The userrights code does removals before adds, so it doesn't remove the sysop
351  // group here and only adds it.
352  [ 'bot', 'sysop' ],
353  ], 'Add and remove same existing group' => [
354  null,
355  [ [ 'bot' ], [ 'bot' ] ],
356  // But here it first removes the existing group and then re-adds it.
357  [ 'bot' ],
358  ],
359  ];
360  }
361 }
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
testAddAndRemoveGroups(array $permissions=null, array $groupsToChange, array $expectedGroups)
Tests adding and removing various groups with various permissions.
getMockForProcessingExpiries( $canProcessExpiries)
Helper for testCanProcessExpiries that returns a mock ApiUserrights that either can or cannot process...
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:62
insert( $dbw=null)
Insert a block into the block table.
Definition: Block.php:543
API Database medium.
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
doApiRequestWithToken(array $params, array $session=null, User $user=null, $tokenType='auto')
Convenience function to access the token parameter of doApiRequest() more succinctly.
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:48
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1982
static getTestSysop()
Convenience method for getting an immutable admin test user.
setGroupPermissions( $newPerms, $newKey=null, $newValue=null)
Alters $wgGroupPermissions for the duration of the test.
static getMutableTestUser( $groups=[])
Convenience method for getting a mutable test user.
$res
Definition: database.txt:21
$params
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:780
setPermissions( $add=[], $remove=[])
Unsets $wgGroupPermissions[&#39;bureaucrat&#39;][&#39;userrights&#39;], and sets $wgAddGroups[&#39;bureaucrat&#39;] and $wgRe...
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static defineTag( $tag)
Set ctd_user_defined = 1 in change_tag_def without checking that the tag name is valid.
Definition: ChangeTags.php:877
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
static isMutable(User $user)
doFailedRightsChange( $expectedException, array $params=[], User $user=null)
Perform an API userrights request that&#39;s expected to fail.
const DB_REPLICA
Definition: defines.php:25
Definition: Block.php:31
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1473
doSuccessfulRightsChange( $expectedGroups='sysop', array $params=[], User $user=null)
Perform an API userrights request that&#39;s expected to be successful.