Include IP address in "Login for $1 succeeded" log entry
[lhc/web/wiklou.git] / includes / auth / AuthManager.php
1 <?php
2 /**
3 * Authentication (and possibly Authorization in the future) system entry point
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Auth
22 */
23
24 namespace MediaWiki\Auth;
25
26 use Config;
27 use MediaWiki\MediaWikiServices;
28 use Psr\Log\LoggerAwareInterface;
29 use Psr\Log\LoggerInterface;
30 use Status;
31 use StatusValue;
32 use User;
33 use WebRequest;
34 use Wikimedia\ObjectFactory;
35
36 /**
37 * This serves as the entry point to the authentication system.
38 *
39 * In the future, it may also serve as the entry point to the authorization
40 * system.
41 *
42 * If you are looking at this because you are working on an extension that creates its own
43 * login or signup page, then 1) you really shouldn't do that, 2) if you feel you absolutely
44 * have to, subclass AuthManagerSpecialPage or build it on the client side using the clientlogin
45 * or the createaccount API. Trying to call this class directly will very likely end up in
46 * security vulnerabilities or broken UX in edge cases.
47 *
48 * If you are working on an extension that needs to integrate with the authentication system
49 * (e.g. by providing a new login method, or doing extra permission checks), you'll probably
50 * need to write an AuthenticationProvider.
51 *
52 * If you want to create a "reserved" user programmatically, User::newSystemUser() might be what
53 * you are looking for. If you want to change user data, use User::changeAuthenticationData().
54 * Code that is related to some SessionProvider or PrimaryAuthenticationProvider can
55 * create a (non-reserved) user by calling AuthManager::autoCreateUser(); it is then the provider's
56 * responsibility to ensure that the user can authenticate somehow (see especially
57 * PrimaryAuthenticationProvider::autoCreatedAccount()).
58 * If you are writing code that is not associated with such a provider and needs to create accounts
59 * programmatically for real users, you should rethink your architecture. There is no good way to
60 * do that as such code has no knowledge of what authentication methods are enabled on the wiki and
61 * cannot provide any means for users to access the accounts it would create.
62 *
63 * The two main control flows when using this class are as follows:
64 * * Login, user creation or account linking code will call getAuthenticationRequests(), populate
65 * the requests with data (by using them to build a HTMLForm and have the user fill it, or by
66 * exposing a form specification via the API, so that the client can build it), and pass them to
67 * the appropriate begin* method. That will return either a success/failure response, or more
68 * requests to fill (either by building a form or by redirecting the user to some external
69 * provider which will send the data back), in which case they need to be submitted to the
70 * appropriate continue* method and that step has to be repeated until the response is a success
71 * or failure response. AuthManager will use the session to maintain internal state during the
72 * process.
73 * * Code doing an authentication data change will call getAuthenticationRequests(), select
74 * a single request, populate it, and pass it to allowsAuthenticationDataChange() and then
75 * changeAuthenticationData(). If the data change is user-initiated, the whole process needs
76 * to be preceded by a call to securitySensitiveOperationStatus() and aborted if that returns
77 * a non-OK status.
78 *
79 * @ingroup Auth
80 * @since 1.27
81 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
82 */
83 class AuthManager implements LoggerAwareInterface {
84 /** Log in with an existing (not necessarily local) user */
85 const ACTION_LOGIN = 'login';
86 /** Continue a login process that was interrupted by the need for user input or communication
87 * with an external provider */
88 const ACTION_LOGIN_CONTINUE = 'login-continue';
89 /** Create a new user */
90 const ACTION_CREATE = 'create';
91 /** Continue a user creation process that was interrupted by the need for user input or
92 * communication with an external provider */
93 const ACTION_CREATE_CONTINUE = 'create-continue';
94 /** Link an existing user to a third-party account */
95 const ACTION_LINK = 'link';
96 /** Continue a user linking process that was interrupted by the need for user input or
97 * communication with an external provider */
98 const ACTION_LINK_CONTINUE = 'link-continue';
99 /** Change a user's credentials */
100 const ACTION_CHANGE = 'change';
101 /** Remove a user's credentials */
102 const ACTION_REMOVE = 'remove';
103 /** Like ACTION_REMOVE but for linking providers only */
104 const ACTION_UNLINK = 'unlink';
105
106 /** Security-sensitive operations are ok. */
107 const SEC_OK = 'ok';
108 /** Security-sensitive operations should re-authenticate. */
109 const SEC_REAUTH = 'reauth';
110 /** Security-sensitive should not be performed. */
111 const SEC_FAIL = 'fail';
112
113 /** Auto-creation is due to SessionManager */
114 const AUTOCREATE_SOURCE_SESSION = \MediaWiki\Session\SessionManager::class;
115
116 /** @var AuthManager|null */
117 private static $instance = null;
118
119 /** @var WebRequest */
120 private $request;
121
122 /** @var Config */
123 private $config;
124
125 /** @var LoggerInterface */
126 private $logger;
127
128 /** @var AuthenticationProvider[] */
129 private $allAuthenticationProviders = [];
130
131 /** @var PreAuthenticationProvider[] */
132 private $preAuthenticationProviders = null;
133
134 /** @var PrimaryAuthenticationProvider[] */
135 private $primaryAuthenticationProviders = null;
136
137 /** @var SecondaryAuthenticationProvider[] */
138 private $secondaryAuthenticationProviders = null;
139
140 /** @var CreatedAccountAuthenticationRequest[] */
141 private $createdAccountAuthenticationRequests = [];
142
143 /**
144 * Get the global AuthManager
145 * @return AuthManager
146 */
147 public static function singleton() {
148 if ( self::$instance === null ) {
149 self::$instance = new self(
150 \RequestContext::getMain()->getRequest(),
151 MediaWikiServices::getInstance()->getMainConfig()
152 );
153 }
154 return self::$instance;
155 }
156
157 /**
158 * @param WebRequest $request
159 * @param Config $config
160 */
161 public function __construct( WebRequest $request, Config $config ) {
162 $this->request = $request;
163 $this->config = $config;
164 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' ) );
165 }
166
167 /**
168 * @param LoggerInterface $logger
169 */
170 public function setLogger( LoggerInterface $logger ) {
171 $this->logger = $logger;
172 }
173
174 /**
175 * @return WebRequest
176 */
177 public function getRequest() {
178 return $this->request;
179 }
180
181 /**
182 * Force certain PrimaryAuthenticationProviders
183 * @deprecated For backwards compatibility only
184 * @param PrimaryAuthenticationProvider[] $providers
185 * @param string $why
186 */
187 public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
188 $this->logger->warning( "Overriding AuthManager primary authn because $why" );
189
190 if ( $this->primaryAuthenticationProviders !== null ) {
191 $this->logger->warning(
192 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
193 );
194
195 $this->allAuthenticationProviders = array_diff_key(
196 $this->allAuthenticationProviders,
197 $this->primaryAuthenticationProviders
198 );
199 $session = $this->request->getSession();
200 $session->remove( 'AuthManager::authnState' );
201 $session->remove( 'AuthManager::accountCreationState' );
202 $session->remove( 'AuthManager::accountLinkState' );
203 $this->createdAccountAuthenticationRequests = [];
204 }
205
206 $this->primaryAuthenticationProviders = [];
207 foreach ( $providers as $provider ) {
208 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
209 throw new \RuntimeException(
210 'Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got ' .
211 get_class( $provider )
212 );
213 }
214 $provider->setLogger( $this->logger );
215 $provider->setManager( $this );
216 $provider->setConfig( $this->config );
217 $id = $provider->getUniqueId();
218 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
219 throw new \RuntimeException(
220 "Duplicate specifications for id $id (classes " .
221 get_class( $provider ) . ' and ' .
222 get_class( $this->allAuthenticationProviders[$id] ) . ')'
223 );
224 }
225 $this->allAuthenticationProviders[$id] = $provider;
226 $this->primaryAuthenticationProviders[$id] = $provider;
227 }
228 }
229
230 /**
231 * Call a legacy AuthPlugin method, if necessary
232 * @codeCoverageIgnore
233 * @deprecated For backwards compatibility only, should be avoided in new code
234 * @param string $method AuthPlugin method to call
235 * @param array $params Parameters to pass
236 * @param mixed $return Return value if AuthPlugin wasn't called
237 * @return mixed Return value from the AuthPlugin method, or $return
238 */
239 public static function callLegacyAuthPlugin( $method, array $params, $return = null ) {
240 global $wgAuth;
241
242 if ( $wgAuth && !$wgAuth instanceof AuthManagerAuthPlugin ) {
243 return call_user_func_array( [ $wgAuth, $method ], $params );
244 } else {
245 return $return;
246 }
247 }
248
249 /**
250 * @name Authentication
251 * @{
252 */
253
254 /**
255 * Indicate whether user authentication is possible
256 *
257 * It may not be if the session is provided by something like OAuth
258 * for which each individual request includes authentication data.
259 *
260 * @return bool
261 */
262 public function canAuthenticateNow() {
263 return $this->request->getSession()->canSetUser();
264 }
265
266 /**
267 * Start an authentication flow
268 *
269 * In addition to the AuthenticationRequests returned by
270 * $this->getAuthenticationRequests(), a client might include a
271 * CreateFromLoginAuthenticationRequest from a previous login attempt to
272 * preserve state.
273 *
274 * Instead of the AuthenticationRequests returned by
275 * $this->getAuthenticationRequests(), a client might pass a
276 * CreatedAccountAuthenticationRequest from an account creation that just
277 * succeeded to log in to the just-created account.
278 *
279 * @param AuthenticationRequest[] $reqs
280 * @param string $returnToUrl Url that REDIRECT responses should eventually
281 * return to.
282 * @return AuthenticationResponse See self::continueAuthentication()
283 */
284 public function beginAuthentication( array $reqs, $returnToUrl ) {
285 $session = $this->request->getSession();
286 if ( !$session->canSetUser() ) {
287 // Caller should have called canAuthenticateNow()
288 $session->remove( 'AuthManager::authnState' );
289 throw new \LogicException( 'Authentication is not possible now' );
290 }
291
292 $guessUserName = null;
293 foreach ( $reqs as $req ) {
294 $req->returnToUrl = $returnToUrl;
295 // @codeCoverageIgnoreStart
296 if ( $req->username !== null && $req->username !== '' ) {
297 if ( $guessUserName === null ) {
298 $guessUserName = $req->username;
299 } elseif ( $guessUserName !== $req->username ) {
300 $guessUserName = null;
301 break;
302 }
303 }
304 // @codeCoverageIgnoreEnd
305 }
306
307 // Check for special-case login of a just-created account
308 $req = AuthenticationRequest::getRequestByClass(
309 $reqs, CreatedAccountAuthenticationRequest::class
310 );
311 if ( $req ) {
312 if ( !in_array( $req, $this->createdAccountAuthenticationRequests, true ) ) {
313 throw new \LogicException(
314 'CreatedAccountAuthenticationRequests are only valid on ' .
315 'the same AuthManager that created the account'
316 );
317 }
318
319 $user = User::newFromName( $req->username );
320 // @codeCoverageIgnoreStart
321 if ( !$user ) {
322 throw new \UnexpectedValueException(
323 "CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
324 );
325 } elseif ( $user->getId() != $req->id ) {
326 throw new \UnexpectedValueException(
327 "ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
328 );
329 }
330 // @codeCoverageIgnoreEnd
331
332 $this->logger->info( 'Logging in {user} after account creation', [
333 'user' => $user->getName(),
334 ] );
335 $ret = AuthenticationResponse::newPass( $user->getName() );
336 $this->setSessionDataForUser( $user );
337 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
338 $session->remove( 'AuthManager::authnState' );
339 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
340 return $ret;
341 }
342
343 $this->removeAuthenticationSessionData( null );
344
345 foreach ( $this->getPreAuthenticationProviders() as $provider ) {
346 $status = $provider->testForAuthentication( $reqs );
347 if ( !$status->isGood() ) {
348 $this->logger->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
349 $ret = AuthenticationResponse::newFail(
350 Status::wrap( $status )->getMessage()
351 );
352 $this->callMethodOnProviders( 7, 'postAuthentication',
353 [ User::newFromName( $guessUserName ) ?: null, $ret ]
354 );
355 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, null, $guessUserName ] );
356 return $ret;
357 }
358 }
359
360 $state = [
361 'reqs' => $reqs,
362 'returnToUrl' => $returnToUrl,
363 'guessUserName' => $guessUserName,
364 'primary' => null,
365 'primaryResponse' => null,
366 'secondary' => [],
367 'maybeLink' => [],
368 'continueRequests' => [],
369 ];
370
371 // Preserve state from a previous failed login
372 $req = AuthenticationRequest::getRequestByClass(
373 $reqs, CreateFromLoginAuthenticationRequest::class
374 );
375 if ( $req ) {
376 $state['maybeLink'] = $req->maybeLink;
377 }
378
379 $session = $this->request->getSession();
380 $session->setSecret( 'AuthManager::authnState', $state );
381 $session->persist();
382
383 return $this->continueAuthentication( $reqs );
384 }
385
386 /**
387 * Continue an authentication flow
388 *
389 * Return values are interpreted as follows:
390 * - status FAIL: Authentication failed. If $response->createRequest is
391 * set, that may be passed to self::beginAuthentication() or to
392 * self::beginAccountCreation() to preserve state.
393 * - status REDIRECT: The client should be redirected to the contained URL,
394 * new AuthenticationRequests should be made (if any), then
395 * AuthManager::continueAuthentication() should be called.
396 * - status UI: The client should be presented with a user interface for
397 * the fields in the specified AuthenticationRequests, then new
398 * AuthenticationRequests should be made, then
399 * AuthManager::continueAuthentication() should be called.
400 * - status RESTART: The user logged in successfully with a third-party
401 * service, but the third-party credentials aren't attached to any local
402 * account. This could be treated as a UI or a FAIL.
403 * - status PASS: Authentication was successful.
404 *
405 * @param AuthenticationRequest[] $reqs
406 * @return AuthenticationResponse
407 */
408 public function continueAuthentication( array $reqs ) {
409 $session = $this->request->getSession();
410 try {
411 if ( !$session->canSetUser() ) {
412 // Caller should have called canAuthenticateNow()
413 // @codeCoverageIgnoreStart
414 throw new \LogicException( 'Authentication is not possible now' );
415 // @codeCoverageIgnoreEnd
416 }
417
418 $state = $session->getSecret( 'AuthManager::authnState' );
419 if ( !is_array( $state ) ) {
420 return AuthenticationResponse::newFail(
421 wfMessage( 'authmanager-authn-not-in-progress' )
422 );
423 }
424 $state['continueRequests'] = [];
425
426 $guessUserName = $state['guessUserName'];
427
428 foreach ( $reqs as $req ) {
429 $req->returnToUrl = $state['returnToUrl'];
430 }
431
432 // Step 1: Choose an primary authentication provider, and call it until it succeeds.
433
434 if ( $state['primary'] === null ) {
435 // We haven't picked a PrimaryAuthenticationProvider yet
436 // @codeCoverageIgnoreStart
437 $guessUserName = null;
438 foreach ( $reqs as $req ) {
439 if ( $req->username !== null && $req->username !== '' ) {
440 if ( $guessUserName === null ) {
441 $guessUserName = $req->username;
442 } elseif ( $guessUserName !== $req->username ) {
443 $guessUserName = null;
444 break;
445 }
446 }
447 }
448 $state['guessUserName'] = $guessUserName;
449 // @codeCoverageIgnoreEnd
450 $state['reqs'] = $reqs;
451
452 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
453 $res = $provider->beginPrimaryAuthentication( $reqs );
454 switch ( $res->status ) {
455 case AuthenticationResponse::PASS;
456 $state['primary'] = $id;
457 $state['primaryResponse'] = $res;
458 $this->logger->debug( "Primary login with $id succeeded" );
459 break 2;
460 case AuthenticationResponse::FAIL;
461 $this->logger->debug( "Login failed in primary authentication by $id" );
462 if ( $res->createRequest || $state['maybeLink'] ) {
463 $res->createRequest = new CreateFromLoginAuthenticationRequest(
464 $res->createRequest, $state['maybeLink']
465 );
466 }
467 $this->callMethodOnProviders( 7, 'postAuthentication',
468 [ User::newFromName( $guessUserName ) ?: null, $res ]
469 );
470 $session->remove( 'AuthManager::authnState' );
471 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
472 return $res;
473 case AuthenticationResponse::ABSTAIN;
474 // Continue loop
475 break;
476 case AuthenticationResponse::REDIRECT;
477 case AuthenticationResponse::UI;
478 $this->logger->debug( "Primary login with $id returned $res->status" );
479 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
480 $state['primary'] = $id;
481 $state['continueRequests'] = $res->neededRequests;
482 $session->setSecret( 'AuthManager::authnState', $state );
483 return $res;
484
485 // @codeCoverageIgnoreStart
486 default:
487 throw new \DomainException(
488 get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
489 );
490 // @codeCoverageIgnoreEnd
491 }
492 }
493 if ( $state['primary'] === null ) {
494 $this->logger->debug( 'Login failed in primary authentication because no provider accepted' );
495 $ret = AuthenticationResponse::newFail(
496 wfMessage( 'authmanager-authn-no-primary' )
497 );
498 $this->callMethodOnProviders( 7, 'postAuthentication',
499 [ User::newFromName( $guessUserName ) ?: null, $ret ]
500 );
501 $session->remove( 'AuthManager::authnState' );
502 return $ret;
503 }
504 } elseif ( $state['primaryResponse'] === null ) {
505 $provider = $this->getAuthenticationProvider( $state['primary'] );
506 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
507 // Configuration changed? Force them to start over.
508 // @codeCoverageIgnoreStart
509 $ret = AuthenticationResponse::newFail(
510 wfMessage( 'authmanager-authn-not-in-progress' )
511 );
512 $this->callMethodOnProviders( 7, 'postAuthentication',
513 [ User::newFromName( $guessUserName ) ?: null, $ret ]
514 );
515 $session->remove( 'AuthManager::authnState' );
516 return $ret;
517 // @codeCoverageIgnoreEnd
518 }
519 $id = $provider->getUniqueId();
520 $res = $provider->continuePrimaryAuthentication( $reqs );
521 switch ( $res->status ) {
522 case AuthenticationResponse::PASS;
523 $state['primaryResponse'] = $res;
524 $this->logger->debug( "Primary login with $id succeeded" );
525 break;
526 case AuthenticationResponse::FAIL;
527 $this->logger->debug( "Login failed in primary authentication by $id" );
528 if ( $res->createRequest || $state['maybeLink'] ) {
529 $res->createRequest = new CreateFromLoginAuthenticationRequest(
530 $res->createRequest, $state['maybeLink']
531 );
532 }
533 $this->callMethodOnProviders( 7, 'postAuthentication',
534 [ User::newFromName( $guessUserName ) ?: null, $res ]
535 );
536 $session->remove( 'AuthManager::authnState' );
537 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, null, $guessUserName ] );
538 return $res;
539 case AuthenticationResponse::REDIRECT;
540 case AuthenticationResponse::UI;
541 $this->logger->debug( "Primary login with $id returned $res->status" );
542 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
543 $state['continueRequests'] = $res->neededRequests;
544 $session->setSecret( 'AuthManager::authnState', $state );
545 return $res;
546 default:
547 throw new \DomainException(
548 get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
549 );
550 }
551 }
552
553 $res = $state['primaryResponse'];
554 if ( $res->username === null ) {
555 $provider = $this->getAuthenticationProvider( $state['primary'] );
556 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
557 // Configuration changed? Force them to start over.
558 // @codeCoverageIgnoreStart
559 $ret = AuthenticationResponse::newFail(
560 wfMessage( 'authmanager-authn-not-in-progress' )
561 );
562 $this->callMethodOnProviders( 7, 'postAuthentication',
563 [ User::newFromName( $guessUserName ) ?: null, $ret ]
564 );
565 $session->remove( 'AuthManager::authnState' );
566 return $ret;
567 // @codeCoverageIgnoreEnd
568 }
569
570 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK &&
571 $res->linkRequest &&
572 // don't confuse the user with an incorrect message if linking is disabled
573 $this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider::class )
574 ) {
575 $state['maybeLink'][$res->linkRequest->getUniqueId()] = $res->linkRequest;
576 $msg = 'authmanager-authn-no-local-user-link';
577 } else {
578 $msg = 'authmanager-authn-no-local-user';
579 }
580 $this->logger->debug(
581 "Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
582 );
583 $ret = AuthenticationResponse::newRestart( wfMessage( $msg ) );
584 $ret->neededRequests = $this->getAuthenticationRequestsInternal(
585 self::ACTION_LOGIN,
586 [],
587 $this->getPrimaryAuthenticationProviders() + $this->getSecondaryAuthenticationProviders()
588 );
589 if ( $res->createRequest || $state['maybeLink'] ) {
590 $ret->createRequest = new CreateFromLoginAuthenticationRequest(
591 $res->createRequest, $state['maybeLink']
592 );
593 $ret->neededRequests[] = $ret->createRequest;
594 }
595 $this->fillRequests( $ret->neededRequests, self::ACTION_LOGIN, null, true );
596 $session->setSecret( 'AuthManager::authnState', [
597 'reqs' => [], // Will be filled in later
598 'primary' => null,
599 'primaryResponse' => null,
600 'secondary' => [],
601 'continueRequests' => $ret->neededRequests,
602 ] + $state );
603 return $ret;
604 }
605
606 // Step 2: Primary authentication succeeded, create the User object
607 // (and add the user locally if necessary)
608
609 $user = User::newFromName( $res->username, 'usable' );
610 if ( !$user ) {
611 $provider = $this->getAuthenticationProvider( $state['primary'] );
612 throw new \DomainException(
613 get_class( $provider ) . " returned an invalid username: {$res->username}"
614 );
615 }
616 if ( $user->getId() === 0 ) {
617 // User doesn't exist locally. Create it.
618 $this->logger->info( 'Auto-creating {user} on login', [
619 'user' => $user->getName(),
620 ] );
621 $status = $this->autoCreateUser( $user, $state['primary'], false );
622 if ( !$status->isGood() ) {
623 $ret = AuthenticationResponse::newFail(
624 Status::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
625 );
626 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
627 $session->remove( 'AuthManager::authnState' );
628 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
629 return $ret;
630 }
631 }
632
633 // Step 3: Iterate over all the secondary authentication providers.
634
635 $beginReqs = $state['reqs'];
636
637 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
638 if ( !isset( $state['secondary'][$id] ) ) {
639 // This provider isn't started yet, so we pass it the set
640 // of reqs from beginAuthentication instead of whatever
641 // might have been used by a previous provider in line.
642 $func = 'beginSecondaryAuthentication';
643 $res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
644 } elseif ( !$state['secondary'][$id] ) {
645 $func = 'continueSecondaryAuthentication';
646 $res = $provider->continueSecondaryAuthentication( $user, $reqs );
647 } else {
648 continue;
649 }
650 switch ( $res->status ) {
651 case AuthenticationResponse::PASS;
652 $this->logger->debug( "Secondary login with $id succeeded" );
653 // fall through
654 case AuthenticationResponse::ABSTAIN;
655 $state['secondary'][$id] = true;
656 break;
657 case AuthenticationResponse::FAIL;
658 $this->logger->debug( "Login failed in secondary authentication by $id" );
659 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $res ] );
660 $session->remove( 'AuthManager::authnState' );
661 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $res, $user, $user->getName() ] );
662 return $res;
663 case AuthenticationResponse::REDIRECT;
664 case AuthenticationResponse::UI;
665 $this->logger->debug( "Secondary login with $id returned " . $res->status );
666 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $user->getName() );
667 $state['secondary'][$id] = false;
668 $state['continueRequests'] = $res->neededRequests;
669 $session->setSecret( 'AuthManager::authnState', $state );
670 return $res;
671
672 // @codeCoverageIgnoreStart
673 default:
674 throw new \DomainException(
675 get_class( $provider ) . "::{$func}() returned $res->status"
676 );
677 // @codeCoverageIgnoreEnd
678 }
679 }
680
681 // Step 4: Authentication complete! Set the user in the session and
682 // clean up.
683
684 $this->logger->info( 'Login for {user} succeeded from {clientip}', [
685 'user' => $user->getName(),
686 'clientip' => $this->request->getIP(),
687 ] );
688 /** @var RememberMeAuthenticationRequest $req */
689 $req = AuthenticationRequest::getRequestByClass(
690 $beginReqs, RememberMeAuthenticationRequest::class
691 );
692 $this->setSessionDataForUser( $user, $req && $req->rememberMe );
693 $ret = AuthenticationResponse::newPass( $user->getName() );
694 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
695 $session->remove( 'AuthManager::authnState' );
696 $this->removeAuthenticationSessionData( null );
697 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
698 return $ret;
699 } catch ( \Exception $ex ) {
700 $session->remove( 'AuthManager::authnState' );
701 throw $ex;
702 }
703 }
704
705 /**
706 * Whether security-sensitive operations should proceed.
707 *
708 * A "security-sensitive operation" is something like a password or email
709 * change, that would normally have a "reenter your password to confirm"
710 * box if we only supported password-based authentication.
711 *
712 * @param string $operation Operation being checked. This should be a
713 * message-key-like string such as 'change-password' or 'change-email'.
714 * @return string One of the SEC_* constants.
715 */
716 public function securitySensitiveOperationStatus( $operation ) {
717 $status = self::SEC_OK;
718
719 $this->logger->debug( __METHOD__ . ": Checking $operation" );
720
721 $session = $this->request->getSession();
722 $aId = $session->getUser()->getId();
723 if ( $aId === 0 ) {
724 // User isn't authenticated. DWIM?
725 $status = $this->canAuthenticateNow() ? self::SEC_REAUTH : self::SEC_FAIL;
726 $this->logger->info( __METHOD__ . ": Not logged in! $operation is $status" );
727 return $status;
728 }
729
730 if ( $session->canSetUser() ) {
731 $id = $session->get( 'AuthManager:lastAuthId' );
732 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
733 if ( $id !== $aId || $last === null ) {
734 $timeSinceLogin = PHP_INT_MAX; // Forever ago
735 } else {
736 $timeSinceLogin = max( 0, time() - $last );
737 }
738
739 $thresholds = $this->config->get( 'ReauthenticateTime' );
740 if ( isset( $thresholds[$operation] ) ) {
741 $threshold = $thresholds[$operation];
742 } elseif ( isset( $thresholds['default'] ) ) {
743 $threshold = $thresholds['default'];
744 } else {
745 throw new \UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
746 }
747
748 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
749 $status = self::SEC_REAUTH;
750 }
751 } else {
752 $timeSinceLogin = -1;
753
754 $pass = $this->config->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
755 if ( isset( $pass[$operation] ) ) {
756 $status = $pass[$operation] ? self::SEC_OK : self::SEC_FAIL;
757 } elseif ( isset( $pass['default'] ) ) {
758 $status = $pass['default'] ? self::SEC_OK : self::SEC_FAIL;
759 } else {
760 throw new \UnexpectedValueException(
761 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
762 );
763 }
764 }
765
766 \Hooks::run( 'SecuritySensitiveOperationStatus', [
767 &$status, $operation, $session, $timeSinceLogin
768 ] );
769
770 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
771 if ( !$this->canAuthenticateNow() && $status === self::SEC_REAUTH ) {
772 $status = self::SEC_FAIL;
773 }
774
775 $this->logger->info( __METHOD__ . ": $operation is $status" );
776
777 return $status;
778 }
779
780 /**
781 * Determine whether a username can authenticate
782 *
783 * This is mainly for internal purposes and only takes authentication data into account,
784 * not things like blocks that can change without the authentication system being aware.
785 *
786 * @param string $username MediaWiki username
787 * @return bool
788 */
789 public function userCanAuthenticate( $username ) {
790 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
791 if ( $provider->testUserCanAuthenticate( $username ) ) {
792 return true;
793 }
794 }
795 return false;
796 }
797
798 /**
799 * Provide normalized versions of the username for security checks
800 *
801 * Since different providers can normalize the input in different ways,
802 * this returns an array of all the different ways the name might be
803 * normalized for authentication.
804 *
805 * The returned strings should not be revealed to the user, as that might
806 * leak private information (e.g. an email address might be normalized to a
807 * username).
808 *
809 * @param string $username
810 * @return string[]
811 */
812 public function normalizeUsername( $username ) {
813 $ret = [];
814 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
815 $normalized = $provider->providerNormalizeUsername( $username );
816 if ( $normalized !== null ) {
817 $ret[$normalized] = true;
818 }
819 }
820 return array_keys( $ret );
821 }
822
823 /**@}*/
824
825 /**
826 * @name Authentication data changing
827 * @{
828 */
829
830 /**
831 * Revoke any authentication credentials for a user
832 *
833 * After this, the user should no longer be able to log in.
834 *
835 * @param string $username
836 */
837 public function revokeAccessForUser( $username ) {
838 $this->logger->info( 'Revoking access for {user}', [
839 'user' => $username,
840 ] );
841 $this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
842 }
843
844 /**
845 * Validate a change of authentication data (e.g. passwords)
846 * @param AuthenticationRequest $req
847 * @param bool $checkData If false, $req hasn't been loaded from the
848 * submission so checks on user-submitted fields should be skipped. $req->username is
849 * considered user-submitted for this purpose, even if it cannot be changed via
850 * $req->loadFromSubmission.
851 * @return Status
852 */
853 public function allowsAuthenticationDataChange( AuthenticationRequest $req, $checkData = true ) {
854 $any = false;
855 $providers = $this->getPrimaryAuthenticationProviders() +
856 $this->getSecondaryAuthenticationProviders();
857 foreach ( $providers as $provider ) {
858 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
859 if ( !$status->isGood() ) {
860 return Status::wrap( $status );
861 }
862 $any = $any || $status->value !== 'ignored';
863 }
864 if ( !$any ) {
865 $status = Status::newGood( 'ignored' );
866 $status->warning( 'authmanager-change-not-supported' );
867 return $status;
868 }
869 return Status::newGood();
870 }
871
872 /**
873 * Change authentication data (e.g. passwords)
874 *
875 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
876 * result in a successful login in the future.
877 *
878 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
879 * no longer result in a successful login.
880 *
881 * This method should only be called if allowsAuthenticationDataChange( $req, true )
882 * returned success.
883 *
884 * @param AuthenticationRequest $req
885 */
886 public function changeAuthenticationData( AuthenticationRequest $req ) {
887 $this->logger->info( 'Changing authentication data for {user} class {what}', [
888 'user' => is_string( $req->username ) ? $req->username : '<no name>',
889 'what' => get_class( $req ),
890 ] );
891
892 $this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
893
894 // When the main account's authentication data is changed, invalidate
895 // all BotPasswords too.
896 \BotPassword::invalidateAllPasswordsForUser( $req->username );
897 }
898
899 /**@}*/
900
901 /**
902 * @name Account creation
903 * @{
904 */
905
906 /**
907 * Determine whether accounts can be created
908 * @return bool
909 */
910 public function canCreateAccounts() {
911 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
912 switch ( $provider->accountCreationType() ) {
913 case PrimaryAuthenticationProvider::TYPE_CREATE:
914 case PrimaryAuthenticationProvider::TYPE_LINK:
915 return true;
916 }
917 }
918 return false;
919 }
920
921 /**
922 * Determine whether a particular account can be created
923 * @param string $username MediaWiki username
924 * @param array $options
925 * - flags: (int) Bitfield of User:READ_* constants, default User::READ_NORMAL
926 * - creating: (bool) For internal use only. Never specify this.
927 * @return Status
928 */
929 public function canCreateAccount( $username, $options = [] ) {
930 // Back compat
931 if ( is_int( $options ) ) {
932 $options = [ 'flags' => $options ];
933 }
934 $options += [
935 'flags' => User::READ_NORMAL,
936 'creating' => false,
937 ];
938 $flags = $options['flags'];
939
940 if ( !$this->canCreateAccounts() ) {
941 return Status::newFatal( 'authmanager-create-disabled' );
942 }
943
944 if ( $this->userExists( $username, $flags ) ) {
945 return Status::newFatal( 'userexists' );
946 }
947
948 $user = User::newFromName( $username, 'creatable' );
949 if ( !is_object( $user ) ) {
950 return Status::newFatal( 'noname' );
951 } else {
952 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
953 if ( $user->getId() !== 0 ) {
954 return Status::newFatal( 'userexists' );
955 }
956 }
957
958 // Denied by providers?
959 $providers = $this->getPreAuthenticationProviders() +
960 $this->getPrimaryAuthenticationProviders() +
961 $this->getSecondaryAuthenticationProviders();
962 foreach ( $providers as $provider ) {
963 $status = $provider->testUserForCreation( $user, false, $options );
964 if ( !$status->isGood() ) {
965 return Status::wrap( $status );
966 }
967 }
968
969 return Status::newGood();
970 }
971
972 /**
973 * Basic permissions checks on whether a user can create accounts
974 * @param User $creator User doing the account creation
975 * @return Status
976 */
977 public function checkAccountCreatePermissions( User $creator ) {
978 // Wiki is read-only?
979 if ( wfReadOnly() ) {
980 return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
981 }
982
983 // This is awful, this permission check really shouldn't go through Title.
984 $permErrors = \SpecialPage::getTitleFor( 'CreateAccount' )
985 ->getUserPermissionsErrors( 'createaccount', $creator, 'secure' );
986 if ( $permErrors ) {
987 $status = Status::newGood();
988 foreach ( $permErrors as $args ) {
989 call_user_func_array( [ $status, 'fatal' ], $args );
990 }
991 return $status;
992 }
993
994 $block = $creator->isBlockedFromCreateAccount();
995 if ( $block ) {
996 $errorParams = [
997 $block->getTarget(),
998 $block->mReason ?: wfMessage( 'blockednoreason' )->text(),
999 $block->getByName()
1000 ];
1001
1002 if ( $block->getType() === \Block::TYPE_RANGE ) {
1003 $errorMessage = 'cantcreateaccount-range-text';
1004 $errorParams[] = $this->getRequest()->getIP();
1005 } else {
1006 $errorMessage = 'cantcreateaccount-text';
1007 }
1008
1009 return Status::newFatal( wfMessage( $errorMessage, $errorParams ) );
1010 }
1011
1012 $ip = $this->getRequest()->getIP();
1013 if ( $creator->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
1014 return Status::newFatal( 'sorbs_create_account_reason' );
1015 }
1016
1017 return Status::newGood();
1018 }
1019
1020 /**
1021 * Start an account creation flow
1022 *
1023 * In addition to the AuthenticationRequests returned by
1024 * $this->getAuthenticationRequests(), a client might include a
1025 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
1026 * <code>
1027 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
1028 * </code>
1029 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
1030 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
1031 * username set, that username must be used for all other requests.
1032 *
1033 * @param User $creator User doing the account creation
1034 * @param AuthenticationRequest[] $reqs
1035 * @param string $returnToUrl Url that REDIRECT responses should eventually
1036 * return to.
1037 * @return AuthenticationResponse
1038 */
1039 public function beginAccountCreation( User $creator, array $reqs, $returnToUrl ) {
1040 $session = $this->request->getSession();
1041 if ( !$this->canCreateAccounts() ) {
1042 // Caller should have called canCreateAccounts()
1043 $session->remove( 'AuthManager::accountCreationState' );
1044 throw new \LogicException( 'Account creation is not possible' );
1045 }
1046
1047 try {
1048 $username = AuthenticationRequest::getUsernameFromRequests( $reqs );
1049 } catch ( \UnexpectedValueException $ex ) {
1050 $username = null;
1051 }
1052 if ( $username === null ) {
1053 $this->logger->debug( __METHOD__ . ': No username provided' );
1054 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1055 }
1056
1057 // Permissions check
1058 $status = $this->checkAccountCreatePermissions( $creator );
1059 if ( !$status->isGood() ) {
1060 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1061 'user' => $username,
1062 'creator' => $creator->getName(),
1063 'reason' => $status->getWikiText( null, null, 'en' )
1064 ] );
1065 return AuthenticationResponse::newFail( $status->getMessage() );
1066 }
1067
1068 $status = $this->canCreateAccount(
1069 $username, [ 'flags' => User::READ_LOCKING, 'creating' => true ]
1070 );
1071 if ( !$status->isGood() ) {
1072 $this->logger->debug( __METHOD__ . ': {user} cannot be created: {reason}', [
1073 'user' => $username,
1074 'creator' => $creator->getName(),
1075 'reason' => $status->getWikiText( null, null, 'en' )
1076 ] );
1077 return AuthenticationResponse::newFail( $status->getMessage() );
1078 }
1079
1080 $user = User::newFromName( $username, 'creatable' );
1081 foreach ( $reqs as $req ) {
1082 $req->username = $username;
1083 $req->returnToUrl = $returnToUrl;
1084 if ( $req instanceof UserDataAuthenticationRequest ) {
1085 $status = $req->populateUser( $user );
1086 if ( !$status->isGood() ) {
1087 $status = Status::wrap( $status );
1088 $session->remove( 'AuthManager::accountCreationState' );
1089 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1090 'user' => $user->getName(),
1091 'creator' => $creator->getName(),
1092 'reason' => $status->getWikiText( null, null, 'en' ),
1093 ] );
1094 return AuthenticationResponse::newFail( $status->getMessage() );
1095 }
1096 }
1097 }
1098
1099 $this->removeAuthenticationSessionData( null );
1100
1101 $state = [
1102 'username' => $username,
1103 'userid' => 0,
1104 'creatorid' => $creator->getId(),
1105 'creatorname' => $creator->getName(),
1106 'reqs' => $reqs,
1107 'returnToUrl' => $returnToUrl,
1108 'primary' => null,
1109 'primaryResponse' => null,
1110 'secondary' => [],
1111 'continueRequests' => [],
1112 'maybeLink' => [],
1113 'ranPreTests' => false,
1114 ];
1115
1116 // Special case: converting a login to an account creation
1117 $req = AuthenticationRequest::getRequestByClass(
1118 $reqs, CreateFromLoginAuthenticationRequest::class
1119 );
1120 if ( $req ) {
1121 $state['maybeLink'] = $req->maybeLink;
1122
1123 if ( $req->createRequest ) {
1124 $reqs[] = $req->createRequest;
1125 $state['reqs'][] = $req->createRequest;
1126 }
1127 }
1128
1129 $session->setSecret( 'AuthManager::accountCreationState', $state );
1130 $session->persist();
1131
1132 return $this->continueAccountCreation( $reqs );
1133 }
1134
1135 /**
1136 * Continue an account creation flow
1137 * @param AuthenticationRequest[] $reqs
1138 * @return AuthenticationResponse
1139 */
1140 public function continueAccountCreation( array $reqs ) {
1141 $session = $this->request->getSession();
1142 try {
1143 if ( !$this->canCreateAccounts() ) {
1144 // Caller should have called canCreateAccounts()
1145 $session->remove( 'AuthManager::accountCreationState' );
1146 throw new \LogicException( 'Account creation is not possible' );
1147 }
1148
1149 $state = $session->getSecret( 'AuthManager::accountCreationState' );
1150 if ( !is_array( $state ) ) {
1151 return AuthenticationResponse::newFail(
1152 wfMessage( 'authmanager-create-not-in-progress' )
1153 );
1154 }
1155 $state['continueRequests'] = [];
1156
1157 // Step 0: Prepare and validate the input
1158
1159 $user = User::newFromName( $state['username'], 'creatable' );
1160 if ( !is_object( $user ) ) {
1161 $session->remove( 'AuthManager::accountCreationState' );
1162 $this->logger->debug( __METHOD__ . ': Invalid username', [
1163 'user' => $state['username'],
1164 ] );
1165 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1166 }
1167
1168 if ( $state['creatorid'] ) {
1169 $creator = User::newFromId( $state['creatorid'] );
1170 } else {
1171 $creator = new User;
1172 $creator->setName( $state['creatorname'] );
1173 }
1174
1175 // Avoid account creation races on double submissions
1176 $cache = \ObjectCache::getLocalClusterInstance();
1177 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1178 if ( !$lock ) {
1179 // Don't clear AuthManager::accountCreationState for this code
1180 // path because the process that won the race owns it.
1181 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
1182 'user' => $user->getName(),
1183 'creator' => $creator->getName(),
1184 ] );
1185 return AuthenticationResponse::newFail( wfMessage( 'usernameinprogress' ) );
1186 }
1187
1188 // Permissions check
1189 $status = $this->checkAccountCreatePermissions( $creator );
1190 if ( !$status->isGood() ) {
1191 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1192 'user' => $user->getName(),
1193 'creator' => $creator->getName(),
1194 'reason' => $status->getWikiText( null, null, 'en' )
1195 ] );
1196 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1197 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1198 $session->remove( 'AuthManager::accountCreationState' );
1199 return $ret;
1200 }
1201
1202 // Load from master for existence check
1203 $user->load( User::READ_LOCKING );
1204
1205 if ( $state['userid'] === 0 ) {
1206 if ( $user->getId() != 0 ) {
1207 $this->logger->debug( __METHOD__ . ': User exists locally', [
1208 'user' => $user->getName(),
1209 'creator' => $creator->getName(),
1210 ] );
1211 $ret = AuthenticationResponse::newFail( wfMessage( 'userexists' ) );
1212 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1213 $session->remove( 'AuthManager::accountCreationState' );
1214 return $ret;
1215 }
1216 } else {
1217 if ( $user->getId() == 0 ) {
1218 $this->logger->debug( __METHOD__ . ': User does not exist locally when it should', [
1219 'user' => $user->getName(),
1220 'creator' => $creator->getName(),
1221 'expected_id' => $state['userid'],
1222 ] );
1223 throw new \UnexpectedValueException(
1224 "User \"{$state['username']}\" should exist now, but doesn't!"
1225 );
1226 }
1227 if ( $user->getId() != $state['userid'] ) {
1228 $this->logger->debug( __METHOD__ . ': User ID/name mismatch', [
1229 'user' => $user->getName(),
1230 'creator' => $creator->getName(),
1231 'expected_id' => $state['userid'],
1232 'actual_id' => $user->getId(),
1233 ] );
1234 throw new \UnexpectedValueException(
1235 "User \"{$state['username']}\" exists, but " .
1236 "ID {$user->getId()} != {$state['userid']}!"
1237 );
1238 }
1239 }
1240 foreach ( $state['reqs'] as $req ) {
1241 if ( $req instanceof UserDataAuthenticationRequest ) {
1242 $status = $req->populateUser( $user );
1243 if ( !$status->isGood() ) {
1244 // This should never happen...
1245 $status = Status::wrap( $status );
1246 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1247 'user' => $user->getName(),
1248 'creator' => $creator->getName(),
1249 'reason' => $status->getWikiText( null, null, 'en' ),
1250 ] );
1251 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1252 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1253 $session->remove( 'AuthManager::accountCreationState' );
1254 return $ret;
1255 }
1256 }
1257 }
1258
1259 foreach ( $reqs as $req ) {
1260 $req->returnToUrl = $state['returnToUrl'];
1261 $req->username = $state['username'];
1262 }
1263
1264 // Run pre-creation tests, if we haven't already
1265 if ( !$state['ranPreTests'] ) {
1266 $providers = $this->getPreAuthenticationProviders() +
1267 $this->getPrimaryAuthenticationProviders() +
1268 $this->getSecondaryAuthenticationProviders();
1269 foreach ( $providers as $id => $provider ) {
1270 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1271 if ( !$status->isGood() ) {
1272 $this->logger->debug( __METHOD__ . ": Fail in pre-authentication by $id", [
1273 'user' => $user->getName(),
1274 'creator' => $creator->getName(),
1275 ] );
1276 $ret = AuthenticationResponse::newFail(
1277 Status::wrap( $status )->getMessage()
1278 );
1279 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1280 $session->remove( 'AuthManager::accountCreationState' );
1281 return $ret;
1282 }
1283 }
1284
1285 $state['ranPreTests'] = true;
1286 }
1287
1288 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1289
1290 if ( $state['primary'] === null ) {
1291 // We haven't picked a PrimaryAuthenticationProvider yet
1292 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1293 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_NONE ) {
1294 continue;
1295 }
1296 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1297 switch ( $res->status ) {
1298 case AuthenticationResponse::PASS;
1299 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1300 'user' => $user->getName(),
1301 'creator' => $creator->getName(),
1302 ] );
1303 $state['primary'] = $id;
1304 $state['primaryResponse'] = $res;
1305 break 2;
1306 case AuthenticationResponse::FAIL;
1307 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1308 'user' => $user->getName(),
1309 'creator' => $creator->getName(),
1310 ] );
1311 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1312 $session->remove( 'AuthManager::accountCreationState' );
1313 return $res;
1314 case AuthenticationResponse::ABSTAIN;
1315 // Continue loop
1316 break;
1317 case AuthenticationResponse::REDIRECT;
1318 case AuthenticationResponse::UI;
1319 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1320 'user' => $user->getName(),
1321 'creator' => $creator->getName(),
1322 ] );
1323 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1324 $state['primary'] = $id;
1325 $state['continueRequests'] = $res->neededRequests;
1326 $session->setSecret( 'AuthManager::accountCreationState', $state );
1327 return $res;
1328
1329 // @codeCoverageIgnoreStart
1330 default:
1331 throw new \DomainException(
1332 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1333 );
1334 // @codeCoverageIgnoreEnd
1335 }
1336 }
1337 if ( $state['primary'] === null ) {
1338 $this->logger->debug( __METHOD__ . ': Primary creation failed because no provider accepted', [
1339 'user' => $user->getName(),
1340 'creator' => $creator->getName(),
1341 ] );
1342 $ret = AuthenticationResponse::newFail(
1343 wfMessage( 'authmanager-create-no-primary' )
1344 );
1345 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1346 $session->remove( 'AuthManager::accountCreationState' );
1347 return $ret;
1348 }
1349 } elseif ( $state['primaryResponse'] === null ) {
1350 $provider = $this->getAuthenticationProvider( $state['primary'] );
1351 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
1352 // Configuration changed? Force them to start over.
1353 // @codeCoverageIgnoreStart
1354 $ret = AuthenticationResponse::newFail(
1355 wfMessage( 'authmanager-create-not-in-progress' )
1356 );
1357 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1358 $session->remove( 'AuthManager::accountCreationState' );
1359 return $ret;
1360 // @codeCoverageIgnoreEnd
1361 }
1362 $id = $provider->getUniqueId();
1363 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1364 switch ( $res->status ) {
1365 case AuthenticationResponse::PASS;
1366 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1367 'user' => $user->getName(),
1368 'creator' => $creator->getName(),
1369 ] );
1370 $state['primaryResponse'] = $res;
1371 break;
1372 case AuthenticationResponse::FAIL;
1373 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1374 'user' => $user->getName(),
1375 'creator' => $creator->getName(),
1376 ] );
1377 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1378 $session->remove( 'AuthManager::accountCreationState' );
1379 return $res;
1380 case AuthenticationResponse::REDIRECT;
1381 case AuthenticationResponse::UI;
1382 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1383 'user' => $user->getName(),
1384 'creator' => $creator->getName(),
1385 ] );
1386 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1387 $state['continueRequests'] = $res->neededRequests;
1388 $session->setSecret( 'AuthManager::accountCreationState', $state );
1389 return $res;
1390 default:
1391 throw new \DomainException(
1392 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1393 );
1394 }
1395 }
1396
1397 // Step 2: Primary authentication succeeded, create the User object
1398 // and add the user locally.
1399
1400 if ( $state['userid'] === 0 ) {
1401 $this->logger->info( 'Creating user {user} during account creation', [
1402 'user' => $user->getName(),
1403 'creator' => $creator->getName(),
1404 ] );
1405 $status = $user->addToDatabase();
1406 if ( !$status->isOK() ) {
1407 // @codeCoverageIgnoreStart
1408 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1409 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1410 $session->remove( 'AuthManager::accountCreationState' );
1411 return $ret;
1412 // @codeCoverageIgnoreEnd
1413 }
1414 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1415 \Hooks::run( 'LocalUserCreated', [ $user, false ] );
1416 $user->saveSettings();
1417 $state['userid'] = $user->getId();
1418
1419 // Update user count
1420 \DeferredUpdates::addUpdate( \SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
1421
1422 // Watch user's userpage and talk page
1423 $user->addWatch( $user->getUserPage(), User::IGNORE_USER_RIGHTS );
1424
1425 // Inform the provider
1426 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1427
1428 // Log the creation
1429 if ( $this->config->get( 'NewUserLog' ) ) {
1430 $isAnon = $creator->isAnon();
1431 $logEntry = new \ManualLogEntry(
1432 'newusers',
1433 $logSubtype ?: ( $isAnon ? 'create' : 'create2' )
1434 );
1435 $logEntry->setPerformer( $isAnon ? $user : $creator );
1436 $logEntry->setTarget( $user->getUserPage() );
1437 /** @var CreationReasonAuthenticationRequest $req */
1438 $req = AuthenticationRequest::getRequestByClass(
1439 $state['reqs'], CreationReasonAuthenticationRequest::class
1440 );
1441 $logEntry->setComment( $req ? $req->reason : '' );
1442 $logEntry->setParameters( [
1443 '4::userid' => $user->getId(),
1444 ] );
1445 $logid = $logEntry->insert();
1446 $logEntry->publish( $logid );
1447 }
1448 }
1449
1450 // Step 3: Iterate over all the secondary authentication providers.
1451
1452 $beginReqs = $state['reqs'];
1453
1454 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1455 if ( !isset( $state['secondary'][$id] ) ) {
1456 // This provider isn't started yet, so we pass it the set
1457 // of reqs from beginAuthentication instead of whatever
1458 // might have been used by a previous provider in line.
1459 $func = 'beginSecondaryAccountCreation';
1460 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1461 } elseif ( !$state['secondary'][$id] ) {
1462 $func = 'continueSecondaryAccountCreation';
1463 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1464 } else {
1465 continue;
1466 }
1467 switch ( $res->status ) {
1468 case AuthenticationResponse::PASS;
1469 $this->logger->debug( __METHOD__ . ": Secondary creation passed by $id", [
1470 'user' => $user->getName(),
1471 'creator' => $creator->getName(),
1472 ] );
1473 // fall through
1474 case AuthenticationResponse::ABSTAIN;
1475 $state['secondary'][$id] = true;
1476 break;
1477 case AuthenticationResponse::REDIRECT;
1478 case AuthenticationResponse::UI;
1479 $this->logger->debug( __METHOD__ . ": Secondary creation $res->status by $id", [
1480 'user' => $user->getName(),
1481 'creator' => $creator->getName(),
1482 ] );
1483 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1484 $state['secondary'][$id] = false;
1485 $state['continueRequests'] = $res->neededRequests;
1486 $session->setSecret( 'AuthManager::accountCreationState', $state );
1487 return $res;
1488 case AuthenticationResponse::FAIL;
1489 throw new \DomainException(
1490 get_class( $provider ) . "::{$func}() returned $res->status." .
1491 ' Secondary providers are not allowed to fail account creation, that' .
1492 ' should have been done via testForAccountCreation().'
1493 );
1494 // @codeCoverageIgnoreStart
1495 default:
1496 throw new \DomainException(
1497 get_class( $provider ) . "::{$func}() returned $res->status"
1498 );
1499 // @codeCoverageIgnoreEnd
1500 }
1501 }
1502
1503 $id = $user->getId();
1504 $name = $user->getName();
1505 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1506 $ret = AuthenticationResponse::newPass( $name );
1507 $ret->loginRequest = $req;
1508 $this->createdAccountAuthenticationRequests[] = $req;
1509
1510 $this->logger->info( __METHOD__ . ': Account creation succeeded for {user}', [
1511 'user' => $user->getName(),
1512 'creator' => $creator->getName(),
1513 ] );
1514
1515 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1516 $session->remove( 'AuthManager::accountCreationState' );
1517 $this->removeAuthenticationSessionData( null );
1518 return $ret;
1519 } catch ( \Exception $ex ) {
1520 $session->remove( 'AuthManager::accountCreationState' );
1521 throw $ex;
1522 }
1523 }
1524
1525 /**
1526 * Auto-create an account, and log into that account
1527 *
1528 * PrimaryAuthenticationProviders can invoke this method by returning a PASS from
1529 * beginPrimaryAuthentication/continuePrimaryAuthentication with the username of a
1530 * non-existing user. SessionProviders can invoke it by returning a SessionInfo with
1531 * the username of a non-existing user from provideSessionInfo(). Calling this method
1532 * explicitly (e.g. from a maintenance script) is also fine.
1533 *
1534 * @param User $user User to auto-create
1535 * @param string $source What caused the auto-creation? This must be the ID
1536 * of a PrimaryAuthenticationProvider or the constant self::AUTOCREATE_SOURCE_SESSION.
1537 * @param bool $login Whether to also log the user in
1538 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1539 */
1540 public function autoCreateUser( User $user, $source, $login = true ) {
1541 if ( $source !== self::AUTOCREATE_SOURCE_SESSION &&
1542 !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1543 ) {
1544 throw new \InvalidArgumentException( "Unknown auto-creation source: $source" );
1545 }
1546
1547 $username = $user->getName();
1548
1549 // Try the local user from the replica DB
1550 $localId = User::idFromName( $username );
1551 $flags = User::READ_NORMAL;
1552
1553 // Fetch the user ID from the master, so that we don't try to create the user
1554 // when they already exist, due to replication lag
1555 // @codeCoverageIgnoreStart
1556 if (
1557 !$localId &&
1558 MediaWikiServices::getInstance()->getDBLoadBalancer()->getReaderIndex() != 0
1559 ) {
1560 $localId = User::idFromName( $username, User::READ_LATEST );
1561 $flags = User::READ_LATEST;
1562 }
1563 // @codeCoverageIgnoreEnd
1564
1565 if ( $localId ) {
1566 $this->logger->debug( __METHOD__ . ': {username} already exists locally', [
1567 'username' => $username,
1568 ] );
1569 $user->setId( $localId );
1570 $user->loadFromId( $flags );
1571 if ( $login ) {
1572 $this->setSessionDataForUser( $user );
1573 }
1574 $status = Status::newGood();
1575 $status->warning( 'userexists' );
1576 return $status;
1577 }
1578
1579 // Wiki is read-only?
1580 if ( wfReadOnly() ) {
1581 $this->logger->debug( __METHOD__ . ': denied by wfReadOnly(): {reason}', [
1582 'username' => $username,
1583 'reason' => wfReadOnlyReason(),
1584 ] );
1585 $user->setId( 0 );
1586 $user->loadFromId();
1587 return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
1588 }
1589
1590 // Check the session, if we tried to create this user already there's
1591 // no point in retrying.
1592 $session = $this->request->getSession();
1593 if ( $session->get( 'AuthManager::AutoCreateBlacklist' ) ) {
1594 $this->logger->debug( __METHOD__ . ': blacklisted in session {sessionid}', [
1595 'username' => $username,
1596 'sessionid' => $session->getId(),
1597 ] );
1598 $user->setId( 0 );
1599 $user->loadFromId();
1600 $reason = $session->get( 'AuthManager::AutoCreateBlacklist' );
1601 if ( $reason instanceof StatusValue ) {
1602 return Status::wrap( $reason );
1603 } else {
1604 return Status::newFatal( $reason );
1605 }
1606 }
1607
1608 // Is the username creatable?
1609 if ( !User::isCreatableName( $username ) ) {
1610 $this->logger->debug( __METHOD__ . ': name "{username}" is not creatable', [
1611 'username' => $username,
1612 ] );
1613 $session->set( 'AuthManager::AutoCreateBlacklist', 'noname' );
1614 $user->setId( 0 );
1615 $user->loadFromId();
1616 return Status::newFatal( 'noname' );
1617 }
1618
1619 // Is the IP user able to create accounts?
1620 $anon = new User;
1621 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' ) ) {
1622 $this->logger->debug( __METHOD__ . ': IP lacks the ability to create or autocreate accounts', [
1623 'username' => $username,
1624 'ip' => $anon->getName(),
1625 ] );
1626 $session->set( 'AuthManager::AutoCreateBlacklist', 'authmanager-autocreate-noperm' );
1627 $session->persist();
1628 $user->setId( 0 );
1629 $user->loadFromId();
1630 return Status::newFatal( 'authmanager-autocreate-noperm' );
1631 }
1632
1633 // Avoid account creation races on double submissions
1634 $cache = \ObjectCache::getLocalClusterInstance();
1635 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1636 if ( !$lock ) {
1637 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
1638 'user' => $username,
1639 ] );
1640 $user->setId( 0 );
1641 $user->loadFromId();
1642 return Status::newFatal( 'usernameinprogress' );
1643 }
1644
1645 // Denied by providers?
1646 $options = [
1647 'flags' => User::READ_LATEST,
1648 'creating' => true,
1649 ];
1650 $providers = $this->getPreAuthenticationProviders() +
1651 $this->getPrimaryAuthenticationProviders() +
1652 $this->getSecondaryAuthenticationProviders();
1653 foreach ( $providers as $provider ) {
1654 $status = $provider->testUserForCreation( $user, $source, $options );
1655 if ( !$status->isGood() ) {
1656 $ret = Status::wrap( $status );
1657 $this->logger->debug( __METHOD__ . ': Provider denied creation of {username}: {reason}', [
1658 'username' => $username,
1659 'reason' => $ret->getWikiText( null, null, 'en' ),
1660 ] );
1661 $session->set( 'AuthManager::AutoCreateBlacklist', $status );
1662 $user->setId( 0 );
1663 $user->loadFromId();
1664 return $ret;
1665 }
1666 }
1667
1668 $backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
1669 if ( $cache->get( $backoffKey ) ) {
1670 $this->logger->debug( __METHOD__ . ': {username} denied by prior creation attempt failures', [
1671 'username' => $username,
1672 ] );
1673 $user->setId( 0 );
1674 $user->loadFromId();
1675 return Status::newFatal( 'authmanager-autocreate-exception' );
1676 }
1677
1678 // Checks passed, create the user...
1679 $from = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : 'CLI';
1680 $this->logger->info( __METHOD__ . ': creating new user ({username}) - from: {from}', [
1681 'username' => $username,
1682 'from' => $from,
1683 ] );
1684
1685 // Ignore warnings about master connections/writes...hard to avoid here
1686 $trxProfiler = \Profiler::instance()->getTransactionProfiler();
1687 $old = $trxProfiler->setSilenced( true );
1688 try {
1689 $status = $user->addToDatabase();
1690 if ( !$status->isOK() ) {
1691 // Double-check for a race condition (T70012). We make use of the fact that when
1692 // addToDatabase fails due to the user already existing, the user object gets loaded.
1693 if ( $user->getId() ) {
1694 $this->logger->info( __METHOD__ . ': {username} already exists locally (race)', [
1695 'username' => $username,
1696 ] );
1697 if ( $login ) {
1698 $this->setSessionDataForUser( $user );
1699 }
1700 $status = Status::newGood();
1701 $status->warning( 'userexists' );
1702 } else {
1703 $this->logger->error( __METHOD__ . ': {username} failed with message {msg}', [
1704 'username' => $username,
1705 'msg' => $status->getWikiText( null, null, 'en' )
1706 ] );
1707 $user->setId( 0 );
1708 $user->loadFromId();
1709 }
1710 return $status;
1711 }
1712 } catch ( \Exception $ex ) {
1713 $trxProfiler->setSilenced( $old );
1714 $this->logger->error( __METHOD__ . ': {username} failed with exception {exception}', [
1715 'username' => $username,
1716 'exception' => $ex,
1717 ] );
1718 // Do not keep throwing errors for a while
1719 $cache->set( $backoffKey, 1, 600 );
1720 // Bubble up error; which should normally trigger DB rollbacks
1721 throw $ex;
1722 }
1723
1724 $this->setDefaultUserOptions( $user, false );
1725
1726 // Inform the providers
1727 $this->callMethodOnProviders( 6, 'autoCreatedAccount', [ $user, $source ] );
1728
1729 \Hooks::run( 'AuthPluginAutoCreate', [ $user ], '1.27' );
1730 \Hooks::run( 'LocalUserCreated', [ $user, true ] );
1731 $user->saveSettings();
1732
1733 // Update user count
1734 \DeferredUpdates::addUpdate( \SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
1735 // Watch user's userpage and talk page
1736 \DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1737 $user->addWatch( $user->getUserPage(), User::IGNORE_USER_RIGHTS );
1738 } );
1739
1740 // Log the creation
1741 if ( $this->config->get( 'NewUserLog' ) ) {
1742 $logEntry = new \ManualLogEntry( 'newusers', 'autocreate' );
1743 $logEntry->setPerformer( $user );
1744 $logEntry->setTarget( $user->getUserPage() );
1745 $logEntry->setComment( '' );
1746 $logEntry->setParameters( [
1747 '4::userid' => $user->getId(),
1748 ] );
1749 $logEntry->insert();
1750 }
1751
1752 $trxProfiler->setSilenced( $old );
1753
1754 if ( $login ) {
1755 $this->setSessionDataForUser( $user );
1756 }
1757
1758 return Status::newGood();
1759 }
1760
1761 /**@}*/
1762
1763 /**
1764 * @name Account linking
1765 * @{
1766 */
1767
1768 /**
1769 * Determine whether accounts can be linked
1770 * @return bool
1771 */
1772 public function canLinkAccounts() {
1773 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1774 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
1775 return true;
1776 }
1777 }
1778 return false;
1779 }
1780
1781 /**
1782 * Start an account linking flow
1783 *
1784 * @param User $user User being linked
1785 * @param AuthenticationRequest[] $reqs
1786 * @param string $returnToUrl Url that REDIRECT responses should eventually
1787 * return to.
1788 * @return AuthenticationResponse
1789 */
1790 public function beginAccountLink( User $user, array $reqs, $returnToUrl ) {
1791 $session = $this->request->getSession();
1792 $session->remove( 'AuthManager::accountLinkState' );
1793
1794 if ( !$this->canLinkAccounts() ) {
1795 // Caller should have called canLinkAccounts()
1796 throw new \LogicException( 'Account linking is not possible' );
1797 }
1798
1799 if ( $user->getId() === 0 ) {
1800 if ( !User::isUsableName( $user->getName() ) ) {
1801 $msg = wfMessage( 'noname' );
1802 } else {
1803 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
1804 }
1805 return AuthenticationResponse::newFail( $msg );
1806 }
1807 foreach ( $reqs as $req ) {
1808 $req->username = $user->getName();
1809 $req->returnToUrl = $returnToUrl;
1810 }
1811
1812 $this->removeAuthenticationSessionData( null );
1813
1814 $providers = $this->getPreAuthenticationProviders();
1815 foreach ( $providers as $id => $provider ) {
1816 $status = $provider->testForAccountLink( $user );
1817 if ( !$status->isGood() ) {
1818 $this->logger->debug( __METHOD__ . ": Account linking pre-check failed by $id", [
1819 'user' => $user->getName(),
1820 ] );
1821 $ret = AuthenticationResponse::newFail(
1822 Status::wrap( $status )->getMessage()
1823 );
1824 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1825 return $ret;
1826 }
1827 }
1828
1829 $state = [
1830 'username' => $user->getName(),
1831 'userid' => $user->getId(),
1832 'returnToUrl' => $returnToUrl,
1833 'primary' => null,
1834 'continueRequests' => [],
1835 ];
1836
1837 $providers = $this->getPrimaryAuthenticationProviders();
1838 foreach ( $providers as $id => $provider ) {
1839 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider::TYPE_LINK ) {
1840 continue;
1841 }
1842
1843 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
1844 switch ( $res->status ) {
1845 case AuthenticationResponse::PASS;
1846 $this->logger->info( "Account linked to {user} by $id", [
1847 'user' => $user->getName(),
1848 ] );
1849 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1850 return $res;
1851
1852 case AuthenticationResponse::FAIL;
1853 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
1854 'user' => $user->getName(),
1855 ] );
1856 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1857 return $res;
1858
1859 case AuthenticationResponse::ABSTAIN;
1860 // Continue loop
1861 break;
1862
1863 case AuthenticationResponse::REDIRECT;
1864 case AuthenticationResponse::UI;
1865 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
1866 'user' => $user->getName(),
1867 ] );
1868 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
1869 $state['primary'] = $id;
1870 $state['continueRequests'] = $res->neededRequests;
1871 $session->setSecret( 'AuthManager::accountLinkState', $state );
1872 $session->persist();
1873 return $res;
1874
1875 // @codeCoverageIgnoreStart
1876 default:
1877 throw new \DomainException(
1878 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
1879 );
1880 // @codeCoverageIgnoreEnd
1881 }
1882 }
1883
1884 $this->logger->debug( __METHOD__ . ': Account linking failed because no provider accepted', [
1885 'user' => $user->getName(),
1886 ] );
1887 $ret = AuthenticationResponse::newFail(
1888 wfMessage( 'authmanager-link-no-primary' )
1889 );
1890 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1891 return $ret;
1892 }
1893
1894 /**
1895 * Continue an account linking flow
1896 * @param AuthenticationRequest[] $reqs
1897 * @return AuthenticationResponse
1898 */
1899 public function continueAccountLink( array $reqs ) {
1900 $session = $this->request->getSession();
1901 try {
1902 if ( !$this->canLinkAccounts() ) {
1903 // Caller should have called canLinkAccounts()
1904 $session->remove( 'AuthManager::accountLinkState' );
1905 throw new \LogicException( 'Account linking is not possible' );
1906 }
1907
1908 $state = $session->getSecret( 'AuthManager::accountLinkState' );
1909 if ( !is_array( $state ) ) {
1910 return AuthenticationResponse::newFail(
1911 wfMessage( 'authmanager-link-not-in-progress' )
1912 );
1913 }
1914 $state['continueRequests'] = [];
1915
1916 // Step 0: Prepare and validate the input
1917
1918 $user = User::newFromName( $state['username'], 'usable' );
1919 if ( !is_object( $user ) ) {
1920 $session->remove( 'AuthManager::accountLinkState' );
1921 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1922 }
1923 if ( $user->getId() != $state['userid'] ) {
1924 throw new \UnexpectedValueException(
1925 "User \"{$state['username']}\" is valid, but " .
1926 "ID {$user->getId()} != {$state['userid']}!"
1927 );
1928 }
1929
1930 foreach ( $reqs as $req ) {
1931 $req->username = $state['username'];
1932 $req->returnToUrl = $state['returnToUrl'];
1933 }
1934
1935 // Step 1: Call the primary again until it succeeds
1936
1937 $provider = $this->getAuthenticationProvider( $state['primary'] );
1938 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
1939 // Configuration changed? Force them to start over.
1940 // @codeCoverageIgnoreStart
1941 $ret = AuthenticationResponse::newFail(
1942 wfMessage( 'authmanager-link-not-in-progress' )
1943 );
1944 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1945 $session->remove( 'AuthManager::accountLinkState' );
1946 return $ret;
1947 // @codeCoverageIgnoreEnd
1948 }
1949 $id = $provider->getUniqueId();
1950 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
1951 switch ( $res->status ) {
1952 case AuthenticationResponse::PASS;
1953 $this->logger->info( "Account linked to {user} by $id", [
1954 'user' => $user->getName(),
1955 ] );
1956 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1957 $session->remove( 'AuthManager::accountLinkState' );
1958 return $res;
1959 case AuthenticationResponse::FAIL;
1960 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
1961 'user' => $user->getName(),
1962 ] );
1963 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1964 $session->remove( 'AuthManager::accountLinkState' );
1965 return $res;
1966 case AuthenticationResponse::REDIRECT;
1967 case AuthenticationResponse::UI;
1968 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
1969 'user' => $user->getName(),
1970 ] );
1971 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
1972 $state['continueRequests'] = $res->neededRequests;
1973 $session->setSecret( 'AuthManager::accountLinkState', $state );
1974 return $res;
1975 default:
1976 throw new \DomainException(
1977 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
1978 );
1979 }
1980 } catch ( \Exception $ex ) {
1981 $session->remove( 'AuthManager::accountLinkState' );
1982 throw $ex;
1983 }
1984 }
1985
1986 /**@}*/
1987
1988 /**
1989 * @name Information methods
1990 * @{
1991 */
1992
1993 /**
1994 * Return the applicable list of AuthenticationRequests
1995 *
1996 * Possible values for $action:
1997 * - ACTION_LOGIN: Valid for passing to beginAuthentication
1998 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
1999 * - ACTION_CREATE: Valid for passing to beginAccountCreation
2000 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
2001 * - ACTION_LINK: Valid for passing to beginAccountLink
2002 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
2003 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
2004 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
2005 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
2006 *
2007 * @param string $action One of the AuthManager::ACTION_* constants
2008 * @param User|null $user User being acted on, instead of the current user.
2009 * @return AuthenticationRequest[]
2010 */
2011 public function getAuthenticationRequests( $action, User $user = null ) {
2012 $options = [];
2013 $providerAction = $action;
2014
2015 // Figure out which providers to query
2016 switch ( $action ) {
2017 case self::ACTION_LOGIN:
2018 case self::ACTION_CREATE:
2019 $providers = $this->getPreAuthenticationProviders() +
2020 $this->getPrimaryAuthenticationProviders() +
2021 $this->getSecondaryAuthenticationProviders();
2022 break;
2023
2024 case self::ACTION_LOGIN_CONTINUE:
2025 $state = $this->request->getSession()->getSecret( 'AuthManager::authnState' );
2026 return is_array( $state ) ? $state['continueRequests'] : [];
2027
2028 case self::ACTION_CREATE_CONTINUE:
2029 $state = $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' );
2030 return is_array( $state ) ? $state['continueRequests'] : [];
2031
2032 case self::ACTION_LINK:
2033 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2034 return $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK;
2035 } );
2036 break;
2037
2038 case self::ACTION_UNLINK:
2039 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2040 return $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK;
2041 } );
2042
2043 // To providers, unlink and remove are identical.
2044 $providerAction = self::ACTION_REMOVE;
2045 break;
2046
2047 case self::ACTION_LINK_CONTINUE:
2048 $state = $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' );
2049 return is_array( $state ) ? $state['continueRequests'] : [];
2050
2051 case self::ACTION_CHANGE:
2052 case self::ACTION_REMOVE:
2053 $providers = $this->getPrimaryAuthenticationProviders() +
2054 $this->getSecondaryAuthenticationProviders();
2055 break;
2056
2057 // @codeCoverageIgnoreStart
2058 default:
2059 throw new \DomainException( __METHOD__ . ": Invalid action \"$action\"" );
2060 }
2061 // @codeCoverageIgnoreEnd
2062
2063 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
2064 }
2065
2066 /**
2067 * Internal request lookup for self::getAuthenticationRequests
2068 *
2069 * @param string $providerAction Action to pass to providers
2070 * @param array $options Options to pass to providers
2071 * @param AuthenticationProvider[] $providers
2072 * @param User|null $user
2073 * @return AuthenticationRequest[]
2074 */
2075 private function getAuthenticationRequestsInternal(
2076 $providerAction, array $options, array $providers, User $user = null
2077 ) {
2078 $user = $user ?: \RequestContext::getMain()->getUser();
2079 $options['username'] = $user->isAnon() ? null : $user->getName();
2080
2081 // Query them and merge results
2082 $reqs = [];
2083 foreach ( $providers as $provider ) {
2084 $isPrimary = $provider instanceof PrimaryAuthenticationProvider;
2085 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2086 $id = $req->getUniqueId();
2087
2088 // If a required request if from a Primary, mark it as "primary-required" instead
2089 if ( $isPrimary ) {
2090 if ( $req->required ) {
2091 $req->required = AuthenticationRequest::PRIMARY_REQUIRED;
2092 }
2093 }
2094
2095 if (
2096 !isset( $reqs[$id] )
2097 || $req->required === AuthenticationRequest::REQUIRED
2098 || $reqs[$id] === AuthenticationRequest::OPTIONAL
2099 ) {
2100 $reqs[$id] = $req;
2101 }
2102 }
2103 }
2104
2105 // AuthManager has its own req for some actions
2106 switch ( $providerAction ) {
2107 case self::ACTION_LOGIN:
2108 $reqs[] = new RememberMeAuthenticationRequest;
2109 break;
2110
2111 case self::ACTION_CREATE:
2112 $reqs[] = new UsernameAuthenticationRequest;
2113 $reqs[] = new UserDataAuthenticationRequest;
2114 if ( $options['username'] !== null ) {
2115 $reqs[] = new CreationReasonAuthenticationRequest;
2116 $options['username'] = null; // Don't fill in the username below
2117 }
2118 break;
2119 }
2120
2121 // Fill in reqs data
2122 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2123
2124 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2125 if ( $providerAction === self::ACTION_CHANGE || $providerAction === self::ACTION_REMOVE ) {
2126 $reqs = array_filter( $reqs, function ( $req ) {
2127 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2128 } );
2129 }
2130
2131 return array_values( $reqs );
2132 }
2133
2134 /**
2135 * Set values in an array of requests
2136 * @param AuthenticationRequest[] &$reqs
2137 * @param string $action
2138 * @param string|null $username
2139 * @param bool $forceAction
2140 */
2141 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2142 foreach ( $reqs as $req ) {
2143 if ( !$req->action || $forceAction ) {
2144 $req->action = $action;
2145 }
2146 if ( $req->username === null ) {
2147 $req->username = $username;
2148 }
2149 }
2150 }
2151
2152 /**
2153 * Determine whether a username exists
2154 * @param string $username
2155 * @param int $flags Bitfield of User:READ_* constants
2156 * @return bool
2157 */
2158 public function userExists( $username, $flags = User::READ_NORMAL ) {
2159 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2160 if ( $provider->testUserExists( $username, $flags ) ) {
2161 return true;
2162 }
2163 }
2164
2165 return false;
2166 }
2167
2168 /**
2169 * Determine whether a user property should be allowed to be changed.
2170 *
2171 * Supported properties are:
2172 * - emailaddress
2173 * - realname
2174 * - nickname
2175 *
2176 * @param string $property
2177 * @return bool
2178 */
2179 public function allowsPropertyChange( $property ) {
2180 $providers = $this->getPrimaryAuthenticationProviders() +
2181 $this->getSecondaryAuthenticationProviders();
2182 foreach ( $providers as $provider ) {
2183 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2184 return false;
2185 }
2186 }
2187 return true;
2188 }
2189
2190 /**
2191 * Get a provider by ID
2192 * @note This is public so extensions can check whether their own provider
2193 * is installed and so they can read its configuration if necessary.
2194 * Other uses are not recommended.
2195 * @param string $id
2196 * @return AuthenticationProvider|null
2197 */
2198 public function getAuthenticationProvider( $id ) {
2199 // Fast version
2200 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2201 return $this->allAuthenticationProviders[$id];
2202 }
2203
2204 // Slow version: instantiate each kind and check
2205 $providers = $this->getPrimaryAuthenticationProviders();
2206 if ( isset( $providers[$id] ) ) {
2207 return $providers[$id];
2208 }
2209 $providers = $this->getSecondaryAuthenticationProviders();
2210 if ( isset( $providers[$id] ) ) {
2211 return $providers[$id];
2212 }
2213 $providers = $this->getPreAuthenticationProviders();
2214 if ( isset( $providers[$id] ) ) {
2215 return $providers[$id];
2216 }
2217
2218 return null;
2219 }
2220
2221 /**@}*/
2222
2223 /**
2224 * @name Internal methods
2225 * @{
2226 */
2227
2228 /**
2229 * Store authentication in the current session
2230 * @protected For use by AuthenticationProviders
2231 * @param string $key
2232 * @param mixed $data Must be serializable
2233 */
2234 public function setAuthenticationSessionData( $key, $data ) {
2235 $session = $this->request->getSession();
2236 $arr = $session->getSecret( 'authData' );
2237 if ( !is_array( $arr ) ) {
2238 $arr = [];
2239 }
2240 $arr[$key] = $data;
2241 $session->setSecret( 'authData', $arr );
2242 }
2243
2244 /**
2245 * Fetch authentication data from the current session
2246 * @protected For use by AuthenticationProviders
2247 * @param string $key
2248 * @param mixed $default
2249 * @return mixed
2250 */
2251 public function getAuthenticationSessionData( $key, $default = null ) {
2252 $arr = $this->request->getSession()->getSecret( 'authData' );
2253 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2254 return $arr[$key];
2255 } else {
2256 return $default;
2257 }
2258 }
2259
2260 /**
2261 * Remove authentication data
2262 * @protected For use by AuthenticationProviders
2263 * @param string|null $key If null, all data is removed
2264 */
2265 public function removeAuthenticationSessionData( $key ) {
2266 $session = $this->request->getSession();
2267 if ( $key === null ) {
2268 $session->remove( 'authData' );
2269 } else {
2270 $arr = $session->getSecret( 'authData' );
2271 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2272 unset( $arr[$key] );
2273 $session->setSecret( 'authData', $arr );
2274 }
2275 }
2276 }
2277
2278 /**
2279 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2280 * @param string $class
2281 * @param array[] $specs
2282 * @return AuthenticationProvider[]
2283 */
2284 protected function providerArrayFromSpecs( $class, array $specs ) {
2285 $i = 0;
2286 foreach ( $specs as &$spec ) {
2287 $spec = [ 'sort2' => $i++ ] + $spec + [ 'sort' => 0 ];
2288 }
2289 unset( $spec );
2290 usort( $specs, function ( $a, $b ) {
2291 return ( (int)$a['sort'] ) - ( (int)$b['sort'] )
2292 ?: $a['sort2'] - $b['sort2'];
2293 } );
2294
2295 $ret = [];
2296 foreach ( $specs as $spec ) {
2297 $provider = ObjectFactory::getObjectFromSpec( $spec );
2298 if ( !$provider instanceof $class ) {
2299 throw new \RuntimeException(
2300 "Expected instance of $class, got " . get_class( $provider )
2301 );
2302 }
2303 $provider->setLogger( $this->logger );
2304 $provider->setManager( $this );
2305 $provider->setConfig( $this->config );
2306 $id = $provider->getUniqueId();
2307 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2308 throw new \RuntimeException(
2309 "Duplicate specifications for id $id (classes " .
2310 get_class( $provider ) . ' and ' .
2311 get_class( $this->allAuthenticationProviders[$id] ) . ')'
2312 );
2313 }
2314 $this->allAuthenticationProviders[$id] = $provider;
2315 $ret[$id] = $provider;
2316 }
2317 return $ret;
2318 }
2319
2320 /**
2321 * Get the configuration
2322 * @return array
2323 */
2324 private function getConfiguration() {
2325 return $this->config->get( 'AuthManagerConfig' ) ?: $this->config->get( 'AuthManagerAutoConfig' );
2326 }
2327
2328 /**
2329 * Get the list of PreAuthenticationProviders
2330 * @return PreAuthenticationProvider[]
2331 */
2332 protected function getPreAuthenticationProviders() {
2333 if ( $this->preAuthenticationProviders === null ) {
2334 $conf = $this->getConfiguration();
2335 $this->preAuthenticationProviders = $this->providerArrayFromSpecs(
2336 PreAuthenticationProvider::class, $conf['preauth']
2337 );
2338 }
2339 return $this->preAuthenticationProviders;
2340 }
2341
2342 /**
2343 * Get the list of PrimaryAuthenticationProviders
2344 * @return PrimaryAuthenticationProvider[]
2345 */
2346 protected function getPrimaryAuthenticationProviders() {
2347 if ( $this->primaryAuthenticationProviders === null ) {
2348 $conf = $this->getConfiguration();
2349 $this->primaryAuthenticationProviders = $this->providerArrayFromSpecs(
2350 PrimaryAuthenticationProvider::class, $conf['primaryauth']
2351 );
2352 }
2353 return $this->primaryAuthenticationProviders;
2354 }
2355
2356 /**
2357 * Get the list of SecondaryAuthenticationProviders
2358 * @return SecondaryAuthenticationProvider[]
2359 */
2360 protected function getSecondaryAuthenticationProviders() {
2361 if ( $this->secondaryAuthenticationProviders === null ) {
2362 $conf = $this->getConfiguration();
2363 $this->secondaryAuthenticationProviders = $this->providerArrayFromSpecs(
2364 SecondaryAuthenticationProvider::class, $conf['secondaryauth']
2365 );
2366 }
2367 return $this->secondaryAuthenticationProviders;
2368 }
2369
2370 /**
2371 * Log the user in
2372 * @param User $user
2373 * @param bool|null $remember
2374 */
2375 private function setSessionDataForUser( $user, $remember = null ) {
2376 $session = $this->request->getSession();
2377 $delay = $session->delaySave();
2378
2379 $session->resetId();
2380 $session->resetAllTokens();
2381 if ( $session->canSetUser() ) {
2382 $session->setUser( $user );
2383 }
2384 if ( $remember !== null ) {
2385 $session->setRememberUser( $remember );
2386 }
2387 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2388 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2389 $session->persist();
2390
2391 \Wikimedia\ScopedCallback::consume( $delay );
2392
2393 \Hooks::run( 'UserLoggedIn', [ $user ] );
2394 }
2395
2396 /**
2397 * @param User $user
2398 * @param bool $useContextLang Use 'uselang' to set the user's language
2399 */
2400 private function setDefaultUserOptions( User $user, $useContextLang ) {
2401 global $wgContLang;
2402
2403 $user->setToken();
2404
2405 $lang = $useContextLang ? \RequestContext::getMain()->getLanguage() : $wgContLang;
2406 $user->setOption( 'language', $lang->getPreferredVariant() );
2407
2408 if ( $wgContLang->hasVariants() ) {
2409 $user->setOption( 'variant', $wgContLang->getPreferredVariant() );
2410 }
2411 }
2412
2413 /**
2414 * @param int $which Bitmask: 1 = pre, 2 = primary, 4 = secondary
2415 * @param string $method
2416 * @param array $args
2417 */
2418 private function callMethodOnProviders( $which, $method, array $args ) {
2419 $providers = [];
2420 if ( $which & 1 ) {
2421 $providers += $this->getPreAuthenticationProviders();
2422 }
2423 if ( $which & 2 ) {
2424 $providers += $this->getPrimaryAuthenticationProviders();
2425 }
2426 if ( $which & 4 ) {
2427 $providers += $this->getSecondaryAuthenticationProviders();
2428 }
2429 foreach ( $providers as $provider ) {
2430 call_user_func_array( [ $provider, $method ], $args );
2431 }
2432 }
2433
2434 /**
2435 * Reset the internal caching for unit testing
2436 * @protected Unit tests only
2437 */
2438 public static function resetCache() {
2439 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
2440 // @codeCoverageIgnoreStart
2441 throw new \MWException( __METHOD__ . ' may only be called from unit tests!' );
2442 // @codeCoverageIgnoreEnd
2443 }
2444
2445 self::$instance = null;
2446 }
2447
2448 /**@}*/
2449
2450 }
2451
2452 /**
2453 * For really cool vim folding this needs to be at the end:
2454 * vim: foldmarker=@{,@} foldmethod=marker
2455 */