MediaWiki  1.28.0
ApiLoginTest.php
Go to the documentation of this file.
1 <?php
2 
10 class ApiLoginTest extends ApiTestCase {
11 
15  public function testApiLoginNoName() {
16  $session = [
17  'wsTokenSecrets' => [ 'login' => 'foobar' ],
18  ];
19  $data = $this->doApiRequest( [ 'action' => 'login',
20  'lgname' => '', 'lgpassword' => self::$users['sysop']->getPassword(),
21  'lgtoken' => (string)( new MediaWiki\Session\Token( 'foobar', '' ) )
22  ], $session );
23  $this->assertEquals( 'Failed', $data[0]['login']['result'] );
24  }
25 
26  public function testApiLoginBadPass() {
28 
29  $user = self::$users['sysop'];
30  $userName = $user->getUser()->getName();
31  $user->getUser()->logout();
32 
33  if ( !isset( $wgServer ) ) {
34  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
35  }
36  $ret = $this->doApiRequest( [
37  "action" => "login",
38  "lgname" => $userName,
39  "lgpassword" => "bad",
40  ] );
41 
42  $result = $ret[0];
43 
44  $this->assertNotInternalType( "bool", $result );
45  $a = $result["login"]["result"];
46  $this->assertEquals( "NeedToken", $a );
47 
48  $token = $result["login"]["token"];
49 
50  $ret = $this->doApiRequest(
51  [
52  "action" => "login",
53  "lgtoken" => $token,
54  "lgname" => $userName,
55  "lgpassword" => "badnowayinhell",
56  ],
57  $ret[2]
58  );
59 
60  $result = $ret[0];
61 
62  $this->assertNotInternalType( "bool", $result );
63  $a = $result["login"]["result"];
64 
65  $this->assertEquals( 'Failed', $a );
66  }
67 
68  public function testApiLoginGoodPass() {
70 
71  if ( !isset( $wgServer ) ) {
72  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
73  }
74 
75  $user = self::$users['sysop'];
76  $userName = $user->getUser()->getName();
77  $password = $user->getPassword();
78  $user->getUser()->logout();
79 
80  $ret = $this->doApiRequest( [
81  "action" => "login",
82  "lgname" => $userName,
83  "lgpassword" => $password,
84  ]
85  );
86 
87  $result = $ret[0];
88  $this->assertNotInternalType( "bool", $result );
89  $this->assertNotInternalType( "null", $result["login"] );
90 
91  $a = $result["login"]["result"];
92  $this->assertEquals( "NeedToken", $a );
93  $token = $result["login"]["token"];
94 
95  $ret = $this->doApiRequest(
96  [
97  "action" => "login",
98  "lgtoken" => $token,
99  "lgname" => $userName,
100  "lgpassword" => $password,
101  ],
102  $ret[2]
103  );
104 
105  $result = $ret[0];
106 
107  $this->assertNotInternalType( "bool", $result );
108  $a = $result["login"]["result"];
109 
110  $this->assertEquals( "Success", $a );
111  }
112 
116  public function testApiLoginGotCookie() {
117  $this->markTestIncomplete( "The server can't do external HTTP requests, "
118  . "and the internal one won't give cookies" );
119 
121 
122  if ( !isset( $wgServer ) ) {
123  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
124  }
125  $user = self::$users['sysop'];
126  $userName = $user->getUser()->getName();
127  $password = $user->getPassword();
128 
129  $req = MWHttpRequest::factory( self::$apiUrl . "?action=login&format=xml",
130  [ "method" => "POST",
131  "postData" => [
132  "lgname" => $userName,
133  "lgpassword" => $password
134  ]
135  ],
136  __METHOD__
137  );
138  $req->execute();
139 
140  libxml_use_internal_errors( true );
141  $sxe = simplexml_load_string( $req->getContent() );
142  $this->assertNotInternalType( "bool", $sxe );
143  $this->assertThat( $sxe, $this->isInstanceOf( "SimpleXMLElement" ) );
144  $this->assertNotInternalType( "null", $sxe->login[0] );
145 
146  $a = $sxe->login[0]->attributes()->result[0];
147  $this->assertEquals( ' result="NeedToken"', $a->asXML() );
148  $token = (string)$sxe->login[0]->attributes()->token;
149 
150  $req->setData( [
151  "lgtoken" => $token,
152  "lgname" => $userName,
153  "lgpassword" => $password ] );
154  $req->execute();
155 
156  $cj = $req->getCookieJar();
157  $serverName = parse_url( $wgServer, PHP_URL_HOST );
158  $this->assertNotEquals( false, $serverName );
159  $serializedCookie = $cj->serializeToHttpRequest( $wgScriptPath, $serverName );
160  $this->assertNotEquals( '', $serializedCookie );
161  $this->assertRegExp(
162  '/_session=[^;]*; .*UserID=[0-9]*; .*UserName=' . $user->userName . '; .*Token=/',
163  $serializedCookie
164  );
165  }
166 
167  public function testRunLogin() {
168  $user = self::$users['sysop'];
169  $userName = $user->getUser()->getName();
170  $password = $user->getPassword();
171 
172  $data = $this->doApiRequest( [
173  'action' => 'login',
174  'lgname' => $userName,
175  'lgpassword' => $password ] );
176 
177  $this->assertArrayHasKey( "login", $data[0] );
178  $this->assertArrayHasKey( "result", $data[0]['login'] );
179  $this->assertEquals( "NeedToken", $data[0]['login']['result'] );
180  $token = $data[0]['login']['token'];
181 
182  $data = $this->doApiRequest( [
183  'action' => 'login',
184  "lgtoken" => $token,
185  "lgname" => $userName,
186  "lgpassword" => $password ], $data[2] );
187 
188  $this->assertArrayHasKey( "login", $data[0] );
189  $this->assertArrayHasKey( "result", $data[0]['login'] );
190  $this->assertEquals( "Success", $data[0]['login']['result'] );
191  }
192 
193  public function testBotPassword() {
194  global $wgServer, $wgSessionProviders;
195 
196  if ( !isset( $wgServer ) ) {
197  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
198  }
199 
200  $this->setMwGlobals( [
201  'wgSessionProviders' => array_merge( $wgSessionProviders, [
202  [
203  'class' => MediaWiki\Session\BotPasswordSessionProvider::class,
204  'args' => [ [ 'priority' => 40 ] ],
205  ]
206  ] ),
207  'wgEnableBotPasswords' => true,
208  'wgBotPasswordsDatabase' => false,
209  'wgCentralIdLookupProvider' => 'local',
210  'wgGrantPermissions' => [
211  'test' => [ 'read' => true ],
212  ],
213  ] );
214 
215  // Make sure our session provider is present
216  $manager = TestingAccessWrapper::newFromObject( MediaWiki\Session\SessionManager::singleton() );
217  if ( !isset( $manager->sessionProviders[MediaWiki\Session\BotPasswordSessionProvider::class] ) ) {
218  $tmp = $manager->sessionProviders;
219  $manager->sessionProviders = null;
220  $manager->sessionProviders = $tmp + $manager->getProviders();
221  }
222  $this->assertNotNull(
223  MediaWiki\Session\SessionManager::singleton()->getProvider(
224  MediaWiki\Session\BotPasswordSessionProvider::class
225  ),
226  'sanity check'
227  );
228 
229  $user = self::$users['sysop'];
230  $centralId = CentralIdLookup::factory()->centralIdFromLocalUser( $user->getUser() );
231  $this->assertNotEquals( 0, $centralId, 'sanity check' );
232 
233  $password = 'ngfhmjm64hv0854493hsj5nncjud2clk';
234  $passwordFactory = new PasswordFactory();
235  $passwordFactory->init( RequestContext::getMain()->getConfig() );
236  // A is unsalted MD5 (thus fast) ... we don't care about security here, this is test only
237  $passwordHash = $passwordFactory->newFromPlaintext( $password );
238 
239  $dbw = wfGetDB( DB_MASTER );
240  $dbw->insert(
241  'bot_passwords',
242  [
243  'bp_user' => $centralId,
244  'bp_app_id' => 'foo',
245  'bp_password' => $passwordHash->toString(),
246  'bp_token' => '',
247  'bp_restrictions' => MWRestrictions::newDefault()->toJson(),
248  'bp_grants' => '["test"]',
249  ],
250  __METHOD__
251  );
252 
253  $lgName = $user->getUser()->getName() . BotPassword::getSeparator() . 'foo';
254 
255  $ret = $this->doApiRequest( [
256  'action' => 'login',
257  'lgname' => $lgName,
258  'lgpassword' => $password,
259  ] );
260 
261  $result = $ret[0];
262  $this->assertNotInternalType( 'bool', $result );
263  $this->assertNotInternalType( 'null', $result['login'] );
264 
265  $a = $result['login']['result'];
266  $this->assertEquals( 'NeedToken', $a );
267  $token = $result['login']['token'];
268 
269  $ret = $this->doApiRequest( [
270  'action' => 'login',
271  'lgtoken' => $token,
272  'lgname' => $lgName,
273  'lgpassword' => $password,
274  ], $ret[2] );
275 
276  $result = $ret[0];
277  $this->assertNotInternalType( 'bool', $result );
278  $a = $result['login']['result'];
279 
280  $this->assertEquals( 'Success', $a );
281  }
282 
283 }
static getSeparator()
Get the separator for combined user name + app ID.
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
testApiLoginNoName()
Test result of attempted login with an empty username.
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:1936
API Database medium.
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:177
A helper class for throttling authentication attempts.
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
const DB_MASTER
Definition: defines.php:23
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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:1934
static getMain()
Static methods.
static factory($providerId=null)
Fetch a CentralIdLookup.
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 local account $user
Definition: hooks.txt:242
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
this hook is for auditing only $req
Definition: hooks.txt:1007
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:71
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
$wgScriptPath
The path we should point to.
static newDefault()
$wgServer
URL of the server.
static factory($url, $options=null, $caller=__METHOD__)
Generate a new request object.
static newFromObject($object)
Return the same object, without access restrictions.
setMwGlobals($pairs, $value=null)
testApiLoginGotCookie()
Broken.