MediaWiki  1.27.2
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']->password,
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  $user->getUser()->logout();
31 
32  if ( !isset( $wgServer ) ) {
33  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
34  }
35  $ret = $this->doApiRequest( [
36  "action" => "login",
37  "lgname" => $user->username,
38  "lgpassword" => "bad",
39  ] );
40 
41  $result = $ret[0];
42 
43  $this->assertNotInternalType( "bool", $result );
44  $a = $result["login"]["result"];
45  $this->assertEquals( "NeedToken", $a );
46 
47  $token = $result["login"]["token"];
48 
49  $ret = $this->doApiRequest(
50  [
51  "action" => "login",
52  "lgtoken" => $token,
53  "lgname" => $user->username,
54  "lgpassword" => "badnowayinhell",
55  ],
56  $ret[2]
57  );
58 
59  $result = $ret[0];
60 
61  $this->assertNotInternalType( "bool", $result );
62  $a = $result["login"]["result"];
63 
64  $this->assertEquals( 'Failed', $a );
65  }
66 
67  public function testApiLoginGoodPass() {
69 
70  if ( !isset( $wgServer ) ) {
71  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
72  }
73 
74  $user = self::$users['sysop'];
75  $user->getUser()->logout();
76 
77  $ret = $this->doApiRequest( [
78  "action" => "login",
79  "lgname" => $user->username,
80  "lgpassword" => $user->password,
81  ]
82  );
83 
84  $result = $ret[0];
85  $this->assertNotInternalType( "bool", $result );
86  $this->assertNotInternalType( "null", $result["login"] );
87 
88  $a = $result["login"]["result"];
89  $this->assertEquals( "NeedToken", $a );
90  $token = $result["login"]["token"];
91 
92  $ret = $this->doApiRequest(
93  [
94  "action" => "login",
95  "lgtoken" => $token,
96  "lgname" => $user->username,
97  "lgpassword" => $user->password,
98  ],
99  $ret[2]
100  );
101 
102  $result = $ret[0];
103 
104  $this->assertNotInternalType( "bool", $result );
105  $a = $result["login"]["result"];
106 
107  $this->assertEquals( "Success", $a );
108  }
109 
113  public function testApiLoginGotCookie() {
114  $this->markTestIncomplete( "The server can't do external HTTP requests, "
115  . "and the internal one won't give cookies" );
116 
118 
119  if ( !isset( $wgServer ) ) {
120  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
121  }
122  $user = self::$users['sysop'];
123 
124  $req = MWHttpRequest::factory( self::$apiUrl . "?action=login&format=xml",
125  [ "method" => "POST",
126  "postData" => [
127  "lgname" => $user->username,
128  "lgpassword" => $user->password
129  ]
130  ],
131  __METHOD__
132  );
133  $req->execute();
134 
135  libxml_use_internal_errors( true );
136  $sxe = simplexml_load_string( $req->getContent() );
137  $this->assertNotInternalType( "bool", $sxe );
138  $this->assertThat( $sxe, $this->isInstanceOf( "SimpleXMLElement" ) );
139  $this->assertNotInternalType( "null", $sxe->login[0] );
140 
141  $a = $sxe->login[0]->attributes()->result[0];
142  $this->assertEquals( ' result="NeedToken"', $a->asXML() );
143  $token = (string)$sxe->login[0]->attributes()->token;
144 
145  $req->setData( [
146  "lgtoken" => $token,
147  "lgname" => $user->username,
148  "lgpassword" => $user->password ] );
149  $req->execute();
150 
151  $cj = $req->getCookieJar();
152  $serverName = parse_url( $wgServer, PHP_URL_HOST );
153  $this->assertNotEquals( false, $serverName );
154  $serializedCookie = $cj->serializeToHttpRequest( $wgScriptPath, $serverName );
155  $this->assertNotEquals( '', $serializedCookie );
156  $this->assertRegExp(
157  '/_session=[^;]*; .*UserID=[0-9]*; .*UserName=' . $user->userName . '; .*Token=/',
158  $serializedCookie
159  );
160  }
161 
162  public function testRunLogin() {
163  $sysopUser = self::$users['sysop'];
164  $data = $this->doApiRequest( [
165  'action' => 'login',
166  'lgname' => $sysopUser->username,
167  'lgpassword' => $sysopUser->password ] );
168 
169  $this->assertArrayHasKey( "login", $data[0] );
170  $this->assertArrayHasKey( "result", $data[0]['login'] );
171  $this->assertEquals( "NeedToken", $data[0]['login']['result'] );
172  $token = $data[0]['login']['token'];
173 
174  $data = $this->doApiRequest( [
175  'action' => 'login',
176  "lgtoken" => $token,
177  "lgname" => $sysopUser->username,
178  "lgpassword" => $sysopUser->password ], $data[2] );
179 
180  $this->assertArrayHasKey( "login", $data[0] );
181  $this->assertArrayHasKey( "result", $data[0]['login'] );
182  $this->assertEquals( "Success", $data[0]['login']['result'] );
183  $this->assertArrayHasKey( 'lgtoken', $data[0]['login'] );
184  }
185 
186  public function testBotPassword() {
187  global $wgServer, $wgSessionProviders;
188 
189  if ( !isset( $wgServer ) ) {
190  $this->markTestIncomplete( 'This test needs $wgServer to be set in LocalSettings.php' );
191  }
192 
193  $this->setMwGlobals( [
194  'wgSessionProviders' => array_merge( $wgSessionProviders, [
195  [
196  'class' => MediaWiki\Session\BotPasswordSessionProvider::class,
197  'args' => [ [ 'priority' => 40 ] ],
198  ]
199  ] ),
200  'wgEnableBotPasswords' => true,
201  'wgBotPasswordsDatabase' => false,
202  'wgCentralIdLookupProvider' => 'local',
203  'wgGrantPermissions' => [
204  'test' => [ 'read' => true ],
205  ],
206  ] );
207 
208  // Make sure our session provider is present
209  $manager = TestingAccessWrapper::newFromObject( MediaWiki\Session\SessionManager::singleton() );
210  if ( !isset( $manager->sessionProviders[MediaWiki\Session\BotPasswordSessionProvider::class] ) ) {
211  $tmp = $manager->sessionProviders;
212  $manager->sessionProviders = null;
213  $manager->sessionProviders = $tmp + $manager->getProviders();
214  }
215  $this->assertNotNull(
216  MediaWiki\Session\SessionManager::singleton()->getProvider(
217  MediaWiki\Session\BotPasswordSessionProvider::class
218  ),
219  'sanity check'
220  );
221 
222  $user = self::$users['sysop'];
223  $centralId = CentralIdLookup::factory()->centralIdFromLocalUser( $user->getUser() );
224  $this->assertNotEquals( 0, $centralId, 'sanity check' );
225 
226  $passwordFactory = new PasswordFactory();
227  $passwordFactory->init( RequestContext::getMain()->getConfig() );
228  // A is unsalted MD5 (thus fast) ... we don't care about security here, this is test only
229  $passwordFactory->setDefaultType( 'A' );
230  $pwhash = $passwordFactory->newFromPlaintext( 'foobaz' );
231 
232  $dbw = wfGetDB( DB_MASTER );
233  $dbw->insert(
234  'bot_passwords',
235  [
236  'bp_user' => $centralId,
237  'bp_app_id' => 'foo',
238  'bp_password' => $pwhash->toString(),
239  'bp_token' => '',
240  'bp_restrictions' => MWRestrictions::newDefault()->toJson(),
241  'bp_grants' => '["test"]',
242  ],
243  __METHOD__
244  );
245 
246  $lgName = $user->username . BotPassword::getSeparator() . 'foo';
247 
248  $ret = $this->doApiRequest( [
249  'action' => 'login',
250  'lgname' => $lgName,
251  'lgpassword' => 'foobaz',
252  ] );
253 
254  $result = $ret[0];
255  $this->assertNotInternalType( 'bool', $result );
256  $this->assertNotInternalType( 'null', $result['login'] );
257 
258  $a = $result['login']['result'];
259  $this->assertEquals( 'NeedToken', $a );
260  $token = $result['login']['token'];
261 
262  $ret = $this->doApiRequest( [
263  'action' => 'login',
264  'lgtoken' => $token,
265  'lgname' => $lgName,
266  'lgpassword' => 'foobaz',
267  ], $ret[2] );
268 
269  $result = $ret[0];
270  $this->assertNotInternalType( 'bool', $result );
271  $a = $result['login']['result'];
272 
273  $this->assertEquals( 'Success', $a );
274  }
275 
276 }
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:1798
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
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':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:1796
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:965
doApiRequest(array $params, array $session=null, $appendModule=false, User $user=null)
Does the API request and returns the result.
Definition: ApiTestCase.php:86
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.
const DB_MASTER
Definition: Defines.php:47
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.