MediaWiki  1.30.0
ApiLoginTest.php
Go to the documentation of this file.
1 <?php
2 
3 use Wikimedia\TestingAccessWrapper;
4 
12 class ApiLoginTest extends ApiTestCase {
13 
17  public function testApiLoginNoName() {
18  $session = [
19  'wsTokenSecrets' => [ 'login' => 'foobar' ],
20  ];
21  $data = $this->doApiRequest( [ 'action' => 'login',
22  'lgname' => '', 'lgpassword' => self::$users['sysop']->getPassword(),
23  'lgtoken' => (string)( new MediaWiki\Session\Token( 'foobar', '' ) )
24  ], $session );
25  $this->assertEquals( 'Failed', $data[0]['login']['result'] );
26  }
27 
28  public function testApiLoginBadPass() {
30 
31  $user = self::$users['sysop'];
32  $userName = $user->getUser()->getName();
33  $user->getUser()->logout();
34 
35  if ( !isset( $wgServer ) ) {
36  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
37  }
38  $ret = $this->doApiRequest( [
39  "action" => "login",
40  "lgname" => $userName,
41  "lgpassword" => "bad",
42  ] );
43 
44  $result = $ret[0];
45 
46  $this->assertNotInternalType( "bool", $result );
47  $a = $result["login"]["result"];
48  $this->assertEquals( "NeedToken", $a );
49 
50  $token = $result["login"]["token"];
51 
52  $ret = $this->doApiRequest(
53  [
54  "action" => "login",
55  "lgtoken" => $token,
56  "lgname" => $userName,
57  "lgpassword" => "badnowayinhell",
58  ],
59  $ret[2]
60  );
61 
62  $result = $ret[0];
63 
64  $this->assertNotInternalType( "bool", $result );
65  $a = $result["login"]["result"];
66 
67  $this->assertEquals( 'Failed', $a );
68  }
69 
70  public function testApiLoginGoodPass() {
72 
73  if ( !isset( $wgServer ) ) {
74  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
75  }
76 
77  $user = self::$users['sysop'];
78  $userName = $user->getUser()->getName();
79  $password = $user->getPassword();
80  $user->getUser()->logout();
81 
82  $ret = $this->doApiRequest( [
83  "action" => "login",
84  "lgname" => $userName,
85  "lgpassword" => $password,
86  ]
87  );
88 
89  $result = $ret[0];
90  $this->assertNotInternalType( "bool", $result );
91  $this->assertNotInternalType( "null", $result["login"] );
92 
93  $a = $result["login"]["result"];
94  $this->assertEquals( "NeedToken", $a );
95  $token = $result["login"]["token"];
96 
97  $ret = $this->doApiRequest(
98  [
99  "action" => "login",
100  "lgtoken" => $token,
101  "lgname" => $userName,
102  "lgpassword" => $password,
103  ],
104  $ret[2]
105  );
106 
107  $result = $ret[0];
108 
109  $this->assertNotInternalType( "bool", $result );
110  $a = $result["login"]["result"];
111 
112  $this->assertEquals( "Success", $a );
113  }
114 
118  public function testApiLoginGotCookie() {
119  $this->markTestIncomplete( "The server can't do external HTTP requests, "
120  . "and the internal one won't give cookies" );
121 
123 
124  if ( !isset( $wgServer ) ) {
125  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
126  }
127  $user = self::$users['sysop'];
128  $userName = $user->getUser()->getName();
129  $password = $user->getPassword();
130 
131  $req = MWHttpRequest::factory( self::$apiUrl . "?action=login&format=xml",
132  [ "method" => "POST",
133  "postData" => [
134  "lgname" => $userName,
135  "lgpassword" => $password
136  ]
137  ],
138  __METHOD__
139  );
140  $req->execute();
141 
142  libxml_use_internal_errors( true );
143  $sxe = simplexml_load_string( $req->getContent() );
144  $this->assertNotInternalType( "bool", $sxe );
145  $this->assertThat( $sxe, $this->isInstanceOf( "SimpleXMLElement" ) );
146  $this->assertNotInternalType( "null", $sxe->login[0] );
147 
148  $a = $sxe->login[0]->attributes()->result[0];
149  $this->assertEquals( ' result="NeedToken"', $a->asXML() );
150  $token = (string)$sxe->login[0]->attributes()->token;
151 
152  $req->setData( [
153  "lgtoken" => $token,
154  "lgname" => $userName,
155  "lgpassword" => $password ] );
156  $req->execute();
157 
158  $cj = $req->getCookieJar();
159  $serverName = parse_url( $wgServer, PHP_URL_HOST );
160  $this->assertNotEquals( false, $serverName );
161  $serializedCookie = $cj->serializeToHttpRequest( $wgScriptPath, $serverName );
162  $this->assertNotEquals( '', $serializedCookie );
163  $this->assertRegExp(
164  '/_session=[^;]*; .*UserID=[0-9]*; .*UserName=' . $user->userName . '; .*Token=/',
165  $serializedCookie
166  );
167  }
168 
169  public function testRunLogin() {
170  $user = self::$users['sysop'];
171  $userName = $user->getUser()->getName();
172  $password = $user->getPassword();
173 
174  $data = $this->doApiRequest( [
175  'action' => 'login',
176  'lgname' => $userName,
177  'lgpassword' => $password ] );
178 
179  $this->assertArrayHasKey( "login", $data[0] );
180  $this->assertArrayHasKey( "result", $data[0]['login'] );
181  $this->assertEquals( "NeedToken", $data[0]['login']['result'] );
182  $token = $data[0]['login']['token'];
183 
184  $data = $this->doApiRequest( [
185  'action' => 'login',
186  "lgtoken" => $token,
187  "lgname" => $userName,
188  "lgpassword" => $password ], $data[2] );
189 
190  $this->assertArrayHasKey( "login", $data[0] );
191  $this->assertArrayHasKey( "result", $data[0]['login'] );
192  $this->assertEquals( "Success", $data[0]['login']['result'] );
193  }
194 
195  public function testBotPassword() {
197 
198  if ( !isset( $wgServer ) ) {
199  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
200  }
201 
202  $this->setMwGlobals( [
203  'wgSessionProviders' => array_merge( $wgSessionProviders, [
204  [
205  'class' => MediaWiki\Session\BotPasswordSessionProvider::class,
206  'args' => [ [ 'priority' => 40 ] ],
207  ]
208  ] ),
209  'wgEnableBotPasswords' => true,
210  'wgBotPasswordsDatabase' => false,
211  'wgCentralIdLookupProvider' => 'local',
212  'wgGrantPermissions' => [
213  'test' => [ 'read' => true ],
214  ],
215  ] );
216 
217  // Make sure our session provider is present
218  $manager = TestingAccessWrapper::newFromObject( MediaWiki\Session\SessionManager::singleton() );
219  if ( !isset( $manager->sessionProviders[MediaWiki\Session\BotPasswordSessionProvider::class] ) ) {
220  $tmp = $manager->sessionProviders;
221  $manager->sessionProviders = null;
222  $manager->sessionProviders = $tmp + $manager->getProviders();
223  }
224  $this->assertNotNull(
225  MediaWiki\Session\SessionManager::singleton()->getProvider(
227  ),
228  'sanity check'
229  );
230 
231  $user = self::$users['sysop'];
232  $centralId = CentralIdLookup::factory()->centralIdFromLocalUser( $user->getUser() );
233  $this->assertNotEquals( 0, $centralId, 'sanity check' );
234 
235  $password = 'ngfhmjm64hv0854493hsj5nncjud2clk';
236  $passwordFactory = new PasswordFactory();
237  $passwordFactory->init( RequestContext::getMain()->getConfig() );
238  // A is unsalted MD5 (thus fast) ... we don't care about security here, this is test only
239  $passwordHash = $passwordFactory->newFromPlaintext( $password );
240 
241  $dbw = wfGetDB( DB_MASTER );
242  $dbw->insert(
243  'bot_passwords',
244  [
245  'bp_user' => $centralId,
246  'bp_app_id' => 'foo',
247  'bp_password' => $passwordHash->toString(),
248  'bp_token' => '',
249  'bp_restrictions' => MWRestrictions::newDefault()->toJson(),
250  'bp_grants' => '["test"]',
251  ],
252  __METHOD__
253  );
254 
255  $lgName = $user->getUser()->getName() . BotPassword::getSeparator() . 'foo';
256 
257  $ret = $this->doApiRequest( [
258  'action' => 'login',
259  'lgname' => $lgName,
260  'lgpassword' => $password,
261  ] );
262 
263  $result = $ret[0];
264  $this->assertNotInternalType( 'bool', $result );
265  $this->assertNotInternalType( 'null', $result['login'] );
266 
267  $a = $result['login']['result'];
268  $this->assertEquals( 'NeedToken', $a );
269  $token = $result['login']['token'];
270 
271  $ret = $this->doApiRequest( [
272  'action' => 'login',
273  'lgtoken' => $token,
274  'lgname' => $lgName,
275  'lgpassword' => $password,
276  ], $ret[2] );
277 
278  $result = $ret[0];
279  $this->assertNotInternalType( 'bool', $result );
280  $a = $result['login']['result'];
281 
282  $this->assertEquals( 'Success', $a );
283  }
284 
285 }
ApiLoginTest\testApiLoginBadPass
testApiLoginBadPass()
Definition: ApiLoginTest.php:28
$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
MWHttpRequest\factory
static factory( $url, $options=null, $caller=__METHOD__)
Generate a new request object.
Definition: MWHttpRequest.php:184
ApiLoginTest
API Database medium.
Definition: ApiLoginTest.php:12
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1963
BotPassword\getSeparator
static getSeparator()
Get the separator for combined user name + app ID.
Definition: BotPassword.php:230
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
ApiLoginTest\testBotPassword
testBotPassword()
Definition: ApiLoginTest.php:195
$req
this hook is for auditing only $req
Definition: hooks.txt:988
ApiLoginTest\testApiLoginNoName
testApiLoginNoName()
Test result of attempted login with an empty username.
Definition: ApiLoginTest.php:17
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
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2856
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:672
MediaWiki
A helper class for throttling authentication attempts.
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_MASTER
const DB_MASTER
Definition: defines.php:26
string
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
MWRestrictions\newDefault
static newDefault()
Definition: MWRestrictions.php:41
ApiLoginTest\testRunLogin
testRunLogin()
Definition: ApiLoginTest.php:169
ApiTestCase
Definition: ApiTestCase.php:3
$wgServer
$wgServer
URL of the server.
Definition: DefaultSettings.php:109
$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:1965
ApiLoginTest\testApiLoginGoodPass
testApiLoginGoodPass()
Definition: ApiLoginTest.php:70
RequestContext\getMain
static getMain()
Static methods.
Definition: RequestContext.php:470
ApiTestCase\doApiRequest
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:73
ApiLoginTest\testApiLoginGotCookie
testApiLoginGotCookie()
Broken.
Definition: ApiLoginTest.php:118
$wgSessionProviders
$wgSessionProviders
MediaWiki\Session\SessionProvider configuration.
Definition: DefaultSettings.php:4977
PasswordFactory
Factory class for creating and checking Password objects.
Definition: PasswordFactory.php:28
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
CentralIdLookup\factory
static factory( $providerId=null)
Fetch a CentralIdLookup.
Definition: CentralIdLookup.php:45
$wgScriptPath
$wgScriptPath
The path we should point to.
Definition: DefaultSettings.php:141