ab7ba0fb8c9e1be6e18b664f1cdffb4ad1245391
[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 $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', [
685 'user' => $user->getName(),
686 ] );
687 /** @var RememberMeAuthenticationRequest $req */
688 $req = AuthenticationRequest::getRequestByClass(
689 $beginReqs, RememberMeAuthenticationRequest::class
690 );
691 $this->setSessionDataForUser( $user, $req && $req->rememberMe );
692 $ret = AuthenticationResponse::newPass( $user->getName() );
693 $this->callMethodOnProviders( 7, 'postAuthentication', [ $user, $ret ] );
694 $session->remove( 'AuthManager::authnState' );
695 $this->removeAuthenticationSessionData( null );
696 \Hooks::run( 'AuthManagerLoginAuthenticateAudit', [ $ret, $user, $user->getName() ] );
697 return $ret;
698 } catch ( \Exception $ex ) {
699 $session->remove( 'AuthManager::authnState' );
700 throw $ex;
701 }
702 }
703
704 /**
705 * Whether security-sensitive operations should proceed.
706 *
707 * A "security-sensitive operation" is something like a password or email
708 * change, that would normally have a "reenter your password to confirm"
709 * box if we only supported password-based authentication.
710 *
711 * @param string $operation Operation being checked. This should be a
712 * message-key-like string such as 'change-password' or 'change-email'.
713 * @return string One of the SEC_* constants.
714 */
715 public function securitySensitiveOperationStatus( $operation ) {
716 $status = self::SEC_OK;
717
718 $this->logger->debug( __METHOD__ . ": Checking $operation" );
719
720 $session = $this->request->getSession();
721 $aId = $session->getUser()->getId();
722 if ( $aId === 0 ) {
723 // User isn't authenticated. DWIM?
724 $status = $this->canAuthenticateNow() ? self::SEC_REAUTH : self::SEC_FAIL;
725 $this->logger->info( __METHOD__ . ": Not logged in! $operation is $status" );
726 return $status;
727 }
728
729 if ( $session->canSetUser() ) {
730 $id = $session->get( 'AuthManager:lastAuthId' );
731 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
732 if ( $id !== $aId || $last === null ) {
733 $timeSinceLogin = PHP_INT_MAX; // Forever ago
734 } else {
735 $timeSinceLogin = max( 0, time() - $last );
736 }
737
738 $thresholds = $this->config->get( 'ReauthenticateTime' );
739 if ( isset( $thresholds[$operation] ) ) {
740 $threshold = $thresholds[$operation];
741 } elseif ( isset( $thresholds['default'] ) ) {
742 $threshold = $thresholds['default'];
743 } else {
744 throw new \UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
745 }
746
747 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
748 $status = self::SEC_REAUTH;
749 }
750 } else {
751 $timeSinceLogin = -1;
752
753 $pass = $this->config->get( 'AllowSecuritySensitiveOperationIfCannotReauthenticate' );
754 if ( isset( $pass[$operation] ) ) {
755 $status = $pass[$operation] ? self::SEC_OK : self::SEC_FAIL;
756 } elseif ( isset( $pass['default'] ) ) {
757 $status = $pass['default'] ? self::SEC_OK : self::SEC_FAIL;
758 } else {
759 throw new \UnexpectedValueException(
760 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
761 );
762 }
763 }
764
765 \Hooks::run( 'SecuritySensitiveOperationStatus', [
766 &$status, $operation, $session, $timeSinceLogin
767 ] );
768
769 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
770 if ( !$this->canAuthenticateNow() && $status === self::SEC_REAUTH ) {
771 $status = self::SEC_FAIL;
772 }
773
774 $this->logger->info( __METHOD__ . ": $operation is $status for '{user}'",
775 [
776 'user' => $session->getUser()->getName(),
777 'clientip' => $this->getRequest()->getIP(),
778 ]
779 );
780
781 return $status;
782 }
783
784 /**
785 * Determine whether a username can authenticate
786 *
787 * This is mainly for internal purposes and only takes authentication data into account,
788 * not things like blocks that can change without the authentication system being aware.
789 *
790 * @param string $username MediaWiki username
791 * @return bool
792 */
793 public function userCanAuthenticate( $username ) {
794 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
795 if ( $provider->testUserCanAuthenticate( $username ) ) {
796 return true;
797 }
798 }
799 return false;
800 }
801
802 /**
803 * Provide normalized versions of the username for security checks
804 *
805 * Since different providers can normalize the input in different ways,
806 * this returns an array of all the different ways the name might be
807 * normalized for authentication.
808 *
809 * The returned strings should not be revealed to the user, as that might
810 * leak private information (e.g. an email address might be normalized to a
811 * username).
812 *
813 * @param string $username
814 * @return string[]
815 */
816 public function normalizeUsername( $username ) {
817 $ret = [];
818 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
819 $normalized = $provider->providerNormalizeUsername( $username );
820 if ( $normalized !== null ) {
821 $ret[$normalized] = true;
822 }
823 }
824 return array_keys( $ret );
825 }
826
827 /**@}*/
828
829 /**
830 * @name Authentication data changing
831 * @{
832 */
833
834 /**
835 * Revoke any authentication credentials for a user
836 *
837 * After this, the user should no longer be able to log in.
838 *
839 * @param string $username
840 */
841 public function revokeAccessForUser( $username ) {
842 $this->logger->info( 'Revoking access for {user}', [
843 'user' => $username,
844 ] );
845 $this->callMethodOnProviders( 6, 'providerRevokeAccessForUser', [ $username ] );
846 }
847
848 /**
849 * Validate a change of authentication data (e.g. passwords)
850 * @param AuthenticationRequest $req
851 * @param bool $checkData If false, $req hasn't been loaded from the
852 * submission so checks on user-submitted fields should be skipped. $req->username is
853 * considered user-submitted for this purpose, even if it cannot be changed via
854 * $req->loadFromSubmission.
855 * @return Status
856 */
857 public function allowsAuthenticationDataChange( AuthenticationRequest $req, $checkData = true ) {
858 $any = false;
859 $providers = $this->getPrimaryAuthenticationProviders() +
860 $this->getSecondaryAuthenticationProviders();
861 foreach ( $providers as $provider ) {
862 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
863 if ( !$status->isGood() ) {
864 return Status::wrap( $status );
865 }
866 $any = $any || $status->value !== 'ignored';
867 }
868 if ( !$any ) {
869 $status = Status::newGood( 'ignored' );
870 $status->warning( 'authmanager-change-not-supported' );
871 return $status;
872 }
873 return Status::newGood();
874 }
875
876 /**
877 * Change authentication data (e.g. passwords)
878 *
879 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
880 * result in a successful login in the future.
881 *
882 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
883 * no longer result in a successful login.
884 *
885 * This method should only be called if allowsAuthenticationDataChange( $req, true )
886 * returned success.
887 *
888 * @param AuthenticationRequest $req
889 * @param bool $isAddition Set true if this represents an addition of
890 * credentials rather than a change. The main difference is that additions
891 * should not invalidate BotPasswords. If you're not sure, leave it false.
892 */
893 public function changeAuthenticationData( AuthenticationRequest $req, $isAddition = false ) {
894 $this->logger->info( 'Changing authentication data for {user} class {what}', [
895 'user' => is_string( $req->username ) ? $req->username : '<no name>',
896 'what' => get_class( $req ),
897 ] );
898
899 $this->callMethodOnProviders( 6, 'providerChangeAuthenticationData', [ $req ] );
900
901 // When the main account's authentication data is changed, invalidate
902 // all BotPasswords too.
903 if ( !$isAddition ) {
904 \BotPassword::invalidateAllPasswordsForUser( $req->username );
905 }
906 }
907
908 /**@}*/
909
910 /**
911 * @name Account creation
912 * @{
913 */
914
915 /**
916 * Determine whether accounts can be created
917 * @return bool
918 */
919 public function canCreateAccounts() {
920 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
921 switch ( $provider->accountCreationType() ) {
922 case PrimaryAuthenticationProvider::TYPE_CREATE:
923 case PrimaryAuthenticationProvider::TYPE_LINK:
924 return true;
925 }
926 }
927 return false;
928 }
929
930 /**
931 * Determine whether a particular account can be created
932 * @param string $username MediaWiki username
933 * @param array $options
934 * - flags: (int) Bitfield of User:READ_* constants, default User::READ_NORMAL
935 * - creating: (bool) For internal use only. Never specify this.
936 * @return Status
937 */
938 public function canCreateAccount( $username, $options = [] ) {
939 // Back compat
940 if ( is_int( $options ) ) {
941 $options = [ 'flags' => $options ];
942 }
943 $options += [
944 'flags' => User::READ_NORMAL,
945 'creating' => false,
946 ];
947 $flags = $options['flags'];
948
949 if ( !$this->canCreateAccounts() ) {
950 return Status::newFatal( 'authmanager-create-disabled' );
951 }
952
953 if ( $this->userExists( $username, $flags ) ) {
954 return Status::newFatal( 'userexists' );
955 }
956
957 $user = User::newFromName( $username, 'creatable' );
958 if ( !is_object( $user ) ) {
959 return Status::newFatal( 'noname' );
960 } else {
961 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
962 if ( $user->getId() !== 0 ) {
963 return Status::newFatal( 'userexists' );
964 }
965 }
966
967 // Denied by providers?
968 $providers = $this->getPreAuthenticationProviders() +
969 $this->getPrimaryAuthenticationProviders() +
970 $this->getSecondaryAuthenticationProviders();
971 foreach ( $providers as $provider ) {
972 $status = $provider->testUserForCreation( $user, false, $options );
973 if ( !$status->isGood() ) {
974 return Status::wrap( $status );
975 }
976 }
977
978 return Status::newGood();
979 }
980
981 /**
982 * Basic permissions checks on whether a user can create accounts
983 * @param User $creator User doing the account creation
984 * @return Status
985 */
986 public function checkAccountCreatePermissions( User $creator ) {
987 // Wiki is read-only?
988 if ( wfReadOnly() ) {
989 return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
990 }
991
992 // This is awful, this permission check really shouldn't go through Title.
993 $permErrors = \SpecialPage::getTitleFor( 'CreateAccount' )
994 ->getUserPermissionsErrors( 'createaccount', $creator, 'secure' );
995 if ( $permErrors ) {
996 $status = Status::newGood();
997 foreach ( $permErrors as $args ) {
998 $status->fatal( ...$args );
999 }
1000 return $status;
1001 }
1002
1003 $block = $creator->isBlockedFromCreateAccount();
1004 if ( $block ) {
1005 $errorParams = [
1006 $block->getTarget(),
1007 $block->mReason ?: wfMessage( 'blockednoreason' )->text(),
1008 $block->getByName()
1009 ];
1010
1011 if ( $block->getType() === \Block::TYPE_RANGE ) {
1012 $errorMessage = 'cantcreateaccount-range-text';
1013 $errorParams[] = $this->getRequest()->getIP();
1014 } else {
1015 $errorMessage = 'cantcreateaccount-text';
1016 }
1017
1018 return Status::newFatal( wfMessage( $errorMessage, $errorParams ) );
1019 }
1020
1021 $ip = $this->getRequest()->getIP();
1022 if ( $creator->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
1023 return Status::newFatal( 'sorbs_create_account_reason' );
1024 }
1025
1026 return Status::newGood();
1027 }
1028
1029 /**
1030 * Start an account creation flow
1031 *
1032 * In addition to the AuthenticationRequests returned by
1033 * $this->getAuthenticationRequests(), a client might include a
1034 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
1035 * <code>
1036 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
1037 * </code>
1038 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
1039 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
1040 * username set, that username must be used for all other requests.
1041 *
1042 * @param User $creator User doing the account creation
1043 * @param AuthenticationRequest[] $reqs
1044 * @param string $returnToUrl Url that REDIRECT responses should eventually
1045 * return to.
1046 * @return AuthenticationResponse
1047 */
1048 public function beginAccountCreation( User $creator, array $reqs, $returnToUrl ) {
1049 $session = $this->request->getSession();
1050 if ( !$this->canCreateAccounts() ) {
1051 // Caller should have called canCreateAccounts()
1052 $session->remove( 'AuthManager::accountCreationState' );
1053 throw new \LogicException( 'Account creation is not possible' );
1054 }
1055
1056 try {
1057 $username = AuthenticationRequest::getUsernameFromRequests( $reqs );
1058 } catch ( \UnexpectedValueException $ex ) {
1059 $username = null;
1060 }
1061 if ( $username === null ) {
1062 $this->logger->debug( __METHOD__ . ': No username provided' );
1063 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1064 }
1065
1066 // Permissions check
1067 $status = $this->checkAccountCreatePermissions( $creator );
1068 if ( !$status->isGood() ) {
1069 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1070 'user' => $username,
1071 'creator' => $creator->getName(),
1072 'reason' => $status->getWikiText( null, null, 'en' )
1073 ] );
1074 return AuthenticationResponse::newFail( $status->getMessage() );
1075 }
1076
1077 $status = $this->canCreateAccount(
1078 $username, [ 'flags' => User::READ_LOCKING, 'creating' => true ]
1079 );
1080 if ( !$status->isGood() ) {
1081 $this->logger->debug( __METHOD__ . ': {user} cannot be created: {reason}', [
1082 'user' => $username,
1083 'creator' => $creator->getName(),
1084 'reason' => $status->getWikiText( null, null, 'en' )
1085 ] );
1086 return AuthenticationResponse::newFail( $status->getMessage() );
1087 }
1088
1089 $user = User::newFromName( $username, 'creatable' );
1090 foreach ( $reqs as $req ) {
1091 $req->username = $username;
1092 $req->returnToUrl = $returnToUrl;
1093 if ( $req instanceof UserDataAuthenticationRequest ) {
1094 $status = $req->populateUser( $user );
1095 if ( !$status->isGood() ) {
1096 $status = Status::wrap( $status );
1097 $session->remove( 'AuthManager::accountCreationState' );
1098 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1099 'user' => $user->getName(),
1100 'creator' => $creator->getName(),
1101 'reason' => $status->getWikiText( null, null, 'en' ),
1102 ] );
1103 return AuthenticationResponse::newFail( $status->getMessage() );
1104 }
1105 }
1106 }
1107
1108 $this->removeAuthenticationSessionData( null );
1109
1110 $state = [
1111 'username' => $username,
1112 'userid' => 0,
1113 'creatorid' => $creator->getId(),
1114 'creatorname' => $creator->getName(),
1115 'reqs' => $reqs,
1116 'returnToUrl' => $returnToUrl,
1117 'primary' => null,
1118 'primaryResponse' => null,
1119 'secondary' => [],
1120 'continueRequests' => [],
1121 'maybeLink' => [],
1122 'ranPreTests' => false,
1123 ];
1124
1125 // Special case: converting a login to an account creation
1126 $req = AuthenticationRequest::getRequestByClass(
1127 $reqs, CreateFromLoginAuthenticationRequest::class
1128 );
1129 if ( $req ) {
1130 $state['maybeLink'] = $req->maybeLink;
1131
1132 if ( $req->createRequest ) {
1133 $reqs[] = $req->createRequest;
1134 $state['reqs'][] = $req->createRequest;
1135 }
1136 }
1137
1138 $session->setSecret( 'AuthManager::accountCreationState', $state );
1139 $session->persist();
1140
1141 return $this->continueAccountCreation( $reqs );
1142 }
1143
1144 /**
1145 * Continue an account creation flow
1146 * @param AuthenticationRequest[] $reqs
1147 * @return AuthenticationResponse
1148 */
1149 public function continueAccountCreation( array $reqs ) {
1150 $session = $this->request->getSession();
1151 try {
1152 if ( !$this->canCreateAccounts() ) {
1153 // Caller should have called canCreateAccounts()
1154 $session->remove( 'AuthManager::accountCreationState' );
1155 throw new \LogicException( 'Account creation is not possible' );
1156 }
1157
1158 $state = $session->getSecret( 'AuthManager::accountCreationState' );
1159 if ( !is_array( $state ) ) {
1160 return AuthenticationResponse::newFail(
1161 wfMessage( 'authmanager-create-not-in-progress' )
1162 );
1163 }
1164 $state['continueRequests'] = [];
1165
1166 // Step 0: Prepare and validate the input
1167
1168 $user = User::newFromName( $state['username'], 'creatable' );
1169 if ( !is_object( $user ) ) {
1170 $session->remove( 'AuthManager::accountCreationState' );
1171 $this->logger->debug( __METHOD__ . ': Invalid username', [
1172 'user' => $state['username'],
1173 ] );
1174 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1175 }
1176
1177 if ( $state['creatorid'] ) {
1178 $creator = User::newFromId( $state['creatorid'] );
1179 } else {
1180 $creator = new User;
1181 $creator->setName( $state['creatorname'] );
1182 }
1183
1184 // Avoid account creation races on double submissions
1185 $cache = \ObjectCache::getLocalClusterInstance();
1186 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1187 if ( !$lock ) {
1188 // Don't clear AuthManager::accountCreationState for this code
1189 // path because the process that won the race owns it.
1190 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
1191 'user' => $user->getName(),
1192 'creator' => $creator->getName(),
1193 ] );
1194 return AuthenticationResponse::newFail( wfMessage( 'usernameinprogress' ) );
1195 }
1196
1197 // Permissions check
1198 $status = $this->checkAccountCreatePermissions( $creator );
1199 if ( !$status->isGood() ) {
1200 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1201 'user' => $user->getName(),
1202 'creator' => $creator->getName(),
1203 'reason' => $status->getWikiText( null, null, 'en' )
1204 ] );
1205 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1206 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1207 $session->remove( 'AuthManager::accountCreationState' );
1208 return $ret;
1209 }
1210
1211 // Load from master for existence check
1212 $user->load( User::READ_LOCKING );
1213
1214 if ( $state['userid'] === 0 ) {
1215 if ( $user->getId() != 0 ) {
1216 $this->logger->debug( __METHOD__ . ': User exists locally', [
1217 'user' => $user->getName(),
1218 'creator' => $creator->getName(),
1219 ] );
1220 $ret = AuthenticationResponse::newFail( wfMessage( 'userexists' ) );
1221 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1222 $session->remove( 'AuthManager::accountCreationState' );
1223 return $ret;
1224 }
1225 } else {
1226 if ( $user->getId() == 0 ) {
1227 $this->logger->debug( __METHOD__ . ': User does not exist locally when it should', [
1228 'user' => $user->getName(),
1229 'creator' => $creator->getName(),
1230 'expected_id' => $state['userid'],
1231 ] );
1232 throw new \UnexpectedValueException(
1233 "User \"{$state['username']}\" should exist now, but doesn't!"
1234 );
1235 }
1236 if ( $user->getId() != $state['userid'] ) {
1237 $this->logger->debug( __METHOD__ . ': User ID/name mismatch', [
1238 'user' => $user->getName(),
1239 'creator' => $creator->getName(),
1240 'expected_id' => $state['userid'],
1241 'actual_id' => $user->getId(),
1242 ] );
1243 throw new \UnexpectedValueException(
1244 "User \"{$state['username']}\" exists, but " .
1245 "ID {$user->getId()} != {$state['userid']}!"
1246 );
1247 }
1248 }
1249 foreach ( $state['reqs'] as $req ) {
1250 if ( $req instanceof UserDataAuthenticationRequest ) {
1251 $status = $req->populateUser( $user );
1252 if ( !$status->isGood() ) {
1253 // This should never happen...
1254 $status = Status::wrap( $status );
1255 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1256 'user' => $user->getName(),
1257 'creator' => $creator->getName(),
1258 'reason' => $status->getWikiText( null, null, 'en' ),
1259 ] );
1260 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1261 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1262 $session->remove( 'AuthManager::accountCreationState' );
1263 return $ret;
1264 }
1265 }
1266 }
1267
1268 foreach ( $reqs as $req ) {
1269 $req->returnToUrl = $state['returnToUrl'];
1270 $req->username = $state['username'];
1271 }
1272
1273 // Run pre-creation tests, if we haven't already
1274 if ( !$state['ranPreTests'] ) {
1275 $providers = $this->getPreAuthenticationProviders() +
1276 $this->getPrimaryAuthenticationProviders() +
1277 $this->getSecondaryAuthenticationProviders();
1278 foreach ( $providers as $id => $provider ) {
1279 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1280 if ( !$status->isGood() ) {
1281 $this->logger->debug( __METHOD__ . ": Fail in pre-authentication by $id", [
1282 'user' => $user->getName(),
1283 'creator' => $creator->getName(),
1284 ] );
1285 $ret = AuthenticationResponse::newFail(
1286 Status::wrap( $status )->getMessage()
1287 );
1288 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1289 $session->remove( 'AuthManager::accountCreationState' );
1290 return $ret;
1291 }
1292 }
1293
1294 $state['ranPreTests'] = true;
1295 }
1296
1297 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1298
1299 if ( $state['primary'] === null ) {
1300 // We haven't picked a PrimaryAuthenticationProvider yet
1301 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1302 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_NONE ) {
1303 continue;
1304 }
1305 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1306 switch ( $res->status ) {
1307 case AuthenticationResponse::PASS;
1308 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1309 'user' => $user->getName(),
1310 'creator' => $creator->getName(),
1311 ] );
1312 $state['primary'] = $id;
1313 $state['primaryResponse'] = $res;
1314 break 2;
1315 case AuthenticationResponse::FAIL;
1316 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1317 'user' => $user->getName(),
1318 'creator' => $creator->getName(),
1319 ] );
1320 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1321 $session->remove( 'AuthManager::accountCreationState' );
1322 return $res;
1323 case AuthenticationResponse::ABSTAIN;
1324 // Continue loop
1325 break;
1326 case AuthenticationResponse::REDIRECT;
1327 case AuthenticationResponse::UI;
1328 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1329 'user' => $user->getName(),
1330 'creator' => $creator->getName(),
1331 ] );
1332 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1333 $state['primary'] = $id;
1334 $state['continueRequests'] = $res->neededRequests;
1335 $session->setSecret( 'AuthManager::accountCreationState', $state );
1336 return $res;
1337
1338 // @codeCoverageIgnoreStart
1339 default:
1340 throw new \DomainException(
1341 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1342 );
1343 // @codeCoverageIgnoreEnd
1344 }
1345 }
1346 if ( $state['primary'] === null ) {
1347 $this->logger->debug( __METHOD__ . ': Primary creation failed because no provider accepted', [
1348 'user' => $user->getName(),
1349 'creator' => $creator->getName(),
1350 ] );
1351 $ret = AuthenticationResponse::newFail(
1352 wfMessage( 'authmanager-create-no-primary' )
1353 );
1354 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1355 $session->remove( 'AuthManager::accountCreationState' );
1356 return $ret;
1357 }
1358 } elseif ( $state['primaryResponse'] === null ) {
1359 $provider = $this->getAuthenticationProvider( $state['primary'] );
1360 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
1361 // Configuration changed? Force them to start over.
1362 // @codeCoverageIgnoreStart
1363 $ret = AuthenticationResponse::newFail(
1364 wfMessage( 'authmanager-create-not-in-progress' )
1365 );
1366 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1367 $session->remove( 'AuthManager::accountCreationState' );
1368 return $ret;
1369 // @codeCoverageIgnoreEnd
1370 }
1371 $id = $provider->getUniqueId();
1372 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1373 switch ( $res->status ) {
1374 case AuthenticationResponse::PASS;
1375 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1376 'user' => $user->getName(),
1377 'creator' => $creator->getName(),
1378 ] );
1379 $state['primaryResponse'] = $res;
1380 break;
1381 case AuthenticationResponse::FAIL;
1382 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1383 'user' => $user->getName(),
1384 'creator' => $creator->getName(),
1385 ] );
1386 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $res ] );
1387 $session->remove( 'AuthManager::accountCreationState' );
1388 return $res;
1389 case AuthenticationResponse::REDIRECT;
1390 case AuthenticationResponse::UI;
1391 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1392 'user' => $user->getName(),
1393 'creator' => $creator->getName(),
1394 ] );
1395 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1396 $state['continueRequests'] = $res->neededRequests;
1397 $session->setSecret( 'AuthManager::accountCreationState', $state );
1398 return $res;
1399 default:
1400 throw new \DomainException(
1401 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1402 );
1403 }
1404 }
1405
1406 // Step 2: Primary authentication succeeded, create the User object
1407 // and add the user locally.
1408
1409 if ( $state['userid'] === 0 ) {
1410 $this->logger->info( 'Creating user {user} during account creation', [
1411 'user' => $user->getName(),
1412 'creator' => $creator->getName(),
1413 ] );
1414 $status = $user->addToDatabase();
1415 if ( !$status->isOK() ) {
1416 // @codeCoverageIgnoreStart
1417 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1418 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1419 $session->remove( 'AuthManager::accountCreationState' );
1420 return $ret;
1421 // @codeCoverageIgnoreEnd
1422 }
1423 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1424 \Hooks::run( 'LocalUserCreated', [ $user, false ] );
1425 $user->saveSettings();
1426 $state['userid'] = $user->getId();
1427
1428 // Update user count
1429 \DeferredUpdates::addUpdate( \SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
1430
1431 // Watch user's userpage and talk page
1432 $user->addWatch( $user->getUserPage(), User::IGNORE_USER_RIGHTS );
1433
1434 // Inform the provider
1435 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1436
1437 // Log the creation
1438 if ( $this->config->get( 'NewUserLog' ) ) {
1439 $isAnon = $creator->isAnon();
1440 $logEntry = new \ManualLogEntry(
1441 'newusers',
1442 $logSubtype ?: ( $isAnon ? 'create' : 'create2' )
1443 );
1444 $logEntry->setPerformer( $isAnon ? $user : $creator );
1445 $logEntry->setTarget( $user->getUserPage() );
1446 /** @var CreationReasonAuthenticationRequest $req */
1447 $req = AuthenticationRequest::getRequestByClass(
1448 $state['reqs'], CreationReasonAuthenticationRequest::class
1449 );
1450 $logEntry->setComment( $req ? $req->reason : '' );
1451 $logEntry->setParameters( [
1452 '4::userid' => $user->getId(),
1453 ] );
1454 $logid = $logEntry->insert();
1455 $logEntry->publish( $logid );
1456 }
1457 }
1458
1459 // Step 3: Iterate over all the secondary authentication providers.
1460
1461 $beginReqs = $state['reqs'];
1462
1463 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1464 if ( !isset( $state['secondary'][$id] ) ) {
1465 // This provider isn't started yet, so we pass it the set
1466 // of reqs from beginAuthentication instead of whatever
1467 // might have been used by a previous provider in line.
1468 $func = 'beginSecondaryAccountCreation';
1469 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1470 } elseif ( !$state['secondary'][$id] ) {
1471 $func = 'continueSecondaryAccountCreation';
1472 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1473 } else {
1474 continue;
1475 }
1476 switch ( $res->status ) {
1477 case AuthenticationResponse::PASS;
1478 $this->logger->debug( __METHOD__ . ": Secondary creation passed by $id", [
1479 'user' => $user->getName(),
1480 'creator' => $creator->getName(),
1481 ] );
1482 // fall through
1483 case AuthenticationResponse::ABSTAIN;
1484 $state['secondary'][$id] = true;
1485 break;
1486 case AuthenticationResponse::REDIRECT;
1487 case AuthenticationResponse::UI;
1488 $this->logger->debug( __METHOD__ . ": Secondary creation $res->status by $id", [
1489 'user' => $user->getName(),
1490 'creator' => $creator->getName(),
1491 ] );
1492 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1493 $state['secondary'][$id] = false;
1494 $state['continueRequests'] = $res->neededRequests;
1495 $session->setSecret( 'AuthManager::accountCreationState', $state );
1496 return $res;
1497 case AuthenticationResponse::FAIL;
1498 throw new \DomainException(
1499 get_class( $provider ) . "::{$func}() returned $res->status." .
1500 ' Secondary providers are not allowed to fail account creation, that' .
1501 ' should have been done via testForAccountCreation().'
1502 );
1503 // @codeCoverageIgnoreStart
1504 default:
1505 throw new \DomainException(
1506 get_class( $provider ) . "::{$func}() returned $res->status"
1507 );
1508 // @codeCoverageIgnoreEnd
1509 }
1510 }
1511
1512 $id = $user->getId();
1513 $name = $user->getName();
1514 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1515 $ret = AuthenticationResponse::newPass( $name );
1516 $ret->loginRequest = $req;
1517 $this->createdAccountAuthenticationRequests[] = $req;
1518
1519 $this->logger->info( __METHOD__ . ': Account creation succeeded for {user}', [
1520 'user' => $user->getName(),
1521 'creator' => $creator->getName(),
1522 ] );
1523
1524 $this->callMethodOnProviders( 7, 'postAccountCreation', [ $user, $creator, $ret ] );
1525 $session->remove( 'AuthManager::accountCreationState' );
1526 $this->removeAuthenticationSessionData( null );
1527 return $ret;
1528 } catch ( \Exception $ex ) {
1529 $session->remove( 'AuthManager::accountCreationState' );
1530 throw $ex;
1531 }
1532 }
1533
1534 /**
1535 * Auto-create an account, and log into that account
1536 *
1537 * PrimaryAuthenticationProviders can invoke this method by returning a PASS from
1538 * beginPrimaryAuthentication/continuePrimaryAuthentication with the username of a
1539 * non-existing user. SessionProviders can invoke it by returning a SessionInfo with
1540 * the username of a non-existing user from provideSessionInfo(). Calling this method
1541 * explicitly (e.g. from a maintenance script) is also fine.
1542 *
1543 * @param User $user User to auto-create
1544 * @param string $source What caused the auto-creation? This must be the ID
1545 * of a PrimaryAuthenticationProvider or the constant self::AUTOCREATE_SOURCE_SESSION.
1546 * @param bool $login Whether to also log the user in
1547 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1548 */
1549 public function autoCreateUser( User $user, $source, $login = true ) {
1550 if ( $source !== self::AUTOCREATE_SOURCE_SESSION &&
1551 !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1552 ) {
1553 throw new \InvalidArgumentException( "Unknown auto-creation source: $source" );
1554 }
1555
1556 $username = $user->getName();
1557
1558 // Try the local user from the replica DB
1559 $localId = User::idFromName( $username );
1560 $flags = User::READ_NORMAL;
1561
1562 // Fetch the user ID from the master, so that we don't try to create the user
1563 // when they already exist, due to replication lag
1564 // @codeCoverageIgnoreStart
1565 if (
1566 !$localId &&
1567 MediaWikiServices::getInstance()->getDBLoadBalancer()->getReaderIndex() != 0
1568 ) {
1569 $localId = User::idFromName( $username, User::READ_LATEST );
1570 $flags = User::READ_LATEST;
1571 }
1572 // @codeCoverageIgnoreEnd
1573
1574 if ( $localId ) {
1575 $this->logger->debug( __METHOD__ . ': {username} already exists locally', [
1576 'username' => $username,
1577 ] );
1578 $user->setId( $localId );
1579 $user->loadFromId( $flags );
1580 if ( $login ) {
1581 $this->setSessionDataForUser( $user );
1582 }
1583 $status = Status::newGood();
1584 $status->warning( 'userexists' );
1585 return $status;
1586 }
1587
1588 // Wiki is read-only?
1589 if ( wfReadOnly() ) {
1590 $this->logger->debug( __METHOD__ . ': denied by wfReadOnly(): {reason}', [
1591 'username' => $username,
1592 'reason' => wfReadOnlyReason(),
1593 ] );
1594 $user->setId( 0 );
1595 $user->loadFromId();
1596 return Status::newFatal( wfMessage( 'readonlytext', wfReadOnlyReason() ) );
1597 }
1598
1599 // Check the session, if we tried to create this user already there's
1600 // no point in retrying.
1601 $session = $this->request->getSession();
1602 if ( $session->get( 'AuthManager::AutoCreateBlacklist' ) ) {
1603 $this->logger->debug( __METHOD__ . ': blacklisted in session {sessionid}', [
1604 'username' => $username,
1605 'sessionid' => $session->getId(),
1606 ] );
1607 $user->setId( 0 );
1608 $user->loadFromId();
1609 $reason = $session->get( 'AuthManager::AutoCreateBlacklist' );
1610 if ( $reason instanceof StatusValue ) {
1611 return Status::wrap( $reason );
1612 } else {
1613 return Status::newFatal( $reason );
1614 }
1615 }
1616
1617 // Is the username creatable?
1618 if ( !User::isCreatableName( $username ) ) {
1619 $this->logger->debug( __METHOD__ . ': name "{username}" is not creatable', [
1620 'username' => $username,
1621 ] );
1622 $session->set( 'AuthManager::AutoCreateBlacklist', 'noname' );
1623 $user->setId( 0 );
1624 $user->loadFromId();
1625 return Status::newFatal( 'noname' );
1626 }
1627
1628 // Is the IP user able to create accounts?
1629 $anon = new User;
1630 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' ) ) {
1631 $this->logger->debug( __METHOD__ . ': IP lacks the ability to create or autocreate accounts', [
1632 'username' => $username,
1633 'ip' => $anon->getName(),
1634 ] );
1635 $session->set( 'AuthManager::AutoCreateBlacklist', 'authmanager-autocreate-noperm' );
1636 $session->persist();
1637 $user->setId( 0 );
1638 $user->loadFromId();
1639 return Status::newFatal( 'authmanager-autocreate-noperm' );
1640 }
1641
1642 // Avoid account creation races on double submissions
1643 $cache = \ObjectCache::getLocalClusterInstance();
1644 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1645 if ( !$lock ) {
1646 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
1647 'user' => $username,
1648 ] );
1649 $user->setId( 0 );
1650 $user->loadFromId();
1651 return Status::newFatal( 'usernameinprogress' );
1652 }
1653
1654 // Denied by providers?
1655 $options = [
1656 'flags' => User::READ_LATEST,
1657 'creating' => true,
1658 ];
1659 $providers = $this->getPreAuthenticationProviders() +
1660 $this->getPrimaryAuthenticationProviders() +
1661 $this->getSecondaryAuthenticationProviders();
1662 foreach ( $providers as $provider ) {
1663 $status = $provider->testUserForCreation( $user, $source, $options );
1664 if ( !$status->isGood() ) {
1665 $ret = Status::wrap( $status );
1666 $this->logger->debug( __METHOD__ . ': Provider denied creation of {username}: {reason}', [
1667 'username' => $username,
1668 'reason' => $ret->getWikiText( null, null, 'en' ),
1669 ] );
1670 $session->set( 'AuthManager::AutoCreateBlacklist', $status );
1671 $user->setId( 0 );
1672 $user->loadFromId();
1673 return $ret;
1674 }
1675 }
1676
1677 $backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
1678 if ( $cache->get( $backoffKey ) ) {
1679 $this->logger->debug( __METHOD__ . ': {username} denied by prior creation attempt failures', [
1680 'username' => $username,
1681 ] );
1682 $user->setId( 0 );
1683 $user->loadFromId();
1684 return Status::newFatal( 'authmanager-autocreate-exception' );
1685 }
1686
1687 // Checks passed, create the user...
1688 $from = $_SERVER['REQUEST_URI'] ?? 'CLI';
1689 $this->logger->info( __METHOD__ . ': creating new user ({username}) - from: {from}', [
1690 'username' => $username,
1691 'from' => $from,
1692 ] );
1693
1694 // Ignore warnings about master connections/writes...hard to avoid here
1695 $trxProfiler = \Profiler::instance()->getTransactionProfiler();
1696 $old = $trxProfiler->setSilenced( true );
1697 try {
1698 $status = $user->addToDatabase();
1699 if ( !$status->isOK() ) {
1700 // Double-check for a race condition (T70012). We make use of the fact that when
1701 // addToDatabase fails due to the user already existing, the user object gets loaded.
1702 if ( $user->getId() ) {
1703 $this->logger->info( __METHOD__ . ': {username} already exists locally (race)', [
1704 'username' => $username,
1705 ] );
1706 if ( $login ) {
1707 $this->setSessionDataForUser( $user );
1708 }
1709 $status = Status::newGood();
1710 $status->warning( 'userexists' );
1711 } else {
1712 $this->logger->error( __METHOD__ . ': {username} failed with message {msg}', [
1713 'username' => $username,
1714 'msg' => $status->getWikiText( null, null, 'en' )
1715 ] );
1716 $user->setId( 0 );
1717 $user->loadFromId();
1718 }
1719 return $status;
1720 }
1721 } catch ( \Exception $ex ) {
1722 $trxProfiler->setSilenced( $old );
1723 $this->logger->error( __METHOD__ . ': {username} failed with exception {exception}', [
1724 'username' => $username,
1725 'exception' => $ex,
1726 ] );
1727 // Do not keep throwing errors for a while
1728 $cache->set( $backoffKey, 1, 600 );
1729 // Bubble up error; which should normally trigger DB rollbacks
1730 throw $ex;
1731 }
1732
1733 $this->setDefaultUserOptions( $user, false );
1734
1735 // Inform the providers
1736 $this->callMethodOnProviders( 6, 'autoCreatedAccount', [ $user, $source ] );
1737
1738 \Hooks::run( 'AuthPluginAutoCreate', [ $user ], '1.27' );
1739 \Hooks::run( 'LocalUserCreated', [ $user, true ] );
1740 $user->saveSettings();
1741
1742 // Update user count
1743 \DeferredUpdates::addUpdate( \SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
1744 // Watch user's userpage and talk page
1745 \DeferredUpdates::addCallableUpdate( function () use ( $user ) {
1746 $user->addWatch( $user->getUserPage(), User::IGNORE_USER_RIGHTS );
1747 } );
1748
1749 // Log the creation
1750 if ( $this->config->get( 'NewUserLog' ) ) {
1751 $logEntry = new \ManualLogEntry( 'newusers', 'autocreate' );
1752 $logEntry->setPerformer( $user );
1753 $logEntry->setTarget( $user->getUserPage() );
1754 $logEntry->setComment( '' );
1755 $logEntry->setParameters( [
1756 '4::userid' => $user->getId(),
1757 ] );
1758 $logEntry->insert();
1759 }
1760
1761 $trxProfiler->setSilenced( $old );
1762
1763 if ( $login ) {
1764 $this->setSessionDataForUser( $user );
1765 }
1766
1767 return Status::newGood();
1768 }
1769
1770 /**@}*/
1771
1772 /**
1773 * @name Account linking
1774 * @{
1775 */
1776
1777 /**
1778 * Determine whether accounts can be linked
1779 * @return bool
1780 */
1781 public function canLinkAccounts() {
1782 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1783 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
1784 return true;
1785 }
1786 }
1787 return false;
1788 }
1789
1790 /**
1791 * Start an account linking flow
1792 *
1793 * @param User $user User being linked
1794 * @param AuthenticationRequest[] $reqs
1795 * @param string $returnToUrl Url that REDIRECT responses should eventually
1796 * return to.
1797 * @return AuthenticationResponse
1798 */
1799 public function beginAccountLink( User $user, array $reqs, $returnToUrl ) {
1800 $session = $this->request->getSession();
1801 $session->remove( 'AuthManager::accountLinkState' );
1802
1803 if ( !$this->canLinkAccounts() ) {
1804 // Caller should have called canLinkAccounts()
1805 throw new \LogicException( 'Account linking is not possible' );
1806 }
1807
1808 if ( $user->getId() === 0 ) {
1809 if ( !User::isUsableName( $user->getName() ) ) {
1810 $msg = wfMessage( 'noname' );
1811 } else {
1812 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
1813 }
1814 return AuthenticationResponse::newFail( $msg );
1815 }
1816 foreach ( $reqs as $req ) {
1817 $req->username = $user->getName();
1818 $req->returnToUrl = $returnToUrl;
1819 }
1820
1821 $this->removeAuthenticationSessionData( null );
1822
1823 $providers = $this->getPreAuthenticationProviders();
1824 foreach ( $providers as $id => $provider ) {
1825 $status = $provider->testForAccountLink( $user );
1826 if ( !$status->isGood() ) {
1827 $this->logger->debug( __METHOD__ . ": Account linking pre-check failed by $id", [
1828 'user' => $user->getName(),
1829 ] );
1830 $ret = AuthenticationResponse::newFail(
1831 Status::wrap( $status )->getMessage()
1832 );
1833 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1834 return $ret;
1835 }
1836 }
1837
1838 $state = [
1839 'username' => $user->getName(),
1840 'userid' => $user->getId(),
1841 'returnToUrl' => $returnToUrl,
1842 'primary' => null,
1843 'continueRequests' => [],
1844 ];
1845
1846 $providers = $this->getPrimaryAuthenticationProviders();
1847 foreach ( $providers as $id => $provider ) {
1848 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider::TYPE_LINK ) {
1849 continue;
1850 }
1851
1852 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
1853 switch ( $res->status ) {
1854 case AuthenticationResponse::PASS;
1855 $this->logger->info( "Account linked to {user} by $id", [
1856 'user' => $user->getName(),
1857 ] );
1858 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1859 return $res;
1860
1861 case AuthenticationResponse::FAIL;
1862 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
1863 'user' => $user->getName(),
1864 ] );
1865 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1866 return $res;
1867
1868 case AuthenticationResponse::ABSTAIN;
1869 // Continue loop
1870 break;
1871
1872 case AuthenticationResponse::REDIRECT;
1873 case AuthenticationResponse::UI;
1874 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
1875 'user' => $user->getName(),
1876 ] );
1877 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
1878 $state['primary'] = $id;
1879 $state['continueRequests'] = $res->neededRequests;
1880 $session->setSecret( 'AuthManager::accountLinkState', $state );
1881 $session->persist();
1882 return $res;
1883
1884 // @codeCoverageIgnoreStart
1885 default:
1886 throw new \DomainException(
1887 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
1888 );
1889 // @codeCoverageIgnoreEnd
1890 }
1891 }
1892
1893 $this->logger->debug( __METHOD__ . ': Account linking failed because no provider accepted', [
1894 'user' => $user->getName(),
1895 ] );
1896 $ret = AuthenticationResponse::newFail(
1897 wfMessage( 'authmanager-link-no-primary' )
1898 );
1899 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1900 return $ret;
1901 }
1902
1903 /**
1904 * Continue an account linking flow
1905 * @param AuthenticationRequest[] $reqs
1906 * @return AuthenticationResponse
1907 */
1908 public function continueAccountLink( array $reqs ) {
1909 $session = $this->request->getSession();
1910 try {
1911 if ( !$this->canLinkAccounts() ) {
1912 // Caller should have called canLinkAccounts()
1913 $session->remove( 'AuthManager::accountLinkState' );
1914 throw new \LogicException( 'Account linking is not possible' );
1915 }
1916
1917 $state = $session->getSecret( 'AuthManager::accountLinkState' );
1918 if ( !is_array( $state ) ) {
1919 return AuthenticationResponse::newFail(
1920 wfMessage( 'authmanager-link-not-in-progress' )
1921 );
1922 }
1923 $state['continueRequests'] = [];
1924
1925 // Step 0: Prepare and validate the input
1926
1927 $user = User::newFromName( $state['username'], 'usable' );
1928 if ( !is_object( $user ) ) {
1929 $session->remove( 'AuthManager::accountLinkState' );
1930 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1931 }
1932 if ( $user->getId() != $state['userid'] ) {
1933 throw new \UnexpectedValueException(
1934 "User \"{$state['username']}\" is valid, but " .
1935 "ID {$user->getId()} != {$state['userid']}!"
1936 );
1937 }
1938
1939 foreach ( $reqs as $req ) {
1940 $req->username = $state['username'];
1941 $req->returnToUrl = $state['returnToUrl'];
1942 }
1943
1944 // Step 1: Call the primary again until it succeeds
1945
1946 $provider = $this->getAuthenticationProvider( $state['primary'] );
1947 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
1948 // Configuration changed? Force them to start over.
1949 // @codeCoverageIgnoreStart
1950 $ret = AuthenticationResponse::newFail(
1951 wfMessage( 'authmanager-link-not-in-progress' )
1952 );
1953 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $ret ] );
1954 $session->remove( 'AuthManager::accountLinkState' );
1955 return $ret;
1956 // @codeCoverageIgnoreEnd
1957 }
1958 $id = $provider->getUniqueId();
1959 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
1960 switch ( $res->status ) {
1961 case AuthenticationResponse::PASS;
1962 $this->logger->info( "Account linked to {user} by $id", [
1963 'user' => $user->getName(),
1964 ] );
1965 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1966 $session->remove( 'AuthManager::accountLinkState' );
1967 return $res;
1968 case AuthenticationResponse::FAIL;
1969 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
1970 'user' => $user->getName(),
1971 ] );
1972 $this->callMethodOnProviders( 3, 'postAccountLink', [ $user, $res ] );
1973 $session->remove( 'AuthManager::accountLinkState' );
1974 return $res;
1975 case AuthenticationResponse::REDIRECT;
1976 case AuthenticationResponse::UI;
1977 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
1978 'user' => $user->getName(),
1979 ] );
1980 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
1981 $state['continueRequests'] = $res->neededRequests;
1982 $session->setSecret( 'AuthManager::accountLinkState', $state );
1983 return $res;
1984 default:
1985 throw new \DomainException(
1986 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
1987 );
1988 }
1989 } catch ( \Exception $ex ) {
1990 $session->remove( 'AuthManager::accountLinkState' );
1991 throw $ex;
1992 }
1993 }
1994
1995 /**@}*/
1996
1997 /**
1998 * @name Information methods
1999 * @{
2000 */
2001
2002 /**
2003 * Return the applicable list of AuthenticationRequests
2004 *
2005 * Possible values for $action:
2006 * - ACTION_LOGIN: Valid for passing to beginAuthentication
2007 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
2008 * - ACTION_CREATE: Valid for passing to beginAccountCreation
2009 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
2010 * - ACTION_LINK: Valid for passing to beginAccountLink
2011 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
2012 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
2013 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
2014 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
2015 *
2016 * @param string $action One of the AuthManager::ACTION_* constants
2017 * @param User|null $user User being acted on, instead of the current user.
2018 * @return AuthenticationRequest[]
2019 */
2020 public function getAuthenticationRequests( $action, User $user = null ) {
2021 $options = [];
2022 $providerAction = $action;
2023
2024 // Figure out which providers to query
2025 switch ( $action ) {
2026 case self::ACTION_LOGIN:
2027 case self::ACTION_CREATE:
2028 $providers = $this->getPreAuthenticationProviders() +
2029 $this->getPrimaryAuthenticationProviders() +
2030 $this->getSecondaryAuthenticationProviders();
2031 break;
2032
2033 case self::ACTION_LOGIN_CONTINUE:
2034 $state = $this->request->getSession()->getSecret( 'AuthManager::authnState' );
2035 return is_array( $state ) ? $state['continueRequests'] : [];
2036
2037 case self::ACTION_CREATE_CONTINUE:
2038 $state = $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' );
2039 return is_array( $state ) ? $state['continueRequests'] : [];
2040
2041 case self::ACTION_LINK:
2042 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2043 return $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK;
2044 } );
2045 break;
2046
2047 case self::ACTION_UNLINK:
2048 $providers = array_filter( $this->getPrimaryAuthenticationProviders(), function ( $p ) {
2049 return $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK;
2050 } );
2051
2052 // To providers, unlink and remove are identical.
2053 $providerAction = self::ACTION_REMOVE;
2054 break;
2055
2056 case self::ACTION_LINK_CONTINUE:
2057 $state = $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' );
2058 return is_array( $state ) ? $state['continueRequests'] : [];
2059
2060 case self::ACTION_CHANGE:
2061 case self::ACTION_REMOVE:
2062 $providers = $this->getPrimaryAuthenticationProviders() +
2063 $this->getSecondaryAuthenticationProviders();
2064 break;
2065
2066 // @codeCoverageIgnoreStart
2067 default:
2068 throw new \DomainException( __METHOD__ . ": Invalid action \"$action\"" );
2069 }
2070 // @codeCoverageIgnoreEnd
2071
2072 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
2073 }
2074
2075 /**
2076 * Internal request lookup for self::getAuthenticationRequests
2077 *
2078 * @param string $providerAction Action to pass to providers
2079 * @param array $options Options to pass to providers
2080 * @param AuthenticationProvider[] $providers
2081 * @param User|null $user
2082 * @return AuthenticationRequest[]
2083 */
2084 private function getAuthenticationRequestsInternal(
2085 $providerAction, array $options, array $providers, User $user = null
2086 ) {
2087 $user = $user ?: \RequestContext::getMain()->getUser();
2088 $options['username'] = $user->isAnon() ? null : $user->getName();
2089
2090 // Query them and merge results
2091 $reqs = [];
2092 foreach ( $providers as $provider ) {
2093 $isPrimary = $provider instanceof PrimaryAuthenticationProvider;
2094 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2095 $id = $req->getUniqueId();
2096
2097 // If a required request if from a Primary, mark it as "primary-required" instead
2098 if ( $isPrimary ) {
2099 if ( $req->required ) {
2100 $req->required = AuthenticationRequest::PRIMARY_REQUIRED;
2101 }
2102 }
2103
2104 if (
2105 !isset( $reqs[$id] )
2106 || $req->required === AuthenticationRequest::REQUIRED
2107 || $reqs[$id] === AuthenticationRequest::OPTIONAL
2108 ) {
2109 $reqs[$id] = $req;
2110 }
2111 }
2112 }
2113
2114 // AuthManager has its own req for some actions
2115 switch ( $providerAction ) {
2116 case self::ACTION_LOGIN:
2117 $reqs[] = new RememberMeAuthenticationRequest;
2118 break;
2119
2120 case self::ACTION_CREATE:
2121 $reqs[] = new UsernameAuthenticationRequest;
2122 $reqs[] = new UserDataAuthenticationRequest;
2123 if ( $options['username'] !== null ) {
2124 $reqs[] = new CreationReasonAuthenticationRequest;
2125 $options['username'] = null; // Don't fill in the username below
2126 }
2127 break;
2128 }
2129
2130 // Fill in reqs data
2131 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2132
2133 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2134 if ( $providerAction === self::ACTION_CHANGE || $providerAction === self::ACTION_REMOVE ) {
2135 $reqs = array_filter( $reqs, function ( $req ) {
2136 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2137 } );
2138 }
2139
2140 return array_values( $reqs );
2141 }
2142
2143 /**
2144 * Set values in an array of requests
2145 * @param AuthenticationRequest[] &$reqs
2146 * @param string $action
2147 * @param string|null $username
2148 * @param bool $forceAction
2149 */
2150 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2151 foreach ( $reqs as $req ) {
2152 if ( !$req->action || $forceAction ) {
2153 $req->action = $action;
2154 }
2155 if ( $req->username === null ) {
2156 $req->username = $username;
2157 }
2158 }
2159 }
2160
2161 /**
2162 * Determine whether a username exists
2163 * @param string $username
2164 * @param int $flags Bitfield of User:READ_* constants
2165 * @return bool
2166 */
2167 public function userExists( $username, $flags = User::READ_NORMAL ) {
2168 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2169 if ( $provider->testUserExists( $username, $flags ) ) {
2170 return true;
2171 }
2172 }
2173
2174 return false;
2175 }
2176
2177 /**
2178 * Determine whether a user property should be allowed to be changed.
2179 *
2180 * Supported properties are:
2181 * - emailaddress
2182 * - realname
2183 * - nickname
2184 *
2185 * @param string $property
2186 * @return bool
2187 */
2188 public function allowsPropertyChange( $property ) {
2189 $providers = $this->getPrimaryAuthenticationProviders() +
2190 $this->getSecondaryAuthenticationProviders();
2191 foreach ( $providers as $provider ) {
2192 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2193 return false;
2194 }
2195 }
2196 return true;
2197 }
2198
2199 /**
2200 * Get a provider by ID
2201 * @note This is public so extensions can check whether their own provider
2202 * is installed and so they can read its configuration if necessary.
2203 * Other uses are not recommended.
2204 * @param string $id
2205 * @return AuthenticationProvider|null
2206 */
2207 public function getAuthenticationProvider( $id ) {
2208 // Fast version
2209 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2210 return $this->allAuthenticationProviders[$id];
2211 }
2212
2213 // Slow version: instantiate each kind and check
2214 $providers = $this->getPrimaryAuthenticationProviders();
2215 if ( isset( $providers[$id] ) ) {
2216 return $providers[$id];
2217 }
2218 $providers = $this->getSecondaryAuthenticationProviders();
2219 if ( isset( $providers[$id] ) ) {
2220 return $providers[$id];
2221 }
2222 $providers = $this->getPreAuthenticationProviders();
2223 if ( isset( $providers[$id] ) ) {
2224 return $providers[$id];
2225 }
2226
2227 return null;
2228 }
2229
2230 /**@}*/
2231
2232 /**
2233 * @name Internal methods
2234 * @{
2235 */
2236
2237 /**
2238 * Store authentication in the current session
2239 * @protected For use by AuthenticationProviders
2240 * @param string $key
2241 * @param mixed $data Must be serializable
2242 */
2243 public function setAuthenticationSessionData( $key, $data ) {
2244 $session = $this->request->getSession();
2245 $arr = $session->getSecret( 'authData' );
2246 if ( !is_array( $arr ) ) {
2247 $arr = [];
2248 }
2249 $arr[$key] = $data;
2250 $session->setSecret( 'authData', $arr );
2251 }
2252
2253 /**
2254 * Fetch authentication data from the current session
2255 * @protected For use by AuthenticationProviders
2256 * @param string $key
2257 * @param mixed|null $default
2258 * @return mixed
2259 */
2260 public function getAuthenticationSessionData( $key, $default = null ) {
2261 $arr = $this->request->getSession()->getSecret( 'authData' );
2262 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2263 return $arr[$key];
2264 } else {
2265 return $default;
2266 }
2267 }
2268
2269 /**
2270 * Remove authentication data
2271 * @protected For use by AuthenticationProviders
2272 * @param string|null $key If null, all data is removed
2273 */
2274 public function removeAuthenticationSessionData( $key ) {
2275 $session = $this->request->getSession();
2276 if ( $key === null ) {
2277 $session->remove( 'authData' );
2278 } else {
2279 $arr = $session->getSecret( 'authData' );
2280 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2281 unset( $arr[$key] );
2282 $session->setSecret( 'authData', $arr );
2283 }
2284 }
2285 }
2286
2287 /**
2288 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2289 * @param string $class
2290 * @param array[] $specs
2291 * @return AuthenticationProvider[]
2292 */
2293 protected function providerArrayFromSpecs( $class, array $specs ) {
2294 $i = 0;
2295 foreach ( $specs as &$spec ) {
2296 $spec = [ 'sort2' => $i++ ] + $spec + [ 'sort' => 0 ];
2297 }
2298 unset( $spec );
2299 // Sort according to the 'sort' field, and if they are equal, according to 'sort2'
2300 usort( $specs, function ( $a, $b ) {
2301 return $a['sort'] <=> $b['sort']
2302 ?: $a['sort2'] <=> $b['sort2'];
2303 } );
2304
2305 $ret = [];
2306 foreach ( $specs as $spec ) {
2307 $provider = ObjectFactory::getObjectFromSpec( $spec );
2308 if ( !$provider instanceof $class ) {
2309 throw new \RuntimeException(
2310 "Expected instance of $class, got " . get_class( $provider )
2311 );
2312 }
2313 $provider->setLogger( $this->logger );
2314 $provider->setManager( $this );
2315 $provider->setConfig( $this->config );
2316 $id = $provider->getUniqueId();
2317 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2318 throw new \RuntimeException(
2319 "Duplicate specifications for id $id (classes " .
2320 get_class( $provider ) . ' and ' .
2321 get_class( $this->allAuthenticationProviders[$id] ) . ')'
2322 );
2323 }
2324 $this->allAuthenticationProviders[$id] = $provider;
2325 $ret[$id] = $provider;
2326 }
2327 return $ret;
2328 }
2329
2330 /**
2331 * Get the configuration
2332 * @return array
2333 */
2334 private function getConfiguration() {
2335 return $this->config->get( 'AuthManagerConfig' ) ?: $this->config->get( 'AuthManagerAutoConfig' );
2336 }
2337
2338 /**
2339 * Get the list of PreAuthenticationProviders
2340 * @return PreAuthenticationProvider[]
2341 */
2342 protected function getPreAuthenticationProviders() {
2343 if ( $this->preAuthenticationProviders === null ) {
2344 $conf = $this->getConfiguration();
2345 $this->preAuthenticationProviders = $this->providerArrayFromSpecs(
2346 PreAuthenticationProvider::class, $conf['preauth']
2347 );
2348 }
2349 return $this->preAuthenticationProviders;
2350 }
2351
2352 /**
2353 * Get the list of PrimaryAuthenticationProviders
2354 * @return PrimaryAuthenticationProvider[]
2355 */
2356 protected function getPrimaryAuthenticationProviders() {
2357 if ( $this->primaryAuthenticationProviders === null ) {
2358 $conf = $this->getConfiguration();
2359 $this->primaryAuthenticationProviders = $this->providerArrayFromSpecs(
2360 PrimaryAuthenticationProvider::class, $conf['primaryauth']
2361 );
2362 }
2363 return $this->primaryAuthenticationProviders;
2364 }
2365
2366 /**
2367 * Get the list of SecondaryAuthenticationProviders
2368 * @return SecondaryAuthenticationProvider[]
2369 */
2370 protected function getSecondaryAuthenticationProviders() {
2371 if ( $this->secondaryAuthenticationProviders === null ) {
2372 $conf = $this->getConfiguration();
2373 $this->secondaryAuthenticationProviders = $this->providerArrayFromSpecs(
2374 SecondaryAuthenticationProvider::class, $conf['secondaryauth']
2375 );
2376 }
2377 return $this->secondaryAuthenticationProviders;
2378 }
2379
2380 /**
2381 * Log the user in
2382 * @param User $user
2383 * @param bool|null $remember
2384 */
2385 private function setSessionDataForUser( $user, $remember = null ) {
2386 $session = $this->request->getSession();
2387 $delay = $session->delaySave();
2388
2389 $session->resetId();
2390 $session->resetAllTokens();
2391 if ( $session->canSetUser() ) {
2392 $session->setUser( $user );
2393 }
2394 if ( $remember !== null ) {
2395 $session->setRememberUser( $remember );
2396 }
2397 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2398 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2399 $session->persist();
2400
2401 \Wikimedia\ScopedCallback::consume( $delay );
2402
2403 \Hooks::run( 'UserLoggedIn', [ $user ] );
2404 }
2405
2406 /**
2407 * @param User $user
2408 * @param bool $useContextLang Use 'uselang' to set the user's language
2409 */
2410 private function setDefaultUserOptions( User $user, $useContextLang ) {
2411 $user->setToken();
2412
2413 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
2414
2415 $lang = $useContextLang ? \RequestContext::getMain()->getLanguage() : $contLang;
2416 $user->setOption( 'language', $lang->getPreferredVariant() );
2417
2418 if ( $contLang->hasVariants() ) {
2419 $user->setOption( 'variant', $contLang->getPreferredVariant() );
2420 }
2421 }
2422
2423 /**
2424 * @param int $which Bitmask: 1 = pre, 2 = primary, 4 = secondary
2425 * @param string $method
2426 * @param array $args
2427 */
2428 private function callMethodOnProviders( $which, $method, array $args ) {
2429 $providers = [];
2430 if ( $which & 1 ) {
2431 $providers += $this->getPreAuthenticationProviders();
2432 }
2433 if ( $which & 2 ) {
2434 $providers += $this->getPrimaryAuthenticationProviders();
2435 }
2436 if ( $which & 4 ) {
2437 $providers += $this->getSecondaryAuthenticationProviders();
2438 }
2439 foreach ( $providers as $provider ) {
2440 $provider->$method( ...$args );
2441 }
2442 }
2443
2444 /**
2445 * Reset the internal caching for unit testing
2446 * @protected Unit tests only
2447 */
2448 public static function resetCache() {
2449 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
2450 // @codeCoverageIgnoreStart
2451 throw new \MWException( __METHOD__ . ' may only be called from unit tests!' );
2452 // @codeCoverageIgnoreEnd
2453 }
2454
2455 self::$instance = null;
2456 }
2457
2458 /**@}*/
2459
2460 }
2461
2462 /**
2463 * For really cool vim folding this needs to be at the end:
2464 * vim: foldmarker=@{,@} foldmethod=marker
2465 */