MediaWiki  1.32.5
ApiLoginTest.php
Go to the documentation of this file.
1 <?php
2 
6 use Wikimedia\TestingAccessWrapper;
7 
15 class ApiLoginTest extends ApiTestCase {
16  public function setUp() {
17  parent::setUp();
18 
19  $this->tablesUsed[] = 'bot_passwords';
20  }
21 
22  public static function provideEnableBotPasswords() {
23  return [
24  'Bot passwords enabled' => [ true ],
25  'Bot passwords disabled' => [ false ],
26  ];
27  }
28 
32  public function testExtendedDescription( $enableBotPasswords ) {
33  $this->setMwGlobals( 'wgEnableBotPasswords', $enableBotPasswords );
34  $ret = $this->doApiRequest( [
35  'action' => 'paraminfo',
36  'modules' => 'login',
37  'helpformat' => 'raw',
38  ] );
39  $this->assertSame(
40  'apihelp-login-extended-description' . ( $enableBotPasswords ? '' : '-nobotpasswords' ),
41  $ret[0]['paraminfo']['modules'][0]['description'][1]['key']
42  );
43  }
44 
48  public function testNoName() {
49  $session = [
50  'wsTokenSecrets' => [ 'login' => 'foobar' ],
51  ];
52  $ret = $this->doApiRequest( [
53  'action' => 'login',
54  'lgname' => '',
55  'lgpassword' => self::$users['sysop']->getPassword(),
56  'lgtoken' => (string)( new MediaWiki\Session\Token( 'foobar', '' ) ),
57  ], $session );
58  $this->assertSame( 'Failed', $ret[0]['login']['result'] );
59  }
60 
64  public function testDeprecatedUserLogin( $enableBotPasswords ) {
65  $this->setMwGlobals( 'wgEnableBotPasswords', $enableBotPasswords );
66 
67  $user = $this->getTestUser();
68 
69  $ret = $this->doApiRequest( [
70  'action' => 'login',
71  'lgname' => $user->getUser()->getName(),
72  ] );
73 
74  $this->assertSame(
76  'apiwarn-deprecation-login-token' )->text() ) ],
77  $ret[0]['warnings']['login']
78  );
79  $this->assertSame( 'NeedToken', $ret[0]['login']['result'] );
80 
81  $ret = $this->doApiRequest( [
82  'action' => 'login',
83  'lgtoken' => $ret[0]['login']['token'],
84  'lgname' => $user->getUser()->getName(),
85  'lgpassword' => $user->getPassword(),
86  ], $ret[2] );
87 
88  $this->assertSame(
90  'apiwarn-deprecation-login-' . ( $enableBotPasswords ? '' : 'no' ) . 'botpw' )
91  ->text() ) ],
92  $ret[0]['warnings']['login']
93  );
94  $this->assertSame(
95  [
96  'result' => 'Success',
97  'lguserid' => $user->getUser()->getId(),
98  'lgusername' => $user->getUser()->getName(),
99  ],
100  $ret[0]['login']
101  );
102  }
103 
113  private function doUserLogin( $name, $password, array $params = [] ) {
114  $ret = $this->doApiRequest( [
115  'action' => 'query',
116  'meta' => 'tokens',
117  'type' => 'login',
118  ] );
119 
120  $this->assertArrayNotHasKey( 'warnings', $ret );
121 
122  return $this->doApiRequest( array_merge(
123  [
124  'action' => 'login',
125  'lgtoken' => $ret[0]['query']['tokens']['logintoken'],
126  'lgname' => $name,
127  'lgpassword' => $password,
128  ], $params
129  ), $ret[2] );
130  }
131 
132  public function testBadToken() {
133  $user = self::$users['sysop'];
134  $userName = $user->getUser()->getName();
135  $password = $user->getPassword();
136  $user->getUser()->logout();
137 
138  $ret = $this->doUserLogin( $userName, $password, [ 'lgtoken' => 'invalid token' ] );
139 
140  $this->assertSame( 'WrongToken', $ret[0]['login']['result'] );
141  }
142 
143  public function testBadPass() {
144  $user = self::$users['sysop'];
145  $userName = $user->getUser()->getName();
146  $user->getUser()->logout();
147 
148  $ret = $this->doUserLogin( $userName, 'bad' );
149 
150  $this->assertSame( 'Failed', $ret[0]['login']['result'] );
151  }
152 
156  public function testGoodPass( $enableBotPasswords ) {
157  $this->setMwGlobals( 'wgEnableBotPasswords', $enableBotPasswords );
158 
159  $user = self::$users['sysop'];
160  $userName = $user->getUser()->getName();
161  $password = $user->getPassword();
162  $user->getUser()->logout();
163 
164  $ret = $this->doUserLogin( $userName, $password );
165 
166  $this->assertSame( 'Success', $ret[0]['login']['result'] );
167  $this->assertSame(
168  [ 'warnings' => ApiErrorFormatter::stripMarkup( wfMessage(
169  'apiwarn-deprecation-login-' . ( $enableBotPasswords ? '' : 'no' ) . 'botpw' )->
170  text() ) ],
171  $ret[0]['warnings']['login']
172  );
173  }
174 
178  public function testUnsupportedAuthResponseType( $enableBotPasswords ) {
179  $this->setMwGlobals( 'wgEnableBotPasswords', $enableBotPasswords );
180 
181  $mockProvider = $this->createMock(
183  $mockProvider->method( 'beginSecondaryAuthentication' )->willReturn(
184  MediaWiki\Auth\AuthenticationResponse::newUI(
185  [ new MediaWiki\Auth\UsernameAuthenticationRequest ],
186  // Slightly silly message here
187  wfMessage( 'mainpage' )
188  )
189  );
190  $mockProvider->method( 'getAuthenticationRequests' )
191  ->willReturn( [] );
192 
193  $this->mergeMwGlobalArrayValue( 'wgAuthManagerConfig', [
194  'secondaryauth' => [ [
195  'factory' => function () use ( $mockProvider ) {
196  return $mockProvider;
197  },
198  ] ],
199  ] );
200 
201  $user = self::$users['sysop'];
202  $userName = $user->getUser()->getName();
203  $password = $user->getPassword();
204  $user->getUser()->logout();
205 
206  $ret = $this->doUserLogin( $userName, $password );
207 
208  $this->assertSame( [ 'login' => [
209  'result' => 'Aborted',
211  'api-login-fail-aborted' . ( $enableBotPasswords ? '' : '-nobotpw' ) )->text() ),
212  ] ], $ret[0] );
213  }
214 
219  public function testGotCookie() {
220  $this->markTestIncomplete( "The server can't do external HTTP requests, "
221  . "and the internal one won't give cookies" );
222 
223  global $wgServer, $wgScriptPath;
224 
225  $user = self::$users['sysop'];
226  $userName = $user->getUser()->getName();
227  $password = $user->getPassword();
228 
230  self::$apiUrl . '?action=login&format=json',
231  [
232  'method' => 'POST',
233  'postData' => [
234  'lgname' => $userName,
235  'lgpassword' => $password,
236  ],
237  ],
238  __METHOD__
239  );
240  $req->execute();
241 
242  $content = json_decode( $req->getContent() );
243 
244  $this->assertSame( 'NeedToken', $content->login->result );
245 
246  $req->setData( [
247  'lgtoken' => $content->login->token,
248  'lgname' => $userName,
249  'lgpassword' => $password,
250  ] );
251  $req->execute();
252 
253  $cj = $req->getCookieJar();
254  $serverName = parse_url( $wgServer, PHP_URL_HOST );
255  $this->assertNotEquals( false, $serverName );
256  $serializedCookie = $cj->serializeToHttpRequest( $wgScriptPath, $serverName );
257  $this->assertRegExp(
258  '/_session=[^;]*; .*UserID=[0-9]*; .*UserName=' . $userName . '; .*Token=/',
259  $serializedCookie
260  );
261  }
262 
266  private function setUpForBotPassword() {
267  global $wgSessionProviders;
268 
269  $this->setMwGlobals( [
270  // We can't use mergeMwGlobalArrayValue because it will overwrite the existing entry
271  // with index 0
272  'wgSessionProviders' => array_merge( $wgSessionProviders, [
273  [
275  'args' => [ [ 'priority' => 40 ] ],
276  ],
277  ] ),
278  'wgEnableBotPasswords' => true,
279  'wgBotPasswordsDatabase' => false,
280  'wgCentralIdLookupProvider' => 'local',
281  'wgGrantPermissions' => [
282  'test' => [ 'read' => true ],
283  ],
284  ] );
285 
286  // Make sure our session provider is present
287  $manager = TestingAccessWrapper::newFromObject( SessionManager::singleton() );
288  if ( !isset( $manager->sessionProviders[BotPasswordSessionProvider::class] ) ) {
289  $tmp = $manager->sessionProviders;
290  $manager->sessionProviders = null;
291  $manager->sessionProviders = $tmp + $manager->getProviders();
292  }
293  $this->assertNotNull(
294  SessionManager::singleton()->getProvider( BotPasswordSessionProvider::class ),
295  'sanity check'
296  );
297 
298  $user = self::$users['sysop'];
299  $centralId = CentralIdLookup::factory()->centralIdFromLocalUser( $user->getUser() );
300  $this->assertNotSame( 0, $centralId, 'sanity check' );
301 
302  $password = 'ngfhmjm64hv0854493hsj5nncjud2clk';
303  $passwordFactory = MediaWikiServices::getInstance()->getPasswordFactory();
304  // A is unsalted MD5 (thus fast) ... we don't care about security here, this is test only
305  $passwordHash = $passwordFactory->newFromPlaintext( $password );
306 
307  $dbw = wfGetDB( DB_MASTER );
308  $dbw->insert(
309  'bot_passwords',
310  [
311  'bp_user' => $centralId,
312  'bp_app_id' => 'foo',
313  'bp_password' => $passwordHash->toString(),
314  'bp_token' => '',
315  'bp_restrictions' => MWRestrictions::newDefault()->toJson(),
316  'bp_grants' => '["test"]',
317  ],
318  __METHOD__
319  );
320 
321  $lgName = $user->getUser()->getName() . BotPassword::getSeparator() . 'foo';
322 
323  return [ $lgName, $password ];
324  }
325 
326  public function testBotPassword() {
327  $ret = $this->doUserLogin( ...$this->setUpForBotPassword() );
328 
329  $this->assertSame( 'Success', $ret[0]['login']['result'] );
330  }
331 
332  public function testBotPasswordThrottled() {
334 
335  $this->setGroupPermissions( 'sysop', 'noratelimit', false );
336  $this->setMwGlobals( 'wgMainCacheType', 'hash' );
337 
338  list( $name, $password ) = $this->setUpForBotPassword();
339 
340  for ( $i = 0; $i < $wgPasswordAttemptThrottle[0]['count']; $i++ ) {
341  $this->doUserLogin( $name, 'incorrectpasswordincorrectpassword' );
342  }
343 
344  $ret = $this->doUserLogin( $name, $password );
345 
346  $this->assertSame( [
347  'result' => 'Failed',
348  'reason' => ApiErrorFormatter::stripMarkup( wfMessage( 'login-throttled' )->
349  durationParams( $wgPasswordAttemptThrottle[0]['seconds'] )->text() ),
350  ], $ret[0]['login'] );
351  }
352 
353  public function testBotPasswordLocked() {
354  $this->setTemporaryHook( 'UserIsLocked', function ( User $unused, &$isLocked ) {
355  $isLocked = true;
356  return true;
357  } );
358 
359  $ret = $this->doUserLogin( ...$this->setUpForBotPassword() );
360 
361  $this->assertSame( [
362  'result' => 'Failed',
363  'reason' => wfMessage( 'botpasswords-locked' )->text(),
364  ], $ret[0]['login'] );
365  }
366 
367  public function testNoSameOriginSecurity() {
368  $this->setTemporaryHook( 'RequestHasSameOriginSecurity',
369  function () {
370  return false;
371  }
372  );
373 
374  $ret = $this->doApiRequest( [
375  'action' => 'login',
376  'errorformat' => 'plaintext',
377  ] )[0]['login'];
378 
379  $this->assertSame( [
380  'result' => 'Aborted',
381  'reason' => [
382  'code' => 'api-login-fail-sameorigin',
383  'text' => 'Cannot log in when the same-origin policy is not applied.',
384  ],
385  ], $ret );
386  }
387 }
ApiLoginTest\testBadToken
testBadToken()
Definition: ApiLoginTest.php:132
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:244
ApiLoginTest\testExtendedDescription
testExtendedDescription( $enableBotPasswords)
provideEnableBotPasswords
Definition: ApiLoginTest.php:32
false
processing should stop and the error should be shown to the user * false
Definition: hooks.txt:187
ApiLoginTest
API Database medium.
Definition: ApiLoginTest.php:15
MediaWikiTestCase\mergeMwGlobalArrayValue
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
Definition: MediaWikiTestCase.php:901
MediaWiki\Session\Session\BotPasswordSessionProvider
Session provider for bot passwords.
Definition: BotPasswordSessionProvider.php:34
MediaWikiTestCase\getTestUser
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
Definition: MediaWikiTestCase.php:179
BotPassword\getSeparator
static getSeparator()
Get the separator for combined user name + app ID.
Definition: BotPassword.php:230
ApiLoginTest\testBadPass
testBadPass()
Definition: ApiLoginTest.php:143
ApiLoginTest\testDeprecatedUserLogin
testDeprecatedUserLogin( $enableBotPasswords)
provideEnableBotPasswords
Definition: ApiLoginTest.php:64
ApiLoginTest\testBotPassword
testBotPassword()
Definition: ApiLoginTest.php:326
$req
this hook is for auditing only $req
Definition: hooks.txt:1018
$params
$params
Definition: styleTest.css.php:44
ApiLoginTest\provideEnableBotPasswords
static provideEnableBotPasswords()
Definition: ApiLoginTest.php:22
ApiLoginTest\testBotPasswordLocked
testBotPasswordLocked()
Definition: ApiLoginTest.php:353
php
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
ApiLoginTest\testBotPasswordThrottled
testBotPasswordThrottled()
Definition: ApiLoginTest.php:332
ApiLoginTest\setUp
setUp()
Definition: ApiLoginTest.php:16
ApiTestCase\doApiRequest
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null, $tokenType=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:63
ApiLoginTest\doUserLogin
doUserLogin( $name, $password, array $params=[])
Attempts to log in with the given name and password, retrieves the returned token,...
Definition: ApiLoginTest.php:113
ApiErrorFormatter\stripMarkup
static stripMarkup( $text)
Turn wikitext into something resembling plaintext.
Definition: ApiErrorFormatter.php:268
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2693
MediaWikiTestCase\setMwGlobals
setMwGlobals( $pairs, $value=null)
Sets a global, maintaining a stashed version of the previous global to be restored in tearDown.
Definition: MediaWikiTestCase.php:706
MediaWiki
A helper class for throttling authentication attempts.
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
DB_MASTER
const DB_MASTER
Definition: defines.php:26
array
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))
MWRestrictions\newDefault
static newDefault()
Definition: MWRestrictions.php:41
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
ApiTestCase
Definition: ApiTestCase.php:5
ApiLoginTest\testNoSameOriginSecurity
testNoSameOriginSecurity()
Definition: ApiLoginTest.php:367
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:105
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:50
$wgPasswordAttemptThrottle
$wgPasswordAttemptThrottle
Limit password attempts to X attempts per Y seconds per IP per account.
Definition: DefaultSettings.php:5795
$ret
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 & $ret
Definition: hooks.txt:2044
MediaWikiTestCase\setGroupPermissions
setGroupPermissions( $newPerms, $newKey=null, $newValue=null)
Alters $wgGroupPermissions for the duration of the test.
Definition: MediaWikiTestCase.php:1092
text
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
Definition: All_system_messages.txt:1267
ApiLoginTest\testGotCookie
testGotCookie()
Definition: ApiLoginTest.php:219
$wgSessionProviders
$wgSessionProviders
MediaWiki\Session\SessionProvider configuration.
Definition: DefaultSettings.php:4975
ApiLoginTest\setUpForBotPassword
setUpForBotPassword()
Definition: ApiLoginTest.php:266
true
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:2044
$content
$content
Definition: pageupdater.txt:72
class
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
MediaWikiTestCase\setTemporaryHook
setTemporaryHook( $hookName, $handler)
Create a temporary hook handler which will be reset by tearDown.
Definition: MediaWikiTestCase.php:2291
MediaWikiServices
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 MediaWikiServices
Definition: injection.txt:23
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt
CentralIdLookup\factory
static factory( $providerId=null)
Fetch a CentralIdLookup.
Definition: CentralIdLookup.php:46
$wgScriptPath
$wgScriptPath
The path we should point to.
Definition: DefaultSettings.php:137
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:47
ApiLoginTest\testNoName
testNoName()
Test result of attempted login with an empty username.
Definition: ApiLoginTest.php:48
ApiLoginTest\testGoodPass
testGoodPass( $enableBotPasswords)
provideEnableBotPasswords
Definition: ApiLoginTest.php:156
ApiLoginTest\testUnsupportedAuthResponseType
testUnsupportedAuthResponseType( $enableBotPasswords)
provideEnableBotPasswords
Definition: ApiLoginTest.php:178
MWHttpRequest\factory
static factory( $url, array $options=null, $caller=__METHOD__)
Generate a new request object Deprecated:
Definition: MWHttpRequest.php:184