MediaWiki REL1_28
LegacyHookPreAuthenticationProviderTest.php
Go to the documentation of this file.
1<?php
2
3namespace MediaWiki\Auth;
4
15 protected function getProvider() {
16 $request = $this->getMock( 'FauxRequest', [ 'getIP' ] );
17 $request->expects( $this->any() )->method( 'getIP' )->will( $this->returnValue( '127.0.0.42' ) );
18
19 $manager = new AuthManager(
20 $request, \ConfigFactory::getDefaultInstance()->makeConfig( 'main' )
21 );
22
24 $provider->setManager( $manager );
25 $provider->setLogger( new \Psr\Log\NullLogger() );
26 $provider->setConfig( new \HashConfig( [
27 'PasswordAttemptThrottle' => [ 'count' => 23, 'seconds' => 42 ],
28 ] ) );
29 return $provider;
30 }
31
38 protected function hook( $hook, $expect ) {
39 $mock = $this->getMock( __CLASS__, [ "on$hook" ] );
40 $this->mergeMwGlobalArrayValue( 'wgHooks', [
41 $hook => [ $mock ],
42 ] );
43 return $mock->expects( $expect )->method( "on$hook" );
44 }
45
50 protected function unhook( $hook ) {
51 $this->mergeMwGlobalArrayValue( 'wgHooks', [
52 $hook => [],
53 ] );
54 }
55
56 // Stubs for hooks taking reference parameters
57 public function onLoginUserMigrated( $user, &$msg ) {
58 }
59 public function onAbortLogin( $user, $password, &$abort, &$msg ) {
60 }
61 public function onAbortNewAccount( $user, &$abortError, &$abortStatus ) {
62 }
63 public function onAbortAutoAccount( $user, &$abortError ) {
64 }
65
77 $username, $password,
78 $msgForLoginUserMigrated, $abortForAbortLogin, $msgForAbortLogin,
79 $failMsg, $failParams = []
80 ) {
81 $reqs = [];
82 if ( $username === null ) {
83 $this->hook( 'LoginUserMigrated', $this->never() );
84 $this->hook( 'AbortLogin', $this->never() );
85 } else {
86 if ( $password === null ) {
87 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
88 } else {
91 $req->password = $password;
92 }
93 $req->username = $username;
94 $reqs[get_class( $req )] = $req;
95
96 $h = $this->hook( 'LoginUserMigrated', $this->once() );
97 if ( $msgForLoginUserMigrated !== null ) {
98 $h->will( $this->returnCallback(
99 function ( $user, &$msg ) use ( $username, $msgForLoginUserMigrated ) {
100 $this->assertInstanceOf( 'User', $user );
101 $this->assertSame( $username, $user->getName() );
102 $msg = $msgForLoginUserMigrated;
103 return false;
104 }
105 ) );
106 $this->hook( 'AbortLogin', $this->never() );
107 } else {
108 $h->will( $this->returnCallback(
109 function ( $user, &$msg ) use ( $username ) {
110 $this->assertInstanceOf( 'User', $user );
111 $this->assertSame( $username, $user->getName() );
112 return true;
113 }
114 ) );
115 $h2 = $this->hook( 'AbortLogin', $this->once() );
116 if ( $abortForAbortLogin !== null ) {
117 $h2->will( $this->returnCallback(
118 function ( $user, $pass, &$abort, &$msg )
119 use ( $username, $password, $abortForAbortLogin, $msgForAbortLogin )
120 {
121 $this->assertInstanceOf( 'User', $user );
122 $this->assertSame( $username, $user->getName() );
123 if ( $password !== null ) {
124 $this->assertSame( $password, $pass );
125 } else {
126 $this->assertInternalType( 'string', $pass );
127 }
128 $abort = $abortForAbortLogin;
129 $msg = $msgForAbortLogin;
130 return false;
131 }
132 ) );
133 } else {
134 $h2->will( $this->returnCallback(
135 function ( $user, $pass, &$abort, &$msg ) use ( $username, $password ) {
136 $this->assertInstanceOf( 'User', $user );
137 $this->assertSame( $username, $user->getName() );
138 if ( $password !== null ) {
139 $this->assertSame( $password, $pass );
140 } else {
141 $this->assertInternalType( 'string', $pass );
142 }
143 return true;
144 }
145 ) );
146 }
147 }
148 }
149 unset( $h, $h2 );
150
151 $status = $this->getProvider()->testForAuthentication( $reqs );
152
153 $this->unhook( 'LoginUserMigrated' );
154 $this->unhook( 'AbortLogin' );
155
156 if ( $failMsg === null ) {
157 $this->assertEquals( \StatusValue::newGood(), $status, 'should succeed' );
158 } else {
159 $this->assertInstanceOf( 'StatusValue', $status, 'should fail (type)' );
160 $this->assertFalse( $status->isOk(), 'should fail (ok)' );
161 $errors = $status->getErrors();
162 $this->assertEquals( $failMsg, $errors[0]['message'], 'should fail (message)' );
163 $this->assertEquals( $failParams, $errors[0]['params'], 'should fail (params)' );
164 }
165 }
166
167 public static function provideTestForAuthentication() {
168 return [
169 'No valid requests' => [
170 null, null, null, null, null, null
171 ],
172 'No hook errors' => [
173 'User', 'PaSsWoRd', null, null, null, null
174 ],
175 'No hook errors, no password' => [
176 'User', null, null, null, null, null
177 ],
178 'LoginUserMigrated no message' => [
179 'User', 'PaSsWoRd', false, null, null, 'login-migrated-generic'
180 ],
181 'LoginUserMigrated with message' => [
182 'User', 'PaSsWoRd', 'LUM-abort', null, null, 'LUM-abort'
183 ],
184 'LoginUserMigrated with message and params' => [
185 'User', 'PaSsWoRd', [ 'LUM-abort', 'foo' ], null, null, 'LUM-abort', [ 'foo' ]
186 ],
187 'AbortLogin, SUCCESS' => [
188 'User', 'PaSsWoRd', null, \LoginForm::SUCCESS, null, null
189 ],
190 'AbortLogin, NEED_TOKEN, no message' => [
191 'User', 'PaSsWoRd', null, \LoginForm::NEED_TOKEN, null, 'nocookiesforlogin'
192 ],
193 'AbortLogin, NEED_TOKEN, with message' => [
194 'User', 'PaSsWoRd', null, \LoginForm::NEED_TOKEN, 'needtoken', 'needtoken'
195 ],
196 'AbortLogin, WRONG_TOKEN, no message' => [
197 'User', 'PaSsWoRd', null, \LoginForm::WRONG_TOKEN, null, 'sessionfailure'
198 ],
199 'AbortLogin, WRONG_TOKEN, with message' => [
200 'User', 'PaSsWoRd', null, \LoginForm::WRONG_TOKEN, 'wrongtoken', 'wrongtoken'
201 ],
202 'AbortLogin, ILLEGAL, no message' => [
203 'User', 'PaSsWoRd', null, \LoginForm::ILLEGAL, null, 'noname'
204 ],
205 'AbortLogin, ILLEGAL, with message' => [
206 'User', 'PaSsWoRd', null, \LoginForm::ILLEGAL, 'badname', 'badname'
207 ],
208 'AbortLogin, NO_NAME, no message' => [
209 'User', 'PaSsWoRd', null, \LoginForm::NO_NAME, null, 'noname'
210 ],
211 'AbortLogin, NO_NAME, with message' => [
212 'User', 'PaSsWoRd', null, \LoginForm::NO_NAME, 'badname', 'badname'
213 ],
214 'AbortLogin, WRONG_PASS, no message' => [
215 'User', 'PaSsWoRd', null, \LoginForm::WRONG_PASS, null, 'wrongpassword'
216 ],
217 'AbortLogin, WRONG_PASS, with message' => [
218 'User', 'PaSsWoRd', null, \LoginForm::WRONG_PASS, 'badpass', 'badpass'
219 ],
220 'AbortLogin, WRONG_PLUGIN_PASS, no message' => [
221 'User', 'PaSsWoRd', null, \LoginForm::WRONG_PLUGIN_PASS, null, 'wrongpassword'
222 ],
223 'AbortLogin, WRONG_PLUGIN_PASS, with message' => [
224 'User', 'PaSsWoRd', null, \LoginForm::WRONG_PLUGIN_PASS, 'badpass', 'badpass'
225 ],
226 'AbortLogin, NOT_EXISTS, no message' => [
227 "User'", 'A', null, \LoginForm::NOT_EXISTS, null, 'nosuchusershort', [ 'User&#39;' ]
228 ],
229 'AbortLogin, NOT_EXISTS, with message' => [
230 "User'", 'A', null, \LoginForm::NOT_EXISTS, 'badname', 'badname', [ 'User&#39;' ]
231 ],
232 'AbortLogin, EMPTY_PASS, no message' => [
233 'User', 'PaSsWoRd', null, \LoginForm::EMPTY_PASS, null, 'wrongpasswordempty'
234 ],
235 'AbortLogin, EMPTY_PASS, with message' => [
236 'User', 'PaSsWoRd', null, \LoginForm::EMPTY_PASS, 'badpass', 'badpass'
237 ],
238 'AbortLogin, RESET_PASS, no message' => [
239 'User', 'PaSsWoRd', null, \LoginForm::RESET_PASS, null, 'resetpass_announce'
240 ],
241 'AbortLogin, RESET_PASS, with message' => [
242 'User', 'PaSsWoRd', null, \LoginForm::RESET_PASS, 'resetpass', 'resetpass'
243 ],
244 'AbortLogin, THROTTLED, no message' => [
245 'User', 'PaSsWoRd', null, \LoginForm::THROTTLED, null, 'login-throttled',
246 [ \Message::durationParam( 42 ) ]
247 ],
248 'AbortLogin, THROTTLED, with message' => [
249 'User', 'PaSsWoRd', null, \LoginForm::THROTTLED, 't', 't',
250 [ \Message::durationParam( 42 ) ]
251 ],
252 'AbortLogin, USER_BLOCKED, no message' => [
253 "User'", 'P', null, \LoginForm::USER_BLOCKED, null, 'login-userblocked', [ 'User&#39;' ]
254 ],
255 'AbortLogin, USER_BLOCKED, with message' => [
256 "User'", 'P', null, \LoginForm::USER_BLOCKED, 'blocked', 'blocked', [ 'User&#39;' ]
257 ],
258 'AbortLogin, ABORTED, no message' => [
259 "User'", 'P', null, \LoginForm::ABORTED, null, 'login-abort-generic', [ 'User&#39;' ]
260 ],
261 'AbortLogin, ABORTED, with message' => [
262 "User'", 'P', null, \LoginForm::ABORTED, 'aborted', 'aborted', [ 'User&#39;' ]
263 ],
264 'AbortLogin, USER_MIGRATED, no message' => [
265 'User', 'P', null, \LoginForm::USER_MIGRATED, null, 'login-migrated-generic'
266 ],
267 'AbortLogin, USER_MIGRATED, with message' => [
268 'User', 'P', null, \LoginForm::USER_MIGRATED, 'migrated', 'migrated'
269 ],
270 'AbortLogin, USER_MIGRATED, with message and params' => [
271 'User', 'P', null, \LoginForm::USER_MIGRATED, [ 'migrated', 'foo' ],
272 'migrated', [ 'foo' ]
273 ],
274 ];
275 }
276
283 public function testTestForAccountCreation( $msg, $status, $result ) {
284 $this->hook( 'AbortNewAccount', $this->once() )
285 ->will( $this->returnCallback( function ( $user, &$error, &$abortStatus )
286 use ( $msg, $status )
287 {
288 $this->assertInstanceOf( 'User', $user );
289 $this->assertSame( 'User', $user->getName() );
290 $error = $msg;
291 $abortStatus = $status;
292 return $error === null && $status === null;
293 } ) );
294
295 $user = \User::newFromName( 'User' );
296 $creator = \User::newFromName( 'UTSysop' );
297 $ret = $this->getProvider()->testForAccountCreation( $user, $creator, [] );
298
299 $this->unhook( 'AbortNewAccount' );
300
301 $this->assertEquals( $result, $ret );
302 }
303
304 public static function provideTestForAccountCreation() {
305 return [
306 'No hook errors' => [
307 null, null, \StatusValue::newGood()
308 ],
309 'AbortNewAccount, old style' => [
310 'foobar', null, \StatusValue::newFatal(
311 \Message::newFromKey( 'createaccount-hook-aborted' )->rawParams( 'foobar' )
312 )
313 ],
314 'AbortNewAccount, new style' => [
315 'foobar',
316 \Status::newFatal( 'aborted!', 'param' ),
317 \StatusValue::newFatal( 'aborted!', 'param' )
318 ],
319 ];
320 }
321
327 public function testTestUserForCreation( $error, $failMsg ) {
328 $testUser = self::getTestUser()->getUser();
329 $provider = $this->getProvider();
330 $options = [ 'flags' => \User::READ_LOCKING, 'creating' => true ];
331
332 $this->hook( 'AbortNewAccount', $this->never() );
333 $this->hook( 'AbortAutoAccount', $this->once() )
334 ->will( $this->returnCallback( function ( $user, &$abortError ) use ( $testUser, $error ) {
335 $this->assertInstanceOf( 'User', $user );
336 $this->assertSame( $testUser->getName(), $user->getName() );
337 $abortError = $error;
338 return $error === null;
339 } ) );
340 $status = $provider->testUserForCreation(
342 );
343 $this->unhook( 'AbortNewAccount' );
344 $this->unhook( 'AbortAutoAccount' );
345 if ( $failMsg === null ) {
346 $this->assertEquals( \StatusValue::newGood(), $status, 'should succeed' );
347 } else {
348 $this->assertInstanceOf( 'StatusValue', $status, 'should fail (type)' );
349 $this->assertFalse( $status->isOk(), 'should fail (ok)' );
350 $errors = $status->getErrors();
351 $this->assertEquals( $failMsg, $errors[0]['message'], 'should fail (message)' );
352 }
353
354 $this->hook( 'AbortAutoAccount', $this->never() );
355 $this->hook( 'AbortNewAccount', $this->never() );
356 $status = $provider->testUserForCreation( $testUser, false, $options );
357 $this->unhook( 'AbortNewAccount' );
358 $this->unhook( 'AbortAutoAccount' );
359 $this->assertEquals( \StatusValue::newGood(), $status, 'should succeed' );
360 }
361
362 public static function provideTestUserForCreation() {
363 return [
364 'Success' => [ null, null ],
365 'Fail, no message' => [ false, 'login-abort-generic' ],
366 'Fail, with message' => [ 'fail', 'fail' ],
367 ];
368 }
369}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static getDefaultInstance()
A Config instance which stores all settings as a member variable.
mergeMwGlobalArrayValue( $name, $values)
Merges the given values into a MW global array variable.
static getTestUser( $groups=[])
Convenience method for getting an immutable test user.
This serves as the entry point to the authentication system.
const AUTOCREATE_SOURCE_SESSION
Auto-creation is due to SessionManager.
const ACTION_LOGIN
Log in with an existing (not necessarily local) user.
AuthManager Database MediaWiki\Auth\LegacyHookPreAuthenticationProvider.
testTestForAuthentication( $username, $password, $msgForLoginUserMigrated, $abortForAbortLogin, $msgForAbortLogin, $failMsg, $failParams=[])
provideTestForAuthentication
testTestForAccountCreation( $msg, $status, $result)
provideTestForAccountCreation
A pre-authentication provider to call some legacy hooks.
This is a value object for authentication requests with a username and password.
this hook is for auditing only $req
Definition hooks.txt:1010
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition hooks.txt:1049
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:249
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:1937
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition hooks.txt:1096
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:1950
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition hooks.txt:2685
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:1949
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:807
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:37