Debian Codegraph @

includes/auth/AuthManager.php

raw symbols SCIP
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 InvalidArgumentException;
27 use LogicException;
28 use MediaWiki\Auth\Hook\AuthManagerVerifyAuthenticationHook;
29 use MediaWiki\Block\BlockManager;
30 use MediaWiki\Config\Config;
31 use MediaWiki\Context\RequestContext;
32 use MediaWiki\Deferred\DeferredUpdates;
33 use MediaWiki\Deferred\SiteStatsUpdate;
34 use MediaWiki\HookContainer\HookContainer;
35 use MediaWiki\HookContainer\HookRunner;
36 use MediaWiki\Language\Language;
37 use MediaWiki\Languages\LanguageConverterFactory;
38 use MediaWiki\MainConfigNames;
39 use MediaWiki\MediaWikiServices;
40 use MediaWiki\Page\PageIdentity;
41 use MediaWiki\Permissions\Authority;
42 use MediaWiki\Permissions\PermissionStatus;
43 use MediaWiki\Request\WebRequest;
44 use MediaWiki\SpecialPage\SpecialPage;
45 use MediaWiki\Status\Status;
46 use MediaWiki\StubObject\StubGlobalUser;
47 use MediaWiki\User\BotPasswordStore;
48 use MediaWiki\User\Options\UserOptionsManager;
49 use MediaWiki\User\TempUser\TempUserCreator;
50 use MediaWiki\User\User;
51 use MediaWiki\User\UserFactory;
52 use MediaWiki\User\UserIdentity;
53 use MediaWiki\User\UserIdentityLookup;
54 use MediaWiki\User\UserNameUtils;
55 use MediaWiki\User\UserRigorOptions;
56 use MediaWiki\Watchlist\WatchlistManager;
57 use MWExceptionHandler;
58 use Psr\Log\LoggerAwareInterface;
59 use Psr\Log\LoggerInterface;
60 use Psr\Log\NullLogger;
61 use StatusValue;
62 use Wikimedia\NormalizedException\NormalizedException;
63 use Wikimedia\ObjectFactory\ObjectFactory;
64 use Wikimedia\Rdbms\IDBAccessObject;
65 use Wikimedia\Rdbms\ILoadBalancer;
66 use Wikimedia\Rdbms\ReadOnlyMode;
67 use Wikimedia\ScopedCallback;
68
69 /**
70 * This serves as the entry point to the authentication system.
71 *
72 * In the future, it may also serve as the entry point to the authorization
73 * system.
74 *
75 * If you are looking at this because you are working on an extension that creates its own
76 * login or signup page, then 1) you really shouldn't do that, 2) if you feel you absolutely
77 * have to, subclass AuthManagerSpecialPage or build it on the client side using the clientlogin
78 * or the createaccount API. Trying to call this class directly will very likely end up in
79 * security vulnerabilities or broken UX in edge cases.
80 *
81 * If you are working on an extension that needs to integrate with the authentication system
82 * (e.g. by providing a new login method, or doing extra permission checks), you'll probably
83 * need to write an AuthenticationProvider.
84 *
85 * If you want to create a "reserved" user programmatically, User::newSystemUser() might be what
86 * you are looking for. If you want to change user data, use User::changeAuthenticationData().
87 * Code that is related to some SessionProvider or PrimaryAuthenticationProvider can
88 * create a (non-reserved) user by calling AuthManager::autoCreateUser(); it is then the provider's
89 * responsibility to ensure that the user can authenticate somehow (see especially
90 * PrimaryAuthenticationProvider::autoCreatedAccount()). The same functionality can also be used
91 * from Maintenance scripts such as createAndPromote.php.
92 * If you are writing code that is not associated with such a provider and needs to create accounts
93 * programmatically for real users, you should rethink your architecture. There is no good way to
94 * do that as such code has no knowledge of what authentication methods are enabled on the wiki and
95 * cannot provide any means for users to access the accounts it would create.
96 *
97 * The two main control flows when using this class are as follows:
98 * * Login, user creation or account linking code will call getAuthenticationRequests(), populate
99 * the requests with data (by using them to build a HTMLForm and have the user fill it, or by
100 * exposing a form specification via the API, so that the client can build it), and pass them to
101 * the appropriate begin* method. That will return either a success/failure response, or more
102 * requests to fill (either by building a form or by redirecting the user to some external
103 * provider which will send the data back), in which case they need to be submitted to the
104 * appropriate continue* method and that step has to be repeated until the response is a success
105 * or failure response. AuthManager will use the session to maintain internal state during the
106 * process.
107 * * Code doing an authentication data change will call getAuthenticationRequests(), select
108 * a single request, populate it, and pass it to allowsAuthenticationDataChange() and then
109 * changeAuthenticationData(). If the data change is user-initiated, the whole process needs
110 * to be preceded by a call to securitySensitiveOperationStatus() and aborted if that returns
111 * a non-OK status.
112 *
113 * @ingroup Auth
114 * @since 1.27
115 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
116 */
117 class AuthManager implements LoggerAwareInterface {
118 /**
119 * @internal
120 * Key in the user's session data for storing login state.
121 */
122 public const AUTHN_STATE = 'AuthManager::authnState';
123
124 /**
125 * @internal
126 * Key in the user's session data for storing account creation state.
127 */
128 public const ACCOUNT_CREATION_STATE = 'AuthManager::accountCreationState';
129
130 /**
131 * @internal
132 * Key in the user's session data for storing account linking state.
133 */
134 public const ACCOUNT_LINK_STATE = 'AuthManager::accountLinkState';
135
136 /**
137 * @internal
138 * Key in the user's session data for storing autocreation failures,
139 * to avoid re-attempting expensive autocreation checks on every request.
140 */
141 public const AUTOCREATE_BLOCKLIST = 'AuthManager::AutoCreateBlacklist';
142
143 /** Log in with an existing (not necessarily local) user */
144 public const ACTION_LOGIN = 'login';
145 /** Continue a login process that was interrupted by the need for user input or communication
146 * with an external provider
147 */
148 public const ACTION_LOGIN_CONTINUE = 'login-continue';
149 /** Create a new user */
150 public const ACTION_CREATE = 'create';
151 /** Continue a user creation process that was interrupted by the need for user input or
152 * communication with an external provider
153 */
154 public const ACTION_CREATE_CONTINUE = 'create-continue';
155 /** Link an existing user to a third-party account */
156 public const ACTION_LINK = 'link';
157 /** Continue a user linking process that was interrupted by the need for user input or
158 * communication with an external provider
159 */
160 public const ACTION_LINK_CONTINUE = 'link-continue';
161 /** Change a user's credentials */
162 public const ACTION_CHANGE = 'change';
163 /** Remove a user's credentials */
164 public const ACTION_REMOVE = 'remove';
165 /** Like ACTION_REMOVE but for linking providers only */
166 public const ACTION_UNLINK = 'unlink';
167
168 /** Security-sensitive operations are ok. */
169 public const SEC_OK = 'ok';
170 /** Security-sensitive operations should re-authenticate. */
171 public const SEC_REAUTH = 'reauth';
172 /** Security-sensitive should not be performed. */
173 public const SEC_FAIL = 'fail';
174
175 /** Auto-creation is due to SessionManager */
176 public const AUTOCREATE_SOURCE_SESSION = \MediaWiki\Session\SessionManager::class;
177
178 /** Auto-creation is due to a Maintenance script */
179 public const AUTOCREATE_SOURCE_MAINT = '::Maintenance::';
180
181 /** Auto-creation is due to temporary account creation on page save */
182 public const AUTOCREATE_SOURCE_TEMP = TempUserCreator::class;
183
184 /**
185 * @internal To be used by primary authentication providers only.
186 * @var string "Remember me" status flag shared between auth providers
187 */
188 public const REMEMBER_ME = 'rememberMe';
189
190 /**
191 * @internal To be used by primary authentication providers only.
192 * @var string Primary providers can set this to false after login to prevent the
193 * login from being considered user interaction. This is important for some security
194 * features which generally interpret a recent login as proof of account ownership
195 * (vs. a stolen session).
196 */
197 public const LOGIN_WAS_INTERACTIVE = 'loginWasInteractive';
198
199 /** Call pre-authentication providers */
200 private const CALL_PRE = 1;
201
202 /** Call primary authentication providers */
203 private const CALL_PRIMARY = 2;
204
205 /** Call secondary authentication providers */
206 private const CALL_SECONDARY = 4;
207
208 /** Call all authentication providers */
209 private const CALL_ALL = self::CALL_PRE | self::CALL_PRIMARY | self::CALL_SECONDARY;
210
211 /** @var WebRequest */
212 private $request;
213
214 /** @var Config */
215 private $config;
216
217 /** @var ObjectFactory */
218 private $objectFactory;
219
220 /** @var LoggerInterface */
221 private $logger;
222
223 /** @var UserNameUtils */
224 private $userNameUtils;
225
226 /** @var AuthenticationProvider[] */
227 private $allAuthenticationProviders = [];
228
229 /** @var PreAuthenticationProvider[] */
230 private $preAuthenticationProviders = null;
231
232 /** @var PrimaryAuthenticationProvider[] */
233 private $primaryAuthenticationProviders = null;
234
235 /** @var SecondaryAuthenticationProvider[] */
236 private $secondaryAuthenticationProviders = null;
237
238 /** @var CreatedAccountAuthenticationRequest[] */
239 private $createdAccountAuthenticationRequests = [];
240
241 /** @var HookContainer */
242 private $hookContainer;
243
244 /** @var HookRunner */
245 private $hookRunner;
246
247 /** @var ReadOnlyMode */
248 private $readOnlyMode;
249
250 /** @var BlockManager */
251 private $blockManager;
252
253 /** @var WatchlistManager */
254 private $watchlistManager;
255
256 /** @var ILoadBalancer */
257 private $loadBalancer;
258
259 /** @var Language */
260 private $contentLanguage;
261
262 /** @var LanguageConverterFactory */
263 private $languageConverterFactory;
264
265 /** @var BotPasswordStore */
266 private $botPasswordStore;
267
268 /** @var UserFactory */
269 private $userFactory;
270
271 /** @var UserIdentityLookup */
272 private $userIdentityLookup;
273
274 /** @var UserOptionsManager */
275 private $userOptionsManager;
276
277 /**
278 * @param WebRequest $request
279 * @param Config $config
280 * @param ObjectFactory $objectFactory
281 * @param HookContainer $hookContainer
282 * @param ReadOnlyMode $readOnlyMode
283 * @param UserNameUtils $userNameUtils
284 * @param BlockManager $blockManager
285 * @param WatchlistManager $watchlistManager
286 * @param ILoadBalancer $loadBalancer
287 * @param Language $contentLanguage
288 * @param LanguageConverterFactory $languageConverterFactory
289 * @param BotPasswordStore $botPasswordStore
290 * @param UserFactory $userFactory
291 * @param UserIdentityLookup $userIdentityLookup
292 * @param UserOptionsManager $userOptionsManager
293 *
294 */
295 public function __construct(
296 WebRequest $request,
297 Config $config,
298 ObjectFactory $objectFactory,
299 HookContainer $hookContainer,
300 ReadOnlyMode $readOnlyMode,
301 UserNameUtils $userNameUtils,
302 BlockManager $blockManager,
303 WatchlistManager $watchlistManager,
304 ILoadBalancer $loadBalancer,
305 Language $contentLanguage,
306 LanguageConverterFactory $languageConverterFactory,
307 BotPasswordStore $botPasswordStore,
308 UserFactory $userFactory,
309 UserIdentityLookup $userIdentityLookup,
310 UserOptionsManager $userOptionsManager
311 ) {
312 $this->request = $request;
313 $this->config = $config;
314 $this->objectFactory = $objectFactory;
315 $this->hookContainer = $hookContainer;
316 $this->hookRunner = new HookRunner( $hookContainer );
317 $this->setLogger( new NullLogger() );
318 $this->readOnlyMode = $readOnlyMode;
319 $this->userNameUtils = $userNameUtils;
320 $this->blockManager = $blockManager;
321 $this->watchlistManager = $watchlistManager;
322 $this->loadBalancer = $loadBalancer;
323 $this->contentLanguage = $contentLanguage;
324 $this->languageConverterFactory = $languageConverterFactory;
325 $this->botPasswordStore = $botPasswordStore;
326 $this->userFactory = $userFactory;
327 $this->userIdentityLookup = $userIdentityLookup;
328 $this->userOptionsManager = $userOptionsManager;
329 }
330
331 /**
332 * @param LoggerInterface $logger
333 */
334 public function setLogger( LoggerInterface $logger ) {
335 $this->logger = $logger;
336 }
337
338 /**
339 * @return WebRequest
340 */
341 public function getRequest() {
342 return $this->request;
343 }
344
345 /**
346 * Force certain PrimaryAuthenticationProviders
347 *
348 * @deprecated since 1.43; for backwards compatibility only
349 * @param PrimaryAuthenticationProvider[] $providers
350 * @param string $why
351 */
352 public function forcePrimaryAuthenticationProviders( array $providers, $why ) {
353 wfDeprecated( __METHOD__, '1.43' );
354
355 $this->logger->warning( "Overriding AuthManager primary authn because $why" );
356
357 if ( $this->primaryAuthenticationProviders !== null ) {
358 $this->logger->warning(
359 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
360 );
361
362 $this->allAuthenticationProviders = array_diff_key(
363 $this->allAuthenticationProviders,
364 $this->primaryAuthenticationProviders
365 );
366 $session = $this->request->getSession();
367 $session->remove( self::AUTHN_STATE );
368 $session->remove( self::ACCOUNT_CREATION_STATE );
369 $session->remove( self::ACCOUNT_LINK_STATE );
370 $this->createdAccountAuthenticationRequests = [];
371 }
372
373 $this->primaryAuthenticationProviders = [];
374 foreach ( $providers as $provider ) {
375 if ( !$provider instanceof AbstractPrimaryAuthenticationProvider ) {
376 throw new \RuntimeException(
377 'Expected instance of MediaWiki\\Auth\\AbstractPrimaryAuthenticationProvider, got ' .
378 get_class( $provider )
379 );
380 }
381 $provider->init( $this->logger, $this, $this->hookContainer, $this->config, $this->userNameUtils );
382 $id = $provider->getUniqueId();
383 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
384 throw new \RuntimeException(
385 "Duplicate specifications for id $id (classes " .
386 get_class( $provider ) . ' and ' .
387 get_class( $this->allAuthenticationProviders[$id] ) . ')'
388 );
389 }
390 $this->allAuthenticationProviders[$id] = $provider;
391 $this->primaryAuthenticationProviders[$id] = $provider;
392 }
393 }
394
395 /***************************************************************************/
396 // region Authentication
397 /** @name Authentication */
398
399 /**
400 * Indicate whether user authentication is possible
401 *
402 * It may not be if the session is provided by something like OAuth
403 * for which each individual request includes authentication data.
404 *
405 * @return bool
406 */
407 public function canAuthenticateNow() {
408 return $this->request->getSession()->canSetUser();
409 }
410
411 /**
412 * Start an authentication flow
413 *
414 * In addition to the AuthenticationRequests returned by
415 * $this->getAuthenticationRequests(), a client might include a
416 * CreateFromLoginAuthenticationRequest from a previous login attempt to
417 * preserve state.
418 *
419 * Instead of the AuthenticationRequests returned by
420 * $this->getAuthenticationRequests(), a client might pass a
421 * CreatedAccountAuthenticationRequest from an account creation that just
422 * succeeded to log in to the just-created account.
423 *
424 * @param AuthenticationRequest[] $reqs
425 * @param string $returnToUrl Url that REDIRECT responses should eventually
426 * return to.
427 * @return AuthenticationResponse See self::continueAuthentication()
428 */
429 public function beginAuthentication( array $reqs, $returnToUrl ) {
430 $session = $this->request->getSession();
431 if ( !$session->canSetUser() ) {
432 // Caller should have called canAuthenticateNow()
433 $session->remove( self::AUTHN_STATE );
434 throw new LogicException( 'Authentication is not possible now' );
435 }
436
437 $guessUserName = null;
438 foreach ( $reqs as $req ) {
439 $req->returnToUrl = $returnToUrl;
440 // @codeCoverageIgnoreStart
441 if ( $req->username !== null && $req->username !== '' ) {
442 if ( $guessUserName === null ) {
443 $guessUserName = $req->username;
444 } elseif ( $guessUserName !== $req->username ) {
445 $guessUserName = null;
446 break;
447 }
448 }
449 // @codeCoverageIgnoreEnd
450 }
451
452 // Check for special-case login of a just-created account
453 $req = AuthenticationRequest::getRequestByClass(
454 $reqs, CreatedAccountAuthenticationRequest::class
455 );
456 if ( $req ) {
457 if ( !in_array( $req, $this->createdAccountAuthenticationRequests, true ) ) {
458 throw new LogicException(
459 'CreatedAccountAuthenticationRequests are only valid on ' .
460 'the same AuthManager that created the account'
461 );
462 }
463
464 $user = $this->userFactory->newFromName( (string)$req->username );
465 // @codeCoverageIgnoreStart
466 if ( !$user ) {
467 throw new \UnexpectedValueException(
468 "CreatedAccountAuthenticationRequest had invalid username \"{$req->username}\""
469 );
470 } elseif ( $user->getId() != $req->id ) {
471 throw new \UnexpectedValueException(
472 "ID for \"{$req->username}\" was {$user->getId()}, expected {$req->id}"
473 );
474 }
475 // @codeCoverageIgnoreEnd
476
477 $this->logger->info( 'Logging in {user} after account creation', [
478 'user' => $user->getName(),
479 ] );
480 $ret = AuthenticationResponse::newPass( $user->getName() );
481 $performer = $session->getUser();
482 $this->setSessionDataForUser( $user );
483 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $ret ] );
484 $session->remove( self::AUTHN_STATE );
485 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
486 $ret, $user, $user->getName(), [
487 'performer' => $performer
488 ] );
489 return $ret;
490 }
491
492 $this->removeAuthenticationSessionData( null );
493
494 foreach ( $this->getPreAuthenticationProviders() as $provider ) {
495 $status = $provider->testForAuthentication( $reqs );
496 if ( !$status->isGood() ) {
497 $this->logger->debug( 'Login failed in pre-authentication by ' . $provider->getUniqueId() );
498 $ret = AuthenticationResponse::newFail(
499 Status::wrap( $status )->getMessage()
500 );
501 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
502 [ $this->userFactory->newFromName( (string)$guessUserName ), $ret ]
503 );
504 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit( $ret, null, $guessUserName, [
505 'performer' => $session->getUser()
506 ] );
507 return $ret;
508 }
509 }
510
511 $state = [
512 'reqs' => $reqs,
513 'returnToUrl' => $returnToUrl,
514 'guessUserName' => $guessUserName,
515 'providerIds' => $this->getProviderIds(),
516 'primary' => null,
517 'primaryResponse' => null,
518 'secondary' => [],
519 'maybeLink' => [],
520 'continueRequests' => [],
521 ];
522
523 // Preserve state from a previous failed login
524 $req = AuthenticationRequest::getRequestByClass(
525 $reqs, CreateFromLoginAuthenticationRequest::class
526 );
527 if ( $req ) {
528 $state['maybeLink'] = $req->maybeLink;
529 }
530
531 $session = $this->request->getSession();
532 $session->setSecret( self::AUTHN_STATE, $state );
533 $session->persist();
534
535 return $this->continueAuthentication( $reqs );
536 }
537
538 /**
539 * Continue an authentication flow
540 *
541 * Return values are interpreted as follows:
542 * - status FAIL: Authentication failed. If $response->createRequest is
543 * set, that may be passed to self::beginAuthentication() or to
544 * self::beginAccountCreation() to preserve state.
545 * - status REDIRECT: The client should be redirected to the contained URL,
546 * new AuthenticationRequests should be made (if any), then
547 * AuthManager::continueAuthentication() should be called.
548 * - status UI: The client should be presented with a user interface for
549 * the fields in the specified AuthenticationRequests, then new
550 * AuthenticationRequests should be made, then
551 * AuthManager::continueAuthentication() should be called.
552 * - status RESTART: The user logged in successfully with a third-party
553 * service, but the third-party credentials aren't attached to any local
554 * account. This could be treated as a UI or a FAIL.
555 * - status PASS: Authentication was successful.
556 *
557 * @param AuthenticationRequest[] $reqs
558 * @return AuthenticationResponse
559 */
560 public function continueAuthentication( array $reqs ) {
561 $session = $this->request->getSession();
562 try {
563 if ( !$session->canSetUser() ) {
564 // Caller should have called canAuthenticateNow()
565 // @codeCoverageIgnoreStart
566 throw new LogicException( 'Authentication is not possible now' );
567 // @codeCoverageIgnoreEnd
568 }
569
570 $state = $session->getSecret( self::AUTHN_STATE );
571 if ( !is_array( $state ) ) {
572 return AuthenticationResponse::newFail(
573 wfMessage( 'authmanager-authn-not-in-progress' )
574 );
575 }
576 if ( $state['providerIds'] !== $this->getProviderIds() ) {
577 // An inconsistent AuthManagerFilterProviders hook, or site configuration changed
578 // while the user was in the middle of authentication. The first is a bug, the
579 // second is rare but expected when deploying a config change. Try handle in a way
580 // that's useful for both cases.
581 // @codeCoverageIgnoreStart
582 MWExceptionHandler::logException( new NormalizedException(
583 'Authentication failed because of inconsistent provider array',
584 [ 'old' => json_encode( $state['providerIds'] ), 'new' => json_encode( $this->getProviderIds() ) ]
585 ) );
586 $response = AuthenticationResponse::newFail(
587 wfMessage( 'authmanager-authn-not-in-progress' )
588 );
589 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
590 [ $this->userFactory->newFromName( (string)$state['guessUserName'] ), $response ]
591 );
592 $session->remove( self::AUTHN_STATE );
593 return $response;
594 // @codeCoverageIgnoreEnd
595 }
596 $state['continueRequests'] = [];
597
598 $guessUserName = $state['guessUserName'];
599
600 foreach ( $reqs as $req ) {
601 $req->returnToUrl = $state['returnToUrl'];
602 }
603
604 // Step 1: Choose a primary authentication provider, and call it until it succeeds.
605
606 if ( $state['primary'] === null ) {
607 // We haven't picked a PrimaryAuthenticationProvider yet
608 // @codeCoverageIgnoreStart
609 $guessUserName = null;
610 foreach ( $reqs as $req ) {
611 if ( $req->username !== null && $req->username !== '' ) {
612 if ( $guessUserName === null ) {
613 $guessUserName = $req->username;
614 } elseif ( $guessUserName !== $req->username ) {
615 $guessUserName = null;
616 break;
617 }
618 }
619 }
620 $state['guessUserName'] = $guessUserName;
621 // @codeCoverageIgnoreEnd
622 $state['reqs'] = $reqs;
623
624 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
625 $res = $provider->beginPrimaryAuthentication( $reqs );
626 switch ( $res->status ) {
627 case AuthenticationResponse::PASS:
628 $state['primary'] = $id;
629 $state['primaryResponse'] = $res;
630 $this->logger->debug( "Primary login with $id succeeded" );
631 break 2;
632 case AuthenticationResponse::FAIL:
633 $this->logger->debug( "Login failed in primary authentication by $id" );
634 if ( $res->createRequest || $state['maybeLink'] ) {
635 $res->createRequest = new CreateFromLoginAuthenticationRequest(
636 $res->createRequest, $state['maybeLink']
637 );
638 }
639 $this->callMethodOnProviders(
640 self::CALL_ALL,
641 'postAuthentication',
642 [
643 $this->userFactory->newFromName( (string)$guessUserName ),
644 $res
645 ]
646 );
647 $session->remove( self::AUTHN_STATE );
648 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
649 $res, null, $guessUserName, [
650 'performer' => $session->getUser()
651 ] );
652 return $res;
653 case AuthenticationResponse::ABSTAIN:
654 // Continue loop
655 break;
656 case AuthenticationResponse::REDIRECT:
657 case AuthenticationResponse::UI:
658 $this->logger->debug( "Primary login with $id returned $res->status" );
659 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
660 $state['primary'] = $id;
661 $state['continueRequests'] = $res->neededRequests;
662 $session->setSecret( self::AUTHN_STATE, $state );
663 return $res;
664
665 // @codeCoverageIgnoreStart
666 default:
667 throw new \DomainException(
668 get_class( $provider ) . "::beginPrimaryAuthentication() returned $res->status"
669 );
670 // @codeCoverageIgnoreEnd
671 }
672 }
673 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
674 if ( $state['primary'] === null ) {
675 $this->logger->debug( 'Login failed in primary authentication because no provider accepted' );
676 $response = AuthenticationResponse::newFail(
677 wfMessage( 'authmanager-authn-no-primary' )
678 );
679 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
680 [ $this->userFactory->newFromName( (string)$guessUserName ), $response ]
681 );
682 $session->remove( self::AUTHN_STATE );
683 return $response;
684 }
685 } elseif ( $state['primaryResponse'] === null ) {
686 $provider = $this->getAuthenticationProvider( $state['primary'] );
687 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
688 // Configuration changed? Force them to start over.
689 // @codeCoverageIgnoreStart
690 $response = AuthenticationResponse::newFail(
691 wfMessage( 'authmanager-authn-not-in-progress' )
692 );
693 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
694 [ $this->userFactory->newFromName( (string)$guessUserName ), $response ]
695 );
696 $session->remove( self::AUTHN_STATE );
697 return $response;
698 // @codeCoverageIgnoreEnd
699 }
700 $id = $provider->getUniqueId();
701 $res = $provider->continuePrimaryAuthentication( $reqs );
702 switch ( $res->status ) {
703 case AuthenticationResponse::PASS:
704 $state['primaryResponse'] = $res;
705 $this->logger->debug( "Primary login with $id succeeded" );
706 break;
707 case AuthenticationResponse::FAIL:
708 $this->logger->debug( "Login failed in primary authentication by $id" );
709 if ( $res->createRequest || $state['maybeLink'] ) {
710 $res->createRequest = new CreateFromLoginAuthenticationRequest(
711 $res->createRequest, $state['maybeLink']
712 );
713 }
714 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
715 [ $this->userFactory->newFromName( (string)$guessUserName ), $res ]
716 );
717 $session->remove( self::AUTHN_STATE );
718 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
719 $res, null, $guessUserName, [
720 'performer' => $session->getUser()
721 ] );
722 return $res;
723 case AuthenticationResponse::REDIRECT:
724 case AuthenticationResponse::UI:
725 $this->logger->debug( "Primary login with $id returned $res->status" );
726 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $guessUserName );
727 $state['continueRequests'] = $res->neededRequests;
728 $session->setSecret( self::AUTHN_STATE, $state );
729 return $res;
730 default:
731 throw new \DomainException(
732 get_class( $provider ) . "::continuePrimaryAuthentication() returned $res->status"
733 );
734 }
735 }
736
737 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
738 $res = $state['primaryResponse'];
739 if ( $res->username === null ) {
740 $provider = $this->getAuthenticationProvider( $state['primary'] );
741 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
742 // Configuration changed? Force them to start over.
743 // @codeCoverageIgnoreStart
744 $response = AuthenticationResponse::newFail(
745 wfMessage( 'authmanager-authn-not-in-progress' )
746 );
747 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication',
748 [ $this->userFactory->newFromName( (string)$guessUserName ), $response ]
749 );
750 $session->remove( self::AUTHN_STATE );
751 return $response;
752 // @codeCoverageIgnoreEnd
753 }
754
755 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK &&
756 $res->linkRequest &&
757 // don't confuse the user with an incorrect message if linking is disabled
758 $this->getAuthenticationProvider( ConfirmLinkSecondaryAuthenticationProvider::class )
759 ) {
760 $state['maybeLink'][$res->linkRequest->getUniqueId()] = $res->linkRequest;
761 $msg = 'authmanager-authn-no-local-user-link';
762 } else {
763 $msg = 'authmanager-authn-no-local-user';
764 }
765 $this->logger->debug(
766 "Primary login with {$provider->getUniqueId()} succeeded, but returned no user"
767 );
768 $response = AuthenticationResponse::newRestart( wfMessage( $msg ) );
769 $response->neededRequests = $this->getAuthenticationRequestsInternal(
770 self::ACTION_LOGIN,
771 [],
772 $this->getPrimaryAuthenticationProviders() + $this->getSecondaryAuthenticationProviders()
773 );
774 if ( $res->createRequest || $state['maybeLink'] ) {
775 $response->createRequest = new CreateFromLoginAuthenticationRequest(
776 $res->createRequest, $state['maybeLink']
777 );
778 $response->neededRequests[] = $response->createRequest;
779 }
780 $this->fillRequests( $response->neededRequests, self::ACTION_LOGIN, null, true );
781 $session->setSecret( self::AUTHN_STATE, [
782 'reqs' => [], // Will be filled in later
783 'primary' => null,
784 'primaryResponse' => null,
785 'secondary' => [],
786 'continueRequests' => $response->neededRequests,
787 ] + $state );
788
789 // Give the AuthManagerVerifyAuthentication hook a chance to interrupt - even though
790 // RESTART does not immediately result in a successful login, the response and session
791 // state can hold information identifying a (remote) user, and that could be turned
792 // into access to that user's account in a follow-up request.
793 if ( !$this->runVerifyHook( self::ACTION_LOGIN, null, $response, $state['primary'] ) ) {
794 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ null, $response ] );
795 $session->remove( self::AUTHN_STATE );
796 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
797 $response, null, null, [ 'performer' => $session->getUser() ]
798 );
799 return $response;
800 }
801
802 return $response;
803 }
804
805 // Step 2: Primary authentication succeeded, create the User object
806 // (and add the user locally if necessary)
807
808 $user = $this->userFactory->newFromName(
809 (string)$res->username,
810 UserRigorOptions::RIGOR_USABLE
811 );
812 if ( !$user ) {
813 $provider = $this->getAuthenticationProvider( $state['primary'] );
814 throw new \DomainException(
815 get_class( $provider ) . " returned an invalid username: {$res->username}"
816 );
817 }
818 if ( !$user->isRegistered() ) {
819 // User doesn't exist locally. Create it.
820 $this->logger->info( 'Auto-creating {user} on login', [
821 'user' => $user->getName(),
822 ] );
823 // Also use $user as performer, because the performer will be used for permission
824 // checks and global rights extensions might add rights based on the username,
825 // even if the user doesn't exist at this point.
826 $status = $this->autoCreateUser( $user, $state['primary'], false, true, $user );
827 if ( !$status->isGood() ) {
828 $response = AuthenticationResponse::newFail(
829 Status::wrap( $status )->getMessage( 'authmanager-authn-autocreate-failed' )
830 );
831 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $response ] );
832 $session->remove( self::AUTHN_STATE );
833 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
834 $response, $user, $user->getName(), [
835 'performer' => $session->getUser()
836 ] );
837 return $response;
838 }
839 }
840
841 // Step 3: Iterate over all the secondary authentication providers.
842
843 $beginReqs = $state['reqs'];
844
845 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
846 if ( !isset( $state['secondary'][$id] ) ) {
847 // This provider isn't started yet, so we pass it the set
848 // of reqs from beginAuthentication instead of whatever
849 // might have been used by a previous provider in line.
850 $func = 'beginSecondaryAuthentication';
851 $res = $provider->beginSecondaryAuthentication( $user, $beginReqs );
852 } elseif ( !$state['secondary'][$id] ) {
853 $func = 'continueSecondaryAuthentication';
854 $res = $provider->continueSecondaryAuthentication( $user, $reqs );
855 } else {
856 continue;
857 }
858 switch ( $res->status ) {
859 case AuthenticationResponse::PASS:
860 $this->logger->debug( "Secondary login with $id succeeded" );
861 // fall through
862 case AuthenticationResponse::ABSTAIN:
863 $state['secondary'][$id] = true;
864 break;
865 case AuthenticationResponse::FAIL:
866 $this->logger->debug( "Login failed in secondary authentication by $id" );
867 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $res ] );
868 $session->remove( self::AUTHN_STATE );
869 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
870 $res, $user, $user->getName(), [
871 'performer' => $session->getUser()
872 ] );
873 return $res;
874 case AuthenticationResponse::REDIRECT:
875 case AuthenticationResponse::UI:
876 $this->logger->debug( "Secondary login with $id returned " . $res->status );
877 $this->fillRequests( $res->neededRequests, self::ACTION_LOGIN, $user->getName() );
878 $state['secondary'][$id] = false;
879 $state['continueRequests'] = $res->neededRequests;
880 $session->setSecret( self::AUTHN_STATE, $state );
881 return $res;
882
883 // @codeCoverageIgnoreStart
884 default:
885 throw new \DomainException(
886 get_class( $provider ) . "::{$func}() returned $res->status"
887 );
888 // @codeCoverageIgnoreEnd
889 }
890 }
891
892 // Step 4: Authentication complete! Give hook handlers a chance to interrupt, then
893 // set the user in the session and clean up.
894
895 $response = AuthenticationResponse::newPass( $user->getName() );
896 if ( !$this->runVerifyHook( self::ACTION_LOGIN, $user, $response, $state['primary'] ) ) {
897 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $response ] );
898 $session->remove( self::AUTHN_STATE );
899 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
900 $response, $user, $user->getName(), [
901 'performer' => $session->getUser(),
902 ] );
903 return $response;
904 }
905 $this->logger->info( 'Login for {user} succeeded from {clientIp}',
906 $this->request->getSecurityLogContext( $user ) );
907 $rememberMeConfig = $this->config->get( MainConfigNames::RememberMe );
908 if ( $rememberMeConfig === RememberMeAuthenticationRequest::ALWAYS_REMEMBER ) {
909 $rememberMe = true;
910 } elseif ( $rememberMeConfig === RememberMeAuthenticationRequest::NEVER_REMEMBER ) {
911 $rememberMe = false;
912 } else {
913 /** @var RememberMeAuthenticationRequest $req */
914 $req = AuthenticationRequest::getRequestByClass(
915 $beginReqs, RememberMeAuthenticationRequest::class
916 );
917
918 // T369668: Before we conclude, let's make sure the user hasn't specified
919 // that they want their login remembered elsewhere like in the central domain.
920 // If the user clicked "remember me" in the central domain, then we should
921 // prioritise that when we call continuePrimaryAuthentication() in the provider
922 // that makes calls continuePrimaryAuthentication(). NOTE: It is the responsibility
923 // of the provider to refresh the "remember me" state that will be applied to
924 // the local wiki.
925 $rememberMe = ( $req && $req->rememberMe ) ||
926 $this->getAuthenticationSessionData( self::REMEMBER_ME );
927 }
928 $loginWasInteractive = $this->getAuthenticationSessionData( self::LOGIN_WAS_INTERACTIVE, true );
929 $this->setSessionDataForUser( $user, $rememberMe, $loginWasInteractive );
930 $this->callMethodOnProviders( self::CALL_ALL, 'postAuthentication', [ $user, $response ] );
931 $performer = $session->getUser();
932 $session->remove( self::AUTHN_STATE );
933 $this->removeAuthenticationSessionData( null );
934 $this->getHookRunner()->onAuthManagerLoginAuthenticateAudit(
935 $response, $user, $user->getName(), [
936 'performer' => $performer
937 ] );
938 return $response;
939 } catch ( \Exception $ex ) {
940 $session->remove( self::AUTHN_STATE );
941 throw $ex;
942 }
943 }
944
945 /**
946 * Whether security-sensitive operations should proceed.
947 *
948 * A "security-sensitive operation" is something like a password or email
949 * change, that would normally have a "reenter your password to confirm"
950 * box if we only supported password-based authentication.
951 *
952 * @param string $operation Operation being checked. This should be a
953 * message-key-like string such as 'change-password' or 'change-email'.
954 * @return string One of the SEC_* constants.
955 */
956 public function securitySensitiveOperationStatus( $operation ) {
957 $status = self::SEC_OK;
958
959 $this->logger->debug( __METHOD__ . ": Checking $operation" );
960
961 $session = $this->request->getSession();
962 $aId = $session->getUser()->getId();
963 if ( $aId === 0 ) {
964 // User isn't authenticated. DWIM?
965 $status = $this->canAuthenticateNow() ? self::SEC_REAUTH : self::SEC_FAIL;
966 $this->logger->info( __METHOD__ . ": Not logged in! $operation is $status" );
967 return $status;
968 }
969
970 if ( $session->canSetUser() ) {
971 $id = $session->get( 'AuthManager:lastAuthId' );
972 $last = $session->get( 'AuthManager:lastAuthTimestamp' );
973 if ( $id !== $aId || $last === null ) {
974 $timeSinceLogin = PHP_INT_MAX; // Forever ago
975 } else {
976 $timeSinceLogin = max( 0, time() - $last );
977 }
978
979 $thresholds = $this->config->get( MainConfigNames::ReauthenticateTime );
980 if ( isset( $thresholds[$operation] ) ) {
981 $threshold = $thresholds[$operation];
982 } elseif ( isset( $thresholds['default'] ) ) {
983 $threshold = $thresholds['default'];
984 } else {
985 throw new \UnexpectedValueException( '$wgReauthenticateTime lacks a default' );
986 }
987
988 if ( $threshold >= 0 && $timeSinceLogin > $threshold ) {
989 $status = self::SEC_REAUTH;
990 }
991 } else {
992 $timeSinceLogin = -1;
993
994 $pass = $this->config->get(
995 MainConfigNames::AllowSecuritySensitiveOperationIfCannotReauthenticate );
996 if ( isset( $pass[$operation] ) ) {
997 $status = $pass[$operation] ? self::SEC_OK : self::SEC_FAIL;
998 } elseif ( isset( $pass['default'] ) ) {
999 $status = $pass['default'] ? self::SEC_OK : self::SEC_FAIL;
1000 } else {
1001 throw new \UnexpectedValueException(
1002 '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default'
1003 );
1004 }
1005 }
1006
1007 $oldStatus = $status;
1008
1009 $this->getHookRunner()->onSecuritySensitiveOperationStatus(
1010 $status, $operation, $session, $timeSinceLogin );
1011
1012 if ( $status !== $oldStatus ) {
1013 $this->logger->info(
1014 __METHOD__ . ': {operation} changed from {oldstatus} to {status} for {user} in ' .
1015 'SecuritySensitiveOperationStatusHook hook',
1016 [
1017 'operation' => $operation,
1018 'oldstatus' => $oldStatus,
1019 'status' => $status,
1020 ] + $this->getRequest()->getSecurityLogContext( $session->getUser() )
1021 );
1022 }
1023
1024 // If authentication is not possible, downgrade from "REAUTH" to "FAIL".
1025 if ( !$this->canAuthenticateNow() && $status === self::SEC_REAUTH ) {
1026 $status = self::SEC_FAIL;
1027 }
1028
1029 $this->logger->info( __METHOD__ . ": {operation} is {status} for '{user}'",
1030 [
1031 'operation' => $operation,
1032 'status' => $status,
1033 ] + $this->getRequest()->getSecurityLogContext( $session->getUser() )
1034 );
1035
1036 return $status;
1037 }
1038
1039 /**
1040 * Determine whether a username can authenticate
1041 *
1042 * This is mainly for internal purposes and only takes authentication data into account,
1043 * not things like blocks that can change without the authentication system being aware.
1044 *
1045 * @param string $username MediaWiki username
1046 * @return bool
1047 */
1048 public function userCanAuthenticate( $username ) {
1049 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1050 if ( $provider->testUserCanAuthenticate( $username ) ) {
1051 return true;
1052 }
1053 }
1054 return false;
1055 }
1056
1057 /**
1058 * Provide normalized versions of the username for security checks
1059 *
1060 * Since different providers can normalize the input in different ways,
1061 * this returns an array of all the different ways the name might be
1062 * normalized for authentication.
1063 *
1064 * The returned strings should not be revealed to the user, as that might
1065 * leak private information (e.g. an email address might be normalized to a
1066 * username).
1067 *
1068 * @param string $username
1069 * @return string[]
1070 */
1071 public function normalizeUsername( $username ) {
1072 $ret = [];
1073 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1074 $normalized = $provider->providerNormalizeUsername( $username );
1075 if ( $normalized !== null ) {
1076 $ret[$normalized] = true;
1077 }
1078 }
1079 return array_keys( $ret );
1080 }
1081
1082 /**
1083 * Call this method to set the request context user for the current request
1084 * from the context session user.
1085 *
1086 * Useful in cases where we need to make sure that a MediaWiki request outputs
1087 * correct context data for a user who has just been logged-in.
1088 *
1089 * The method will also update the global language variable based on the
1090 * session's user's context language.
1091 *
1092 * This won't affect objects which already made a copy of the user or the
1093 * context, so it shouldn't be relied on too heavily, but can help to make the
1094 * UI more consistent after changing the user. Typically used after a successful
1095 * AuthManager action that changed the session user (e.g.
1096 * AuthManager::autoCreateUser() with the login flag set).
1097 */
1098 public function setRequestContextUserFromSessionUser(): void {
1099 $context = RequestContext::getMain();
1100 $user = $context->getRequest()->getSession()->getUser();
1101
1102 StubGlobalUser::setUser( $user );
1103 $context->setUser( $user );
1104
1105 // phpcs:ignore MediaWiki.Usage.ExtendClassUsage.FunctionVarUsage
1106 global $wgLang;
1107 // phpcs:ignore MediaWiki.Usage.ExtendClassUsage.FunctionVarUsage
1108 $wgLang = $context->getLanguage();
1109 }
1110
1111 // endregion -- end of Authentication
1112
1113 /***************************************************************************/
1114 // region Authentication data changing
1115 /** @name Authentication data changing */
1116
1117 /**
1118 * Revoke any authentication credentials for a user
1119 *
1120 * After this, the user should no longer be able to log in.
1121 *
1122 * @param string $username
1123 */
1124 public function revokeAccessForUser( $username ) {
1125 $this->logger->info( 'Revoking access for {user}', [
1126 'user' => $username,
1127 ] );
1128 $this->callMethodOnProviders( self::CALL_PRIMARY | self::CALL_SECONDARY, 'providerRevokeAccessForUser',
1129 [ $username ]
1130 );
1131 }
1132
1133 /**
1134 * Validate a change of authentication data (e.g. passwords)
1135 * @param AuthenticationRequest $req
1136 * @param bool $checkData If false, $req hasn't been loaded from the
1137 * submission so checks on user-submitted fields should be skipped. $req->username is
1138 * considered user-submitted for this purpose, even if it cannot be changed via
1139 * $req->loadFromSubmission.
1140 * @return Status
1141 */
1142 public function allowsAuthenticationDataChange( AuthenticationRequest $req, $checkData = true ) {
1143 $any = false;
1144 $providers = $this->getPrimaryAuthenticationProviders() +
1145 $this->getSecondaryAuthenticationProviders();
1146
1147 foreach ( $providers as $provider ) {
1148 $status = $provider->providerAllowsAuthenticationDataChange( $req, $checkData );
1149 if ( !$status->isGood() ) {
1150 // If status is not good because reset email password last attempt was within
1151 // $wgPasswordReminderResendTime then return good status with throttled-mailpassword value;
1152 // otherwise, return the $status wrapped.
1153 return $status->hasMessage( 'throttled-mailpassword' )
1154 ? Status::newGood( 'throttled-mailpassword' )
1155 : Status::wrap( $status );
1156 }
1157 $any = $any || $status->value !== 'ignored';
1158 }
1159 if ( !$any ) {
1160 return Status::newGood( 'ignored' )
1161 ->warning( 'authmanager-change-not-supported' );
1162 }
1163 return Status::newGood();
1164 }
1165
1166 /**
1167 * Change authentication data (e.g. passwords)
1168 *
1169 * If $req was returned for AuthManager::ACTION_CHANGE, using $req should
1170 * result in a successful login in the future.
1171 *
1172 * If $req was returned for AuthManager::ACTION_REMOVE, using $req should
1173 * no longer result in a successful login.
1174 *
1175 * This method should only be called if allowsAuthenticationDataChange( $req, true )
1176 * returned success.
1177 *
1178 * @param AuthenticationRequest $req
1179 * @param bool $isAddition Set true if this represents an addition of
1180 * credentials rather than a change. The main difference is that additions
1181 * should not invalidate BotPasswords. If you're not sure, leave it false.
1182 */
1183 public function changeAuthenticationData( AuthenticationRequest $req, $isAddition = false ) {
1184 $this->logger->info( 'Changing authentication data for {user} class {what}', [
1185 'user' => is_string( $req->username ) ? $req->username : '<no name>',
1186 'what' => get_class( $req ),
1187 ] );
1188
1189 $this->callMethodOnProviders( self::CALL_PRIMARY | self::CALL_SECONDARY, 'providerChangeAuthenticationData',
1190 [ $req ]
1191 );
1192
1193 // When the main account's authentication data is changed, invalidate
1194 // all BotPasswords too.
1195 if ( !$isAddition ) {
1196 $this->botPasswordStore->invalidateUserPasswords( (string)$req->username );
1197 }
1198 }
1199
1200 // endregion -- end of Authentication data changing
1201
1202 /***************************************************************************/
1203 // region Account creation
1204 /** @name Account creation */
1205
1206 /**
1207 * Determine whether accounts can be created
1208 * @return bool
1209 */
1210 public function canCreateAccounts() {
1211 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
1212 switch ( $provider->accountCreationType() ) {
1213 case PrimaryAuthenticationProvider::TYPE_CREATE:
1214 case PrimaryAuthenticationProvider::TYPE_LINK:
1215 return true;
1216 }
1217 }
1218 return false;
1219 }
1220
1221 /**
1222 * Determine whether a particular account can be created
1223 * @param string $username MediaWiki username
1224 * @param array $options
1225 * - flags: (int) Bitfield of IDBAccessObject::READ_* constants, default IDBAccessObject::READ_NORMAL
1226 * - creating: (bool) For internal use only. Never specify this.
1227 * @return Status
1228 */
1229 public function canCreateAccount( $username, $options = [] ) {
1230 // Back compat
1231 if ( is_int( $options ) ) {
1232 $options = [ 'flags' => $options ];
1233 }
1234 $options += [
1235 'flags' => IDBAccessObject::READ_NORMAL,
1236 'creating' => false,
1237 ];
1238 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
1239 $flags = $options['flags'];
1240
1241 if ( !$this->canCreateAccounts() ) {
1242 return Status::newFatal( 'authmanager-create-disabled' );
1243 }
1244
1245 if ( $this->userExists( $username, $flags ) ) {
1246 return Status::newFatal( 'userexists' );
1247 }
1248
1249 $user = $this->userFactory->newFromName( (string)$username, UserRigorOptions::RIGOR_CREATABLE );
1250 if ( !is_object( $user ) ) {
1251 return Status::newFatal( 'noname' );
1252 } else {
1253 $user->load( $flags ); // Explicitly load with $flags, auto-loading always uses READ_NORMAL
1254 if ( $user->isRegistered() ) {
1255 return Status::newFatal( 'userexists' );
1256 }
1257 }
1258
1259 // Denied by providers?
1260 $providers = $this->getPreAuthenticationProviders() +
1261 $this->getPrimaryAuthenticationProviders() +
1262 $this->getSecondaryAuthenticationProviders();
1263 foreach ( $providers as $provider ) {
1264 $status = $provider->testUserForCreation( $user, false, $options );
1265 if ( !$status->isGood() ) {
1266 return Status::wrap( $status );
1267 }
1268 }
1269
1270 return Status::newGood();
1271 }
1272
1273 /**
1274 * @param callable $authorizer ( string $action, PageIdentity $target, PermissionStatus $status )
1275 * @param string $action
1276 * @return StatusValue
1277 */
1278 private function authorizeInternal(
1279 callable $authorizer,
1280 string $action
1281 ): StatusValue {
1282 // Wiki is read-only?
1283 if ( $this->readOnlyMode->isReadOnly() ) {
1284 return StatusValue::newFatal( wfMessage( 'readonlytext', $this->readOnlyMode->getReason() ) );
1285 }
1286
1287 $permStatus = new PermissionStatus();
1288 if ( !$authorizer(
1289 $action,
1290 SpecialPage::getTitleFor( 'CreateAccount' ),
1291 $permStatus
1292 ) ) {
1293 return $permStatus;
1294 }
1295
1296 $ip = $this->getRequest()->getIP();
1297 if ( $this->blockManager->isDnsBlacklisted( $ip, true /* check $wgProxyWhitelist */ ) ) {
1298 return StatusValue::newFatal( 'sorbs_create_account_reason' );
1299 }
1300
1301 return StatusValue::newGood();
1302 }
1303
1304 /**
1305 * Check whether $creator can create accounts.
1306 *
1307 * @note this method does not guarantee full permissions check, so it should only
1308 * be used to to decide whether to show a form. To authorize the account creation
1309 * action use {@link self::authorizeCreateAccount} instead.
1310 *
1311 * @since 1.39
1312 * @param Authority $creator
1313 * @return StatusValue
1314 */
1315 public function probablyCanCreateAccount( Authority $creator ): StatusValue {
1316 return $this->authorizeInternal(
1317 static function (
1318 string $action,
1319 PageIdentity $target,
1320 PermissionStatus $status
1321 ) use ( $creator ) {
1322 return $creator->probablyCan( $action, $target, $status );
1323 },
1324 'createaccount'
1325 );
1326 }
1327
1328 /**
1329 * Authorize the account creation by $creator
1330 *
1331 * @note this method should be used right before the account is created.
1332 * To check whether a current performer has the potential to create accounts,
1333 * use {@link self::probablyCanCreateAccount} instead.
1334 *
1335 * @since 1.39
1336 * @param Authority $creator
1337 * @return StatusValue
1338 */
1339 public function authorizeCreateAccount( Authority $creator ): StatusValue {
1340 return $this->authorizeInternal(
1341 static function (
1342 string $action,
1343 PageIdentity $target,
1344 PermissionStatus $status
1345 ) use ( $creator ) {
1346 return $creator->authorizeWrite( $action, $target, $status );
1347 },
1348 'createaccount'
1349 );
1350 }
1351
1352 /**
1353 * Start an account creation flow
1354 *
1355 * In addition to the AuthenticationRequests returned by
1356 * $this->getAuthenticationRequests(), a client might include a
1357 * CreateFromLoginAuthenticationRequest from a previous login attempt. If
1358 * <code>
1359 * $createFromLoginAuthenticationRequest->hasPrimaryStateForAction( AuthManager::ACTION_CREATE )
1360 * </code>
1361 * returns true, any AuthenticationRequest::PRIMARY_REQUIRED requests
1362 * should be omitted. If the CreateFromLoginAuthenticationRequest has a
1363 * username set, that username must be used for all other requests.
1364 *
1365 * @param Authority $creator User doing the account creation
1366 * @param AuthenticationRequest[] $reqs
1367 * @param string $returnToUrl Url that REDIRECT responses should eventually
1368 * return to.
1369 * @return AuthenticationResponse
1370 */
1371 public function beginAccountCreation( Authority $creator, array $reqs, $returnToUrl ) {
1372 $session = $this->request->getSession();
1373 if ( $creator->isTemp() ) {
1374 // For a temp account creating a permanent account, we do not want the temporary
1375 // account to be associated with the created permanent account. To avoid this,
1376 // set the session user to a new anonymous user, save it, and set the request
1377 // context from the new session user account. (T393628)
1378 $creator = $this->userFactory->newAnonymous();
1379 $session->setUser( $creator );
1380 // Ensure the temporary account username is also cleared from the session, this is set
1381 // in TempUserCreator::acquireAndStashName
1382 $session->remove( 'TempUser:name' );
1383 $session->save();
1384 $this->setRequestContextUserFromSessionUser();
1385 }
1386 if ( !$this->canCreateAccounts() ) {
1387 // Caller should have called canCreateAccounts()
1388 $session->remove( self::ACCOUNT_CREATION_STATE );
1389 throw new LogicException( 'Account creation is not possible' );
1390 }
1391
1392 try {
1393 $username = AuthenticationRequest::getUsernameFromRequests( $reqs );
1394 } catch ( \UnexpectedValueException $ex ) {
1395 $username = null;
1396 }
1397 if ( $username === null ) {
1398 $this->logger->debug( __METHOD__ . ': No username provided' );
1399 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1400 }
1401
1402 // Permissions check
1403 $status = Status::wrap( $this->authorizeCreateAccount( $creator ) );
1404 if ( !$status->isGood() ) {
1405 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1406 'user' => $username,
1407 'creator' => $creator->getUser()->getName(),
1408 'reason' => $status->getWikiText( false, false, 'en' )
1409 ] );
1410 return AuthenticationResponse::newFail( $status->getMessage() );
1411 }
1412
1413 $status = $this->canCreateAccount(
1414 $username, [ 'flags' => IDBAccessObject::READ_LOCKING, 'creating' => true ]
1415 );
1416 if ( !$status->isGood() ) {
1417 $this->logger->debug( __METHOD__ . ': {user} cannot be created: {reason}', [
1418 'user' => $username,
1419 'creator' => $creator->getUser()->getName(),
1420 'reason' => $status->getWikiText( false, false, 'en' )
1421 ] );
1422 return AuthenticationResponse::newFail( $status->getMessage() );
1423 }
1424
1425 $user = $this->userFactory->newFromName( (string)$username, UserRigorOptions::RIGOR_CREATABLE );
1426 foreach ( $reqs as $req ) {
1427 $req->username = $username;
1428 $req->returnToUrl = $returnToUrl;
1429 if ( $req instanceof UserDataAuthenticationRequest ) {
1430 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable user should be checked and valid here
1431 $status = $req->populateUser( $user );
1432 if ( !$status->isGood() ) {
1433 $status = Status::wrap( $status );
1434 $session->remove( self::ACCOUNT_CREATION_STATE );
1435 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1436 'user' => $user->getName(),
1437 'creator' => $creator->getUser()->getName(),
1438 'reason' => $status->getWikiText( false, false, 'en' ),
1439 ] );
1440 return AuthenticationResponse::newFail( $status->getMessage() );
1441 }
1442 }
1443 }
1444
1445 $this->removeAuthenticationSessionData( null );
1446
1447 $state = [
1448 'username' => $username,
1449 'userid' => 0,
1450 'creatorid' => $creator->getUser()->getId(),
1451 'creatorname' => $creator->getUser()->getName(),
1452 'reqs' => $reqs,
1453 'returnToUrl' => $returnToUrl,
1454 'providerIds' => $this->getProviderIds(),
1455 'primary' => null,
1456 'primaryResponse' => null,
1457 'secondary' => [],
1458 'continueRequests' => [],
1459 'maybeLink' => [],
1460 'ranPreTests' => false,
1461 ];
1462
1463 // Special case: converting a login to an account creation
1464 $req = AuthenticationRequest::getRequestByClass(
1465 $reqs, CreateFromLoginAuthenticationRequest::class
1466 );
1467 if ( $req ) {
1468 $state['maybeLink'] = $req->maybeLink;
1469
1470 if ( $req->createRequest ) {
1471 $reqs[] = $req->createRequest;
1472 $state['reqs'][] = $req->createRequest;
1473 }
1474 }
1475
1476 $session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
1477 $session->persist();
1478 $this->logger->debug( __METHOD__ . ': Proceeding with account creation for {username} by {creator}', [
1479 'username' => $user->getName(),
1480 'creator' => $creator->getUser()->getName(),
1481 ] );
1482
1483 return $this->continueAccountCreation( $reqs );
1484 }
1485
1486 /**
1487 * Continue an account creation flow
1488 * @param AuthenticationRequest[] $reqs
1489 * @return AuthenticationResponse
1490 */
1491 public function continueAccountCreation( array $reqs ) {
1492 $session = $this->request->getSession();
1493 try {
1494 if ( !$this->canCreateAccounts() ) {
1495 // Caller should have called canCreateAccounts()
1496 $session->remove( self::ACCOUNT_CREATION_STATE );
1497 throw new LogicException( 'Account creation is not possible' );
1498 }
1499
1500 $state = $session->getSecret( self::ACCOUNT_CREATION_STATE );
1501 if ( !is_array( $state ) ) {
1502 return AuthenticationResponse::newFail(
1503 wfMessage( 'authmanager-create-not-in-progress' )
1504 );
1505 }
1506 $state['continueRequests'] = [];
1507
1508 // Step 0: Prepare and validate the input
1509
1510 $user = $this->userFactory->newFromName(
1511 (string)$state['username'],
1512 UserRigorOptions::RIGOR_CREATABLE
1513 );
1514 if ( !is_object( $user ) ) {
1515 $session->remove( self::ACCOUNT_CREATION_STATE );
1516 $this->logger->debug( __METHOD__ . ': Invalid username', [
1517 'user' => $state['username'],
1518 ] );
1519 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
1520 }
1521
1522 if ( $state['creatorid'] ) {
1523 $creator = $this->userFactory->newFromId( (int)$state['creatorid'] );
1524 } else {
1525 $creator = $this->userFactory->newAnonymous();
1526 $creator->setName( $state['creatorname'] );
1527 }
1528
1529 if ( $state['providerIds'] !== $this->getProviderIds() ) {
1530 // An inconsistent AuthManagerFilterProviders hook, or site configuration changed
1531 // while the user was in the middle of authentication. The first is a bug, the
1532 // second is rare but expected when deploying a config change. Try handle in a way
1533 // that's useful for both cases.
1534 // @codeCoverageIgnoreStart
1535 MWExceptionHandler::logException( new NormalizedException(
1536 'Authentication failed because of inconsistent provider array',
1537 [ 'old' => json_encode( $state['providerIds'] ), 'new' => json_encode( $this->getProviderIds() ) ]
1538 ) );
1539 $ret = AuthenticationResponse::newFail(
1540 wfMessage( 'authmanager-create-not-in-progress' )
1541 );
1542 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
1543 $session->remove( self::ACCOUNT_CREATION_STATE );
1544 return $ret;
1545 // @codeCoverageIgnoreEnd
1546 }
1547
1548 // Avoid account creation races on double submissions
1549 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
1550 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $user->getName() ) ) );
1551 if ( !$lock ) {
1552 // Don't clear AuthManager::accountCreationState for this code
1553 // path because the process that won the race owns it.
1554 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
1555 'user' => $user->getName(),
1556 'creator' => $creator->getName(),
1557 ] );
1558 return AuthenticationResponse::newFail( wfMessage( 'usernameinprogress' ) );
1559 }
1560
1561 // Permissions check
1562 $status = Status::wrap( $this->authorizeCreateAccount( $creator ) );
1563 if ( !$status->isGood() ) {
1564 $this->logger->debug( __METHOD__ . ': {creator} cannot create users: {reason}', [
1565 'user' => $user->getName(),
1566 'creator' => $creator->getName(),
1567 'reason' => $status->getWikiText( false, false, 'en' )
1568 ] );
1569 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1570 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
1571 $session->remove( self::ACCOUNT_CREATION_STATE );
1572 return $ret;
1573 }
1574
1575 // Load from primary DB for existence check
1576 $user->load( IDBAccessObject::READ_LOCKING );
1577
1578 if ( $state['userid'] === 0 ) {
1579 if ( $user->isRegistered() ) {
1580 $this->logger->debug( __METHOD__ . ': User exists locally', [
1581 'user' => $user->getName(),
1582 'creator' => $creator->getName(),
1583 ] );
1584 $ret = AuthenticationResponse::newFail( wfMessage( 'userexists' ) );
1585 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
1586 $session->remove( self::ACCOUNT_CREATION_STATE );
1587 return $ret;
1588 }
1589 } else {
1590 if ( !$user->isRegistered() ) {
1591 $this->logger->debug( __METHOD__ . ': User does not exist locally when it should', [
1592 'user' => $user->getName(),
1593 'creator' => $creator->getName(),
1594 'expected_id' => $state['userid'],
1595 ] );
1596 throw new \UnexpectedValueException(
1597 "User \"{$state['username']}\" should exist now, but doesn't!"
1598 );
1599 }
1600 if ( $user->getId() !== $state['userid'] ) {
1601 $this->logger->debug( __METHOD__ . ': User ID/name mismatch', [
1602 'user' => $user->getName(),
1603 'creator' => $creator->getName(),
1604 'expected_id' => $state['userid'],
1605 'actual_id' => $user->getId(),
1606 ] );
1607 throw new \UnexpectedValueException(
1608 "User \"{$state['username']}\" exists, but " .
1609 "ID {$user->getId()} !== {$state['userid']}!"
1610 );
1611 }
1612 }
1613 foreach ( $state['reqs'] as $req ) {
1614 if ( $req instanceof UserDataAuthenticationRequest ) {
1615 $status = $req->populateUser( $user );
1616 if ( !$status->isGood() ) {
1617 // This should never happen...
1618 $status = Status::wrap( $status );
1619 $this->logger->debug( __METHOD__ . ': UserData is invalid: {reason}', [
1620 'user' => $user->getName(),
1621 'creator' => $creator->getName(),
1622 'reason' => $status->getWikiText( false, false, 'en' ),
1623 ] );
1624 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1625 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
1626 [ $user, $creator, $ret ]
1627 );
1628 $session->remove( self::ACCOUNT_CREATION_STATE );
1629 return $ret;
1630 }
1631 }
1632 }
1633
1634 foreach ( $reqs as $req ) {
1635 $req->returnToUrl = $state['returnToUrl'];
1636 $req->username = $state['username'];
1637 }
1638
1639 // Run pre-creation tests, if we haven't already
1640 if ( !$state['ranPreTests'] ) {
1641 $providers = $this->getPreAuthenticationProviders() +
1642 $this->getPrimaryAuthenticationProviders() +
1643 $this->getSecondaryAuthenticationProviders();
1644 foreach ( $providers as $id => $provider ) {
1645 $status = $provider->testForAccountCreation( $user, $creator, $reqs );
1646 if ( !$status->isGood() ) {
1647 $this->logger->debug( __METHOD__ . ": Fail in pre-authentication by $id", [
1648 'user' => $user->getName(),
1649 'creator' => $creator->getName(),
1650 ] );
1651 $ret = AuthenticationResponse::newFail(
1652 Status::wrap( $status )->getMessage()
1653 );
1654 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
1655 [ $user, $creator, $ret ]
1656 );
1657 $session->remove( self::ACCOUNT_CREATION_STATE );
1658 return $ret;
1659 }
1660 }
1661
1662 $state['ranPreTests'] = true;
1663 }
1664
1665 // Step 1: Choose a primary authentication provider and call it until it succeeds.
1666
1667 if ( $state['primary'] === null ) {
1668 // We haven't picked a PrimaryAuthenticationProvider yet
1669 foreach ( $this->getPrimaryAuthenticationProviders() as $id => $provider ) {
1670 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_NONE ) {
1671 continue;
1672 }
1673 $res = $provider->beginPrimaryAccountCreation( $user, $creator, $reqs );
1674 switch ( $res->status ) {
1675 case AuthenticationResponse::PASS:
1676 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1677 'user' => $user->getName(),
1678 'creator' => $creator->getName(),
1679 ] );
1680 $state['primary'] = $id;
1681 $state['primaryResponse'] = $res;
1682 break 2;
1683 case AuthenticationResponse::FAIL:
1684 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1685 'user' => $user->getName(),
1686 'creator' => $creator->getName(),
1687 ] );
1688 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
1689 [ $user, $creator, $res ]
1690 );
1691 $session->remove( self::ACCOUNT_CREATION_STATE );
1692 return $res;
1693 case AuthenticationResponse::ABSTAIN:
1694 // Continue loop
1695 break;
1696 case AuthenticationResponse::REDIRECT:
1697 case AuthenticationResponse::UI:
1698 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1699 'user' => $user->getName(),
1700 'creator' => $creator->getName(),
1701 ] );
1702 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1703 $state['primary'] = $id;
1704 $state['continueRequests'] = $res->neededRequests;
1705 $session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
1706 return $res;
1707
1708 // @codeCoverageIgnoreStart
1709 default:
1710 throw new \DomainException(
1711 get_class( $provider ) . "::beginPrimaryAccountCreation() returned $res->status"
1712 );
1713 // @codeCoverageIgnoreEnd
1714 }
1715 }
1716 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
1717 if ( $state['primary'] === null ) {
1718 $this->logger->debug( __METHOD__ . ': Primary creation failed because no provider accepted', [
1719 'user' => $user->getName(),
1720 'creator' => $creator->getName(),
1721 ] );
1722 $ret = AuthenticationResponse::newFail(
1723 wfMessage( 'authmanager-create-no-primary' )
1724 );
1725 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
1726 $session->remove( self::ACCOUNT_CREATION_STATE );
1727 return $ret;
1728 }
1729 } elseif ( $state['primaryResponse'] === null ) {
1730 $provider = $this->getAuthenticationProvider( $state['primary'] );
1731 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
1732 // Configuration changed? Force them to start over.
1733 // @codeCoverageIgnoreStart
1734 $ret = AuthenticationResponse::newFail(
1735 wfMessage( 'authmanager-create-not-in-progress' )
1736 );
1737 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
1738 $session->remove( self::ACCOUNT_CREATION_STATE );
1739 return $ret;
1740 // @codeCoverageIgnoreEnd
1741 }
1742 $id = $provider->getUniqueId();
1743 $res = $provider->continuePrimaryAccountCreation( $user, $creator, $reqs );
1744 switch ( $res->status ) {
1745 case AuthenticationResponse::PASS:
1746 $this->logger->debug( __METHOD__ . ": Primary creation passed by $id", [
1747 'user' => $user->getName(),
1748 'creator' => $creator->getName(),
1749 ] );
1750 $state['primaryResponse'] = $res;
1751 break;
1752 case AuthenticationResponse::FAIL:
1753 $this->logger->debug( __METHOD__ . ": Primary creation failed by $id", [
1754 'user' => $user->getName(),
1755 'creator' => $creator->getName(),
1756 ] );
1757 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
1758 [ $user, $creator, $res ]
1759 );
1760 $session->remove( self::ACCOUNT_CREATION_STATE );
1761 return $res;
1762 case AuthenticationResponse::REDIRECT:
1763 case AuthenticationResponse::UI:
1764 $this->logger->debug( __METHOD__ . ": Primary creation $res->status by $id", [
1765 'user' => $user->getName(),
1766 'creator' => $creator->getName(),
1767 ] );
1768 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1769 $state['continueRequests'] = $res->neededRequests;
1770 $session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
1771 return $res;
1772 default:
1773 throw new \DomainException(
1774 get_class( $provider ) . "::continuePrimaryAccountCreation() returned $res->status"
1775 );
1776 }
1777 }
1778
1779 // Step 2: Primary authentication succeeded. Give hook handlers a chance to interrupt,
1780 // then create the User object and add the user locally.
1781
1782 if ( $state['userid'] === 0 ) {
1783 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set if we passed step 1
1784 $response = $state['primaryResponse'];
1785 if ( !$this->runVerifyHook( self::ACTION_CREATE, $user, $response, $state['primary'] ) ) {
1786 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation',
1787 [ $user, $creator, $response ]
1788 );
1789 $session->remove( self::ACCOUNT_CREATION_STATE );
1790 return $response;
1791 }
1792 $this->logger->info( 'Creating user {user} during account creation', [
1793 'user' => $user->getName(),
1794 'creator' => $creator->getName(),
1795 ] );
1796 $status = $user->addToDatabase();
1797 if ( !$status->isOK() ) {
1798 // @codeCoverageIgnoreStart
1799 $ret = AuthenticationResponse::newFail( $status->getMessage() );
1800 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
1801 $session->remove( self::ACCOUNT_CREATION_STATE );
1802 return $ret;
1803 // @codeCoverageIgnoreEnd
1804 }
1805 $this->setDefaultUserOptions( $user, $creator->isAnon() );
1806 $this->getHookRunner()->onLocalUserCreated( $user, false );
1807 $user->saveSettings();
1808 $state['userid'] = $user->getId();
1809
1810 // Update user count
1811 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
1812
1813 // Watch user's userpage and talk page
1814 $this->watchlistManager->addWatchIgnoringRights( $user, $user->getUserPage() );
1815
1816 // Inform the provider
1817 // @phan-suppress-next-next-line PhanPossiblyUndeclaredVariable
1818 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset Always set in loop before, if passed
1819 $logSubtype = $provider->finishAccountCreation( $user, $creator, $state['primaryResponse'] );
1820
1821 // Log the creation
1822 if ( $this->config->get( MainConfigNames::NewUserLog ) ) {
1823 $isNamed = $creator->isNamed();
1824 $logEntry = new \ManualLogEntry(
1825 'newusers',
1826 $logSubtype ?: ( $isNamed ? 'create2' : 'create' )
1827 );
1828 $logEntry->setPerformer( $isNamed ? $creator : $user );
1829 $logEntry->setTarget( $user->getUserPage() );
1830 /** @var CreationReasonAuthenticationRequest $req */
1831 $req = AuthenticationRequest::getRequestByClass(
1832 $state['reqs'], CreationReasonAuthenticationRequest::class
1833 );
1834 $logEntry->setComment( $req ? $req->reason : '' );
1835 $logEntry->setParameters( [
1836 '4::userid' => $user->getId(),
1837 ] );
1838 $logid = $logEntry->insert();
1839 $logEntry->publish( $logid );
1840 }
1841 }
1842
1843 // Step 3: Iterate over all the secondary authentication providers.
1844
1845 $beginReqs = $state['reqs'];
1846
1847 foreach ( $this->getSecondaryAuthenticationProviders() as $id => $provider ) {
1848 if ( !isset( $state['secondary'][$id] ) ) {
1849 // This provider isn't started yet, so we pass it the set
1850 // of reqs from beginAuthentication instead of whatever
1851 // might have been used by a previous provider in line.
1852 $func = 'beginSecondaryAccountCreation';
1853 $res = $provider->beginSecondaryAccountCreation( $user, $creator, $beginReqs );
1854 } elseif ( !$state['secondary'][$id] ) {
1855 $func = 'continueSecondaryAccountCreation';
1856 $res = $provider->continueSecondaryAccountCreation( $user, $creator, $reqs );
1857 } else {
1858 continue;
1859 }
1860 switch ( $res->status ) {
1861 case AuthenticationResponse::PASS:
1862 $this->logger->debug( __METHOD__ . ": Secondary creation passed by $id", [
1863 'user' => $user->getName(),
1864 'creator' => $creator->getName(),
1865 ] );
1866 // fall through
1867 case AuthenticationResponse::ABSTAIN:
1868 $state['secondary'][$id] = true;
1869 break;
1870 case AuthenticationResponse::REDIRECT:
1871 case AuthenticationResponse::UI:
1872 $this->logger->debug( __METHOD__ . ": Secondary creation $res->status by $id", [
1873 'user' => $user->getName(),
1874 'creator' => $creator->getName(),
1875 ] );
1876 $this->fillRequests( $res->neededRequests, self::ACTION_CREATE, null );
1877 $state['secondary'][$id] = false;
1878 $state['continueRequests'] = $res->neededRequests;
1879 $session->setSecret( self::ACCOUNT_CREATION_STATE, $state );
1880 return $res;
1881 case AuthenticationResponse::FAIL:
1882 throw new \DomainException(
1883 get_class( $provider ) . "::{$func}() returned $res->status." .
1884 ' Secondary providers are not allowed to fail account creation, that' .
1885 ' should have been done via testForAccountCreation().'
1886 );
1887 // @codeCoverageIgnoreStart
1888 default:
1889 throw new \DomainException(
1890 get_class( $provider ) . "::{$func}() returned $res->status"
1891 );
1892 // @codeCoverageIgnoreEnd
1893 }
1894 }
1895
1896 $id = $user->getId();
1897 $name = $user->getName();
1898 $req = new CreatedAccountAuthenticationRequest( $id, $name );
1899 $ret = AuthenticationResponse::newPass( $name );
1900 $ret->loginRequest = $req;
1901 $this->createdAccountAuthenticationRequests[] = $req;
1902
1903 $this->logger->info( __METHOD__ . ': Account creation succeeded for {user}', [
1904 'user' => $user->getName(),
1905 'creator' => $creator->getName(),
1906 ] );
1907
1908 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $creator, $ret ] );
1909 $session->remove( self::ACCOUNT_CREATION_STATE );
1910 $this->removeAuthenticationSessionData( null );
1911 return $ret;
1912 } catch ( \Exception $ex ) {
1913 $session->remove( self::ACCOUNT_CREATION_STATE );
1914 throw $ex;
1915 }
1916 }
1917
1918 /**
1919 * Auto-create an account, and optionally log into that account
1920 *
1921 * PrimaryAuthenticationProviders can invoke this method by returning a PASS from
1922 * beginPrimaryAuthentication/continuePrimaryAuthentication with the username of a
1923 * non-existing user. SessionProviders can invoke it by returning a SessionInfo with
1924 * the username of a non-existing user from provideSessionInfo(). Calling this method
1925 * explicitly (e.g. from a maintenance script) is also fine.
1926 *
1927 * @param User $user User to auto-create
1928 * @param string $source What caused the auto-creation? This must be one of:
1929 * - the ID of a PrimaryAuthenticationProvider,
1930 * - one of the self::AUTOCREATE_SOURCE_* constants
1931 * @param bool $login Whether to also log the user in
1932 * @param bool $log Whether to generate a user creation log entry (since 1.36)
1933 * @param Authority|null $performer The performer of the action to use for user rights
1934 * checking. Normally null to indicate an anonymous performer. Added in 1.42 for
1935 * Special:CreateLocalAccount (T234371).
1936 *
1937 * @return Status Good if user was created, Ok if user already existed, otherwise Fatal
1938 */
1939 public function autoCreateUser(
1940 User $user,
1941 $source,
1942 $login = true,
1943 $log = true,
1944 ?Authority $performer = null
1945 ) {
1946 $validSources = [
1947 self::AUTOCREATE_SOURCE_SESSION,
1948 self::AUTOCREATE_SOURCE_MAINT,
1949 self::AUTOCREATE_SOURCE_TEMP
1950 ];
1951 if ( !in_array( $source, $validSources, true )
1952 && !$this->getAuthenticationProvider( $source ) instanceof PrimaryAuthenticationProvider
1953 ) {
1954 throw new InvalidArgumentException( "Unknown auto-creation source: $source" );
1955 }
1956
1957 $username = $user->getName();
1958
1959 // Try the local user from the replica DB, then fall back to the primary.
1960 $localUserIdentity = $this->userIdentityLookup->getUserIdentityByName( $username );
1961 // @codeCoverageIgnoreStart
1962 if ( ( !$localUserIdentity || !$localUserIdentity->isRegistered() )
1963 && $this->loadBalancer->getReaderIndex() !== 0
1964 ) {
1965 $localUserIdentity = $this->userIdentityLookup->getUserIdentityByName(
1966 $username, IDBAccessObject::READ_LATEST
1967 );
1968 }
1969 // @codeCoverageIgnoreEnd
1970 $localId = ( $localUserIdentity && $localUserIdentity->isRegistered() )
1971 ? $localUserIdentity->getId()
1972 : null;
1973
1974 if ( $localId ) {
1975 $this->logger->debug( __METHOD__ . ': {username} already exists locally', [
1976 'username' => $username,
1977 ] );
1978 $user->setId( $localId );
1979
1980 // Can't rely on a replica read, not even when getUserIdentityByName() used
1981 // READ_NORMAL, because that method has an in-process cache not shared
1982 // with loadFromId.
1983 $user->loadFromId( IDBAccessObject::READ_LATEST );
1984 if ( $login ) {
1985 $remember = $source === self::AUTOCREATE_SOURCE_TEMP;
1986 $this->setSessionDataForUser( $user, $remember, false );
1987 }
1988 return Status::newGood()->warning( 'userexists' );
1989 }
1990
1991 // Wiki is read-only?
1992 if ( $this->readOnlyMode->isReadOnly() ) {
1993 $reason = $this->readOnlyMode->getReason();
1994 $this->logger->debug( __METHOD__ . ': denied because of read only mode: {reason}', [
1995 'username' => $username,
1996 'reason' => $reason,
1997 ] );
1998 $user->setId( 0 );
1999 $user->loadFromId();
2000 return Status::newFatal( wfMessage( 'readonlytext', $reason ) );
2001 }
2002
2003 // If there is a non-anonymous performer, don't use their session
2004 $session = null;
2005 if ( !$performer || $performer->getUser()->equals( $user ) ) {
2006 $session = $this->request->getSession();
2007 }
2008
2009 // Check the session, if we tried to create this user already there's
2010 // no point in retrying.
2011 if ( $session && $session->get( self::AUTOCREATE_BLOCKLIST ) ) {
2012 $this->logger->debug( __METHOD__ . ': blacklisted in session {sessionid}', [
2013 'username' => $username,
2014 'sessionid' => $session->getId(),
2015 ] );
2016 $user->setId( 0 );
2017 $user->loadFromId();
2018 $reason = $session->get( self::AUTOCREATE_BLOCKLIST );
2019 if ( $reason instanceof StatusValue ) {
2020 return Status::wrap( $reason );
2021 } else {
2022 return Status::newFatal( $reason );
2023 }
2024 }
2025
2026 // Is the username usable? (Previously isCreatable() was checked here but
2027 // that doesn't work with auto-creation of TempUser accounts by CentralAuth)
2028 if ( !$this->userNameUtils->isUsable( $username ) ) {
2029 $this->logger->debug( __METHOD__ . ': name "{username}" is not usable', [
2030 'username' => $username,
2031 ] );
2032 if ( $session ) {
2033 $session->set( self::AUTOCREATE_BLOCKLIST, 'noname' );
2034 }
2035 $user->setId( 0 );
2036 $user->loadFromId();
2037 return Status::newFatal( 'noname' );
2038 }
2039
2040 // Is the IP user able to create accounts?
2041 $performer ??= $this->userFactory->newAnonymous();
2042 $bypassAuthorization = $session ? $session->getProvider()->canAlwaysAutocreate() : false;
2043 if ( $source !== self::AUTOCREATE_SOURCE_MAINT && !$bypassAuthorization ) {
2044 $status = $this->authorizeAutoCreateAccount( $performer );
2045 if ( !$status->isOK() ) {
2046 $this->logger->debug( __METHOD__ . ': cannot create or autocreate accounts', [
2047 'username' => $username,
2048 'creator' => $performer->getUser()->getName(),
2049 ] );
2050 if ( $session ) {
2051 $session->set( self::AUTOCREATE_BLOCKLIST, $status );
2052 $session->persist();
2053 }
2054 $user->setId( 0 );
2055 $user->loadFromId();
2056 return Status::wrap( $status );
2057 }
2058 }
2059
2060 // Avoid account creation races on double submissions
2061 $cache = MediaWikiServices::getInstance()->getObjectCacheFactory()->getLocalClusterInstance();
2062 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
2063 if ( !$lock ) {
2064 $this->logger->debug( __METHOD__ . ': Could not acquire account creation lock', [
2065 'user' => $username,
2066 ] );
2067 $user->setId( 0 );
2068 $user->loadFromId();
2069 return Status::newFatal( 'usernameinprogress' );
2070 }
2071
2072 // Denied by providers?
2073 $options = [
2074 'flags' => IDBAccessObject::READ_LATEST,
2075 'creating' => true,
2076 'canAlwaysAutocreate' => $session && $session->getProvider()->canAlwaysAutocreate(),
2077 ];
2078 $providers = $this->getPreAuthenticationProviders() +
2079 $this->getPrimaryAuthenticationProviders() +
2080 $this->getSecondaryAuthenticationProviders();
2081 foreach ( $providers as $provider ) {
2082 $status = $provider->testUserForCreation( $user, $source, $options );
2083 if ( !$status->isGood() ) {
2084 $ret = Status::wrap( $status );
2085 $this->logger->debug( __METHOD__ . ': Provider denied creation of {username}: {reason}', [
2086 'username' => $username,
2087 'reason' => $ret->getWikiText( false, false, 'en' ),
2088 ] );
2089 if ( $session ) {
2090 $session->set( self::AUTOCREATE_BLOCKLIST, $status );
2091 }
2092 $user->setId( 0 );
2093 $user->loadFromId();
2094 return $ret;
2095 }
2096 }
2097
2098 $backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
2099 if ( $cache->get( $backoffKey ) ) {
2100 $this->logger->debug( __METHOD__ . ': {username} denied by prior creation attempt failures', [
2101 'username' => $username,
2102 ] );
2103 $user->setId( 0 );
2104 $user->loadFromId();
2105 return Status::newFatal( 'authmanager-autocreate-exception' );
2106 }
2107
2108 // Checks passed, create the user...
2109 $from = $_SERVER['REQUEST_URI'] ?? 'CLI';
2110 $this->logger->info( __METHOD__ . ': creating new user ({username}) - from: {from}', [
2111 'username' => $username,
2112 'from' => $from,
2113 ] );
2114
2115 // Ignore warnings about primary connections/writes...hard to avoid here
2116 $trxProfiler = \Profiler::instance()->getTransactionProfiler();
2117 $scope = $trxProfiler->silenceForScope( $trxProfiler::EXPECTATION_REPLICAS_ONLY );
2118 try {
2119 $status = $user->addToDatabase();
2120 if ( !$status->isOK() ) {
2121 // Double-check for a race condition (T70012). We make use of the fact that when
2122 // addToDatabase fails due to the user already existing, the user object gets loaded.
2123 if ( $user->getId() ) {
2124 $this->logger->info( __METHOD__ . ': {username} already exists locally (race)', [
2125 'username' => $username,
2126 ] );
2127 if ( $login ) {
2128 $remember = $source === self::AUTOCREATE_SOURCE_TEMP;
2129 $this->setSessionDataForUser( $user, $remember, false );
2130 }
2131 $status = Status::newGood()->warning( 'userexists' );
2132 } else {
2133 $this->logger->error( __METHOD__ . ': {username} failed with message {msg}', [
2134 'username' => $username,
2135 'msg' => $status->getWikiText( false, false, 'en' )
2136 ] );
2137 $user->setId( 0 );
2138 $user->loadFromId();
2139 }
2140 return $status;
2141 }
2142 } catch ( \Exception $ex ) {
2143 $this->logger->error( __METHOD__ . ': {username} failed with exception {exception}', [
2144 'username' => $username,
2145 'exception' => $ex,
2146 ] );
2147 // Do not keep throwing errors for a while
2148 $cache->set( $backoffKey, 1, 600 );
2149 // Bubble up error; which should normally trigger DB rollbacks
2150 throw $ex;
2151 }
2152
2153 $this->setDefaultUserOptions( $user, false );
2154
2155 // Inform the providers
2156 $this->callMethodOnProviders( self::CALL_PRIMARY | self::CALL_SECONDARY, 'autoCreatedAccount',
2157 [ $user, $source ]
2158 );
2159
2160 $this->getHookRunner()->onLocalUserCreated( $user, true );
2161 $user->saveSettings();
2162
2163 // Update user count
2164 DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'users' => 1 ] ) );
2165 // Watch user's userpage and talk page (except temp users)
2166 if ( $source !== self::AUTOCREATE_SOURCE_TEMP ) {
2167 DeferredUpdates::addCallableUpdate( function () use ( $user ) {
2168 $this->watchlistManager->addWatchIgnoringRights( $user, $user->getUserPage() );
2169 } );
2170 }
2171
2172 // Log the creation
2173 if ( $this->config->get( MainConfigNames::NewUserLog ) && $log ) {
2174 $logEntry = new \ManualLogEntry( 'newusers', 'autocreate' );
2175 $logEntry->setPerformer( $user );
2176 $logEntry->setTarget( $user->getUserPage() );
2177 $logEntry->setComment( '' );
2178 $logEntry->setParameters( [
2179 '4::userid' => $user->getId(),
2180 ] );
2181 $logEntry->insert();
2182 }
2183
2184 ScopedCallback::consume( $scope );
2185
2186 if ( $login ) {
2187 $remember = $source === self::AUTOCREATE_SOURCE_TEMP;
2188 $this->setSessionDataForUser( $user, $remember, false );
2189 }
2190
2191 return Status::newGood();
2192 }
2193
2194 /**
2195 * Authorize automatic account creation. This is like account creation but
2196 * checks the autocreateaccount right instead of the createaccount right.
2197 *
2198 * @param Authority $creator
2199 * @return StatusValue
2200 */
2201 private function authorizeAutoCreateAccount( Authority $creator ) {
2202 return $this->authorizeInternal(
2203 static function (
2204 string $action,
2205 PageIdentity $target,
2206 PermissionStatus $status
2207 ) use ( $creator ) {
2208 return $creator->authorizeWrite( $action, $target, $status );
2209 },
2210 'autocreateaccount'
2211 );
2212 }
2213
2214 // endregion -- end of Account creation
2215
2216 /***************************************************************************/
2217 // region Account linking
2218 /** @name Account linking */
2219
2220 /**
2221 * Determine whether accounts can be linked
2222 * @return bool
2223 */
2224 public function canLinkAccounts() {
2225 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2226 if ( $provider->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
2227 return true;
2228 }
2229 }
2230 return false;
2231 }
2232
2233 /**
2234 * Start an account linking flow
2235 *
2236 * @param User $user User being linked
2237 * @param AuthenticationRequest[] $reqs
2238 * @param string $returnToUrl Url that REDIRECT responses should eventually
2239 * return to.
2240 * @return AuthenticationResponse
2241 */
2242 public function beginAccountLink( User $user, array $reqs, $returnToUrl ) {
2243 $session = $this->request->getSession();
2244 $session->remove( self::ACCOUNT_LINK_STATE );
2245
2246 if ( !$this->canLinkAccounts() ) {
2247 // Caller should have called canLinkAccounts()
2248 throw new LogicException( 'Account linking is not possible' );
2249 }
2250
2251 if ( !$user->isRegistered() ) {
2252 if ( !$this->userNameUtils->isUsable( $user->getName() ) ) {
2253 $msg = wfMessage( 'noname' );
2254 } else {
2255 $msg = wfMessage( 'authmanager-userdoesnotexist', $user->getName() );
2256 }
2257 return AuthenticationResponse::newFail( $msg );
2258 }
2259 foreach ( $reqs as $req ) {
2260 $req->username = $user->getName();
2261 $req->returnToUrl = $returnToUrl;
2262 }
2263
2264 $this->removeAuthenticationSessionData( null );
2265
2266 $providers = $this->getPreAuthenticationProviders();
2267 foreach ( $providers as $id => $provider ) {
2268 $status = $provider->testForAccountLink( $user );
2269 if ( !$status->isGood() ) {
2270 $this->logger->debug( __METHOD__ . ": Account linking pre-check failed by $id", [
2271 'user' => $user->getName(),
2272 ] );
2273 $ret = AuthenticationResponse::newFail(
2274 Status::wrap( $status )->getMessage()
2275 );
2276 $this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink', [ $user, $ret ] );
2277 return $ret;
2278 }
2279 }
2280
2281 $state = [
2282 'username' => $user->getName(),
2283 'userid' => $user->getId(),
2284 'returnToUrl' => $returnToUrl,
2285 'providerIds' => $this->getProviderIds(),
2286 'primary' => null,
2287 'continueRequests' => [],
2288 ];
2289
2290 $providers = $this->getPrimaryAuthenticationProviders();
2291 foreach ( $providers as $id => $provider ) {
2292 if ( $provider->accountCreationType() !== PrimaryAuthenticationProvider::TYPE_LINK ) {
2293 continue;
2294 }
2295
2296 $res = $provider->beginPrimaryAccountLink( $user, $reqs );
2297 switch ( $res->status ) {
2298 case AuthenticationResponse::PASS:
2299 $this->logger->info( "Account linked to {user} by $id", [
2300 'user' => $user->getName(),
2301 ] );
2302 $this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
2303 [ $user, $res ]
2304 );
2305 return $res;
2306
2307 case AuthenticationResponse::FAIL:
2308 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
2309 'user' => $user->getName(),
2310 ] );
2311 $this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
2312 [ $user, $res ]
2313 );
2314 return $res;
2315
2316 case AuthenticationResponse::ABSTAIN:
2317 // Continue loop
2318 break;
2319
2320 case AuthenticationResponse::REDIRECT:
2321 case AuthenticationResponse::UI:
2322 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
2323 'user' => $user->getName(),
2324 ] );
2325 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
2326 $state['primary'] = $id;
2327 $state['continueRequests'] = $res->neededRequests;
2328 $session->setSecret( self::ACCOUNT_LINK_STATE, $state );
2329 $session->persist();
2330 return $res;
2331
2332 // @codeCoverageIgnoreStart
2333 default:
2334 throw new \DomainException(
2335 get_class( $provider ) . "::beginPrimaryAccountLink() returned $res->status"
2336 );
2337 // @codeCoverageIgnoreEnd
2338 }
2339 }
2340
2341 $this->logger->debug( __METHOD__ . ': Account linking failed because no provider accepted', [
2342 'user' => $user->getName(),
2343 ] );
2344 $ret = AuthenticationResponse::newFail(
2345 wfMessage( 'authmanager-link-no-primary' )
2346 );
2347 $this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink', [ $user, $ret ] );
2348 return $ret;
2349 }
2350
2351 /**
2352 * Continue an account linking flow
2353 * @param AuthenticationRequest[] $reqs
2354 * @return AuthenticationResponse
2355 */
2356 public function continueAccountLink( array $reqs ) {
2357 $session = $this->request->getSession();
2358 try {
2359 if ( !$this->canLinkAccounts() ) {
2360 // Caller should have called canLinkAccounts()
2361 $session->remove( self::ACCOUNT_LINK_STATE );
2362 throw new LogicException( 'Account linking is not possible' );
2363 }
2364
2365 $state = $session->getSecret( self::ACCOUNT_LINK_STATE );
2366 if ( !is_array( $state ) ) {
2367 return AuthenticationResponse::newFail(
2368 wfMessage( 'authmanager-link-not-in-progress' )
2369 );
2370 }
2371 $state['continueRequests'] = [];
2372
2373 // Step 0: Prepare and validate the input
2374
2375 $user = $this->userFactory->newFromName(
2376 (string)$state['username'],
2377 UserRigorOptions::RIGOR_USABLE
2378 );
2379 if ( !is_object( $user ) ) {
2380 $session->remove( self::ACCOUNT_LINK_STATE );
2381 return AuthenticationResponse::newFail( wfMessage( 'noname' ) );
2382 }
2383 if ( $user->getId() !== $state['userid'] ) {
2384 throw new \UnexpectedValueException(
2385 "User \"{$state['username']}\" is valid, but " .
2386 "ID {$user->getId()} !== {$state['userid']}!"
2387 );
2388 }
2389
2390 if ( $state['providerIds'] !== $this->getProviderIds() ) {
2391 // An inconsistent AuthManagerFilterProviders hook, or site configuration changed
2392 // while the user was in the middle of authentication. The first is a bug, the
2393 // second is rare but expected when deploying a config change. Try handle in a way
2394 // that's useful for both cases.
2395 // @codeCoverageIgnoreStart
2396 MWExceptionHandler::logException( new NormalizedException(
2397 'Authentication failed because of inconsistent provider array',
2398 [ 'old' => json_encode( $state['providerIds'] ), 'new' => json_encode( $this->getProviderIds() ) ]
2399 ) );
2400 $ret = AuthenticationResponse::newFail(
2401 wfMessage( 'authmanager-link-not-in-progress' )
2402 );
2403 $this->callMethodOnProviders( self::CALL_ALL, 'postAccountCreation', [ $user, $ret ] );
2404 $session->remove( self::ACCOUNT_LINK_STATE );
2405 return $ret;
2406 // @codeCoverageIgnoreEnd
2407 }
2408
2409 foreach ( $reqs as $req ) {
2410 $req->username = $state['username'];
2411 $req->returnToUrl = $state['returnToUrl'];
2412 }
2413
2414 // Step 1: Call the primary again until it succeeds
2415
2416 $provider = $this->getAuthenticationProvider( $state['primary'] );
2417 if ( !$provider instanceof PrimaryAuthenticationProvider ) {
2418 // Configuration changed? Force them to start over.
2419 // @codeCoverageIgnoreStart
2420 $ret = AuthenticationResponse::newFail(
2421 wfMessage( 'authmanager-link-not-in-progress' )
2422 );
2423 $this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink', [ $user, $ret ] );
2424 $session->remove( self::ACCOUNT_LINK_STATE );
2425 return $ret;
2426 // @codeCoverageIgnoreEnd
2427 }
2428 $id = $provider->getUniqueId();
2429 $res = $provider->continuePrimaryAccountLink( $user, $reqs );
2430 switch ( $res->status ) {
2431 case AuthenticationResponse::PASS:
2432 $this->logger->info( "Account linked to {user} by $id", [
2433 'user' => $user->getName(),
2434 ] );
2435 $this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
2436 [ $user, $res ]
2437 );
2438 $session->remove( self::ACCOUNT_LINK_STATE );
2439 return $res;
2440 case AuthenticationResponse::FAIL:
2441 $this->logger->debug( __METHOD__ . ": Account linking failed by $id", [
2442 'user' => $user->getName(),
2443 ] );
2444 $this->callMethodOnProviders( self::CALL_PRE | self::CALL_PRIMARY, 'postAccountLink',
2445 [ $user, $res ]
2446 );
2447 $session->remove( self::ACCOUNT_LINK_STATE );
2448 return $res;
2449 case AuthenticationResponse::REDIRECT:
2450 case AuthenticationResponse::UI:
2451 $this->logger->debug( __METHOD__ . ": Account linking $res->status by $id", [
2452 'user' => $user->getName(),
2453 ] );
2454 $this->fillRequests( $res->neededRequests, self::ACTION_LINK, $user->getName() );
2455 $state['continueRequests'] = $res->neededRequests;
2456 $session->setSecret( self::ACCOUNT_LINK_STATE, $state );
2457 return $res;
2458 default:
2459 throw new \DomainException(
2460 get_class( $provider ) . "::continuePrimaryAccountLink() returned $res->status"
2461 );
2462 }
2463 } catch ( \Exception $ex ) {
2464 $session->remove( self::ACCOUNT_LINK_STATE );
2465 throw $ex;
2466 }
2467 }
2468
2469 // endregion -- end of Account linking
2470
2471 /***************************************************************************/
2472 // region Information methods
2473 /** @name Information methods */
2474
2475 /**
2476 * Return the applicable list of AuthenticationRequests
2477 *
2478 * Possible values for $action:
2479 * - ACTION_LOGIN: Valid for passing to beginAuthentication
2480 * - ACTION_LOGIN_CONTINUE: Valid for passing to continueAuthentication in the current state
2481 * - ACTION_CREATE: Valid for passing to beginAccountCreation
2482 * - ACTION_CREATE_CONTINUE: Valid for passing to continueAccountCreation in the current state
2483 * - ACTION_LINK: Valid for passing to beginAccountLink
2484 * - ACTION_LINK_CONTINUE: Valid for passing to continueAccountLink in the current state
2485 * - ACTION_CHANGE: Valid for passing to changeAuthenticationData to change credentials
2486 * - ACTION_REMOVE: Valid for passing to changeAuthenticationData to remove credentials.
2487 * - ACTION_UNLINK: Same as ACTION_REMOVE, but limited to linked accounts.
2488 *
2489 * @param string $action One of the AuthManager::ACTION_* constants
2490 * @param UserIdentity|null $user User being acted on, instead of the current user.
2491 * @return AuthenticationRequest[]
2492 */
2493 public function getAuthenticationRequests( $action, ?UserIdentity $user = null ) {
2494 $options = [];
2495 $providerAction = $action;
2496
2497 // Figure out which providers to query
2498 switch ( $action ) {
2499 case self::ACTION_LOGIN:
2500 case self::ACTION_CREATE:
2501 $providers = $this->getPreAuthenticationProviders() +
2502 $this->getPrimaryAuthenticationProviders() +
2503 $this->getSecondaryAuthenticationProviders();
2504 break;
2505
2506 case self::ACTION_LOGIN_CONTINUE:
2507 $state = $this->request->getSession()->getSecret( self::AUTHN_STATE );
2508 return is_array( $state ) ? $state['continueRequests'] : [];
2509
2510 case self::ACTION_CREATE_CONTINUE:
2511 $state = $this->request->getSession()->getSecret( self::ACCOUNT_CREATION_STATE );
2512 return is_array( $state ) ? $state['continueRequests'] : [];
2513
2514 case self::ACTION_LINK:
2515 $providers = [];
2516 foreach ( $this->getPrimaryAuthenticationProviders() as $p ) {
2517 if ( $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
2518 $providers[] = $p;
2519 }
2520 }
2521 break;
2522
2523 case self::ACTION_UNLINK:
2524 $providers = [];
2525 foreach ( $this->getPrimaryAuthenticationProviders() as $p ) {
2526 if ( $p->accountCreationType() === PrimaryAuthenticationProvider::TYPE_LINK ) {
2527 $providers[] = $p;
2528 }
2529 }
2530
2531 // To providers, unlink and remove are identical.
2532 $providerAction = self::ACTION_REMOVE;
2533 break;
2534
2535 case self::ACTION_LINK_CONTINUE:
2536 $state = $this->request->getSession()->getSecret( self::ACCOUNT_LINK_STATE );
2537 return is_array( $state ) ? $state['continueRequests'] : [];
2538
2539 case self::ACTION_CHANGE:
2540 case self::ACTION_REMOVE:
2541 $providers = $this->getPrimaryAuthenticationProviders() +
2542 $this->getSecondaryAuthenticationProviders();
2543 break;
2544
2545 // @codeCoverageIgnoreStart
2546 default:
2547 throw new \DomainException( __METHOD__ . ": Invalid action \"$action\"" );
2548 }
2549 // @codeCoverageIgnoreEnd
2550
2551 return $this->getAuthenticationRequestsInternal( $providerAction, $options, $providers, $user );
2552 }
2553
2554 /**
2555 * Internal request lookup for self::getAuthenticationRequests
2556 *
2557 * @param string $providerAction Action to pass to providers
2558 * @param array $options Options to pass to providers
2559 * @param AuthenticationProvider[] $providers
2560 * @param UserIdentity|null $user being acted on
2561 * @return AuthenticationRequest[]
2562 */
2563 private function getAuthenticationRequestsInternal(
2564 $providerAction, array $options, array $providers, ?UserIdentity $user = null
2565 ) {
2566 $user = $user ?: RequestContext::getMain()->getUser();
2567 $options['username'] = $user->isRegistered() ? $user->getName() : null;
2568
2569 // Query them and merge results
2570 $reqs = [];
2571 foreach ( $providers as $provider ) {
2572 $isPrimary = $provider instanceof PrimaryAuthenticationProvider;
2573 foreach ( $provider->getAuthenticationRequests( $providerAction, $options ) as $req ) {
2574 $id = $req->getUniqueId();
2575
2576 // If a required request if from a Primary, mark it as "primary-required" instead
2577 if ( $isPrimary && $req->required ) {
2578 $req->required = AuthenticationRequest::PRIMARY_REQUIRED;
2579 }
2580
2581 if (
2582 !isset( $reqs[$id] )
2583 || $req->required === AuthenticationRequest::REQUIRED
2584 || $reqs[$id] === AuthenticationRequest::OPTIONAL
2585 ) {
2586 $reqs[$id] = $req;
2587 }
2588 }
2589 }
2590
2591 // AuthManager has its own req for some actions
2592 switch ( $providerAction ) {
2593 case self::ACTION_LOGIN:
2594 $reqs[] = new RememberMeAuthenticationRequest(
2595 $this->config->get( MainConfigNames::RememberMe ) );
2596 $options['username'] = null; // Don't fill in the username below
2597 break;
2598
2599 case self::ACTION_CREATE:
2600 $reqs[] = new UsernameAuthenticationRequest;
2601 $reqs[] = new UserDataAuthenticationRequest;
2602
2603 // Registered users should be prompted to provide a rationale for account creations,
2604 // except for the case of a temporary user registering a full account (T328718).
2605 if (
2606 $options['username'] !== null &&
2607 !$this->userNameUtils->isTemp( $options['username'] )
2608 ) {
2609 $reqs[] = new CreationReasonAuthenticationRequest;
2610 $options['username'] = null; // Don't fill in the username below
2611 }
2612 break;
2613 }
2614
2615 // Fill in reqs data
2616 $this->fillRequests( $reqs, $providerAction, $options['username'], true );
2617
2618 // For self::ACTION_CHANGE, filter out any that something else *doesn't* allow changing
2619 if ( $providerAction === self::ACTION_CHANGE || $providerAction === self::ACTION_REMOVE ) {
2620 $reqs = array_filter( $reqs, function ( $req ) {
2621 return $this->allowsAuthenticationDataChange( $req, false )->isGood();
2622 } );
2623 }
2624
2625 return array_values( $reqs );
2626 }
2627
2628 /**
2629 * Set values in an array of requests
2630 * @param AuthenticationRequest[] &$reqs
2631 * @param string $action
2632 * @param string|null $username
2633 * @param bool $forceAction
2634 */
2635 private function fillRequests( array &$reqs, $action, $username, $forceAction = false ) {
2636 foreach ( $reqs as $req ) {
2637 if ( !$req->action || $forceAction ) {
2638 $req->action = $action;
2639 }
2640 $req->username ??= $username;
2641 }
2642 }
2643
2644 /**
2645 * Determine whether a username exists
2646 * @param string $username
2647 * @param int $flags Bitfield of IDBAccessObject::READ_* constants
2648 * @return bool
2649 */
2650 public function userExists( $username, $flags = IDBAccessObject::READ_NORMAL ) {
2651 foreach ( $this->getPrimaryAuthenticationProviders() as $provider ) {
2652 if ( $provider->testUserExists( $username, $flags ) ) {
2653 return true;
2654 }
2655 }
2656
2657 return false;
2658 }
2659
2660 /**
2661 * Determine whether a user property should be allowed to be changed.
2662 *
2663 * Supported properties are:
2664 * - emailaddress
2665 * - realname
2666 * - nickname
2667 *
2668 * @param string $property
2669 * @return bool
2670 */
2671 public function allowsPropertyChange( $property ) {
2672 $providers = $this->getPrimaryAuthenticationProviders() +
2673 $this->getSecondaryAuthenticationProviders();
2674 foreach ( $providers as $provider ) {
2675 if ( !$provider->providerAllowsPropertyChange( $property ) ) {
2676 return false;
2677 }
2678 }
2679 return true;
2680 }
2681
2682 /**
2683 * Get a provider by ID
2684 * @note This is public so extensions can check whether their own provider
2685 * is installed and so they can read its configuration if necessary.
2686 * Other uses are not recommended.
2687 * @param string $id
2688 * @return AuthenticationProvider|null
2689 */
2690 public function getAuthenticationProvider( $id ) {
2691 // Fast version
2692 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2693 return $this->allAuthenticationProviders[$id];
2694 }
2695
2696 // Slow version: instantiate each kind and check
2697 $providers = $this->getPrimaryAuthenticationProviders();
2698 if ( isset( $providers[$id] ) ) {
2699 return $providers[$id];
2700 }
2701 $providers = $this->getSecondaryAuthenticationProviders();
2702 if ( isset( $providers[$id] ) ) {
2703 return $providers[$id];
2704 }
2705 $providers = $this->getPreAuthenticationProviders();
2706 if ( isset( $providers[$id] ) ) {
2707 return $providers[$id];
2708 }
2709
2710 return null;
2711 }
2712
2713 // endregion -- end of Information methods
2714
2715 /***************************************************************************/
2716 // region Internal methods
2717 /** @name Internal methods */
2718
2719 /**
2720 * Store authentication in the current session
2721 * @note For use by AuthenticationProviders only
2722 * @param string $key
2723 * @param mixed $data Must be serializable
2724 */
2725 public function setAuthenticationSessionData( $key, $data ) {
2726 $session = $this->request->getSession();
2727 $arr = $session->getSecret( 'authData' );
2728 if ( !is_array( $arr ) ) {
2729 $arr = [];
2730 }
2731 $arr[$key] = $data;
2732 $session->setSecret( 'authData', $arr );
2733 }
2734
2735 /**
2736 * Fetch authentication data from the current session
2737 * @note For use by AuthenticationProviders only
2738 * @param string $key
2739 * @param mixed|null $default
2740 * @return mixed
2741 */
2742 public function getAuthenticationSessionData( $key, $default = null ) {
2743 $arr = $this->request->getSession()->getSecret( 'authData' );
2744 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2745 return $arr[$key];
2746 } else {
2747 return $default;
2748 }
2749 }
2750
2751 /**
2752 * Remove authentication data
2753 * @note For use by AuthenticationProviders
2754 * @param string|null $key If null, all data is removed
2755 */
2756 public function removeAuthenticationSessionData( $key ) {
2757 $session = $this->request->getSession();
2758 if ( $key === null ) {
2759 $session->remove( 'authData' );
2760 } else {
2761 $arr = $session->getSecret( 'authData' );
2762 if ( is_array( $arr ) && array_key_exists( $key, $arr ) ) {
2763 unset( $arr[$key] );
2764 $session->setSecret( 'authData', $arr );
2765 }
2766 }
2767 }
2768
2769 /**
2770 * Create an array of AuthenticationProviders from an array of ObjectFactory specs
2771 * @param string $class
2772 * @param array[] $specs
2773 * @return AuthenticationProvider[]
2774 */
2775 protected function providerArrayFromSpecs( $class, array $specs ) {
2776 $i = 0;
2777 foreach ( $specs as &$spec ) {
2778 $spec = [ 'sort2' => $i++ ] + $spec + [ 'sort' => 0 ];
2779 }
2780 unset( $spec );
2781 // Sort according to the 'sort' field, and if they are equal, according to 'sort2'
2782 usort( $specs, static function ( $a, $b ) {
2783 return $a['sort'] <=> $b['sort']
2784 ?: $a['sort2'] <=> $b['sort2'];
2785 } );
2786
2787 $ret = [];
2788 foreach ( $specs as $spec ) {
2789 /** @var AbstractAuthenticationProvider $provider */
2790 $provider = $this->objectFactory->createObject( $spec, [ 'assertClass' => $class ] );
2791 $provider->init( $this->logger, $this, $this->getHookContainer(), $this->config, $this->userNameUtils );
2792 $id = $provider->getUniqueId();
2793 if ( isset( $this->allAuthenticationProviders[$id] ) ) {
2794 throw new \RuntimeException(
2795 "Duplicate specifications for id $id (classes " .
2796 get_class( $provider ) . ' and ' .
2797 get_class( $this->allAuthenticationProviders[$id] ) . ')'
2798 );
2799 }
2800 $this->allAuthenticationProviders[$id] = $provider;
2801 $ret[$id] = $provider;
2802 }
2803 return $ret;
2804 }
2805
2806 /**
2807 * Get the list of PreAuthenticationProviders
2808 * @return PreAuthenticationProvider[]
2809 */
2810 protected function getPreAuthenticationProviders() {
2811 if ( $this->preAuthenticationProviders === null ) {
2812 $this->initializeAuthenticationProviders();
2813 }
2814 return $this->preAuthenticationProviders;
2815 }
2816
2817 /**
2818 * Get the list of PrimaryAuthenticationProviders
2819 * @return PrimaryAuthenticationProvider[]
2820 */
2821 protected function getPrimaryAuthenticationProviders() {
2822 if ( $this->primaryAuthenticationProviders === null ) {
2823 $this->initializeAuthenticationProviders();
2824 }
2825 return $this->primaryAuthenticationProviders;
2826 }
2827
2828 /**
2829 * Get the list of SecondaryAuthenticationProviders
2830 * @return SecondaryAuthenticationProvider[]
2831 */
2832 protected function getSecondaryAuthenticationProviders() {
2833 if ( $this->secondaryAuthenticationProviders === null ) {
2834 $this->initializeAuthenticationProviders();
2835 }
2836 return $this->secondaryAuthenticationProviders;
2837 }
2838
2839 private function getProviderIds(): array {
2840 return [
2841 'preauth' => array_keys( $this->getPreAuthenticationProviders() ),
2842 'primaryauth' => array_keys( $this->getPrimaryAuthenticationProviders() ),
2843 'secondaryauth' => array_keys( $this->getSecondaryAuthenticationProviders() ),
2844 ];
2845 }
2846
2847 private function initializeAuthenticationProviders() {
2848 $conf = $this->config->get( MainConfigNames::AuthManagerConfig )
2849 ?: $this->config->get( MainConfigNames::AuthManagerAutoConfig );
2850
2851 $providers = array_map( fn ( $stepConf ) => array_fill_keys( array_keys( $stepConf ), true ), $conf );
2852 $this->getHookRunner()->onAuthManagerFilterProviders( $providers );
2853 foreach ( $conf as $step => $stepConf ) {
2854 $conf[$step] = array_intersect_key( $stepConf, array_filter( $providers[$step] ) );
2855 }
2856
2857 $this->preAuthenticationProviders = $this->providerArrayFromSpecs(
2858 PreAuthenticationProvider::class, $conf['preauth']
2859 );
2860 $this->primaryAuthenticationProviders = $this->providerArrayFromSpecs(
2861 PrimaryAuthenticationProvider::class, $conf['primaryauth']
2862 );
2863 $this->secondaryAuthenticationProviders = $this->providerArrayFromSpecs(
2864 SecondaryAuthenticationProvider::class, $conf['secondaryauth']
2865 );
2866 }
2867
2868 /**
2869 * Log the user in
2870 * @param User $user
2871 * @param bool|null $remember The "remember me" flag.
2872 * @param bool $isReauthentication Whether creating this session should count as a recent
2873 * authentication for $wgReauthenticateTime checks.
2874 */
2875 private function setSessionDataForUser( $user, $remember = null, $isReauthentication = true ) {
2876 $session = $this->request->getSession();
2877 $delay = $session->delaySave();
2878
2879 $session->resetId();
2880 $session->resetAllTokens();
2881 if ( $session->canSetUser() ) {
2882 $session->setUser( $user );
2883 }
2884 if ( $remember !== null ) {
2885 $session->setRememberUser( $remember );
2886 }
2887 if ( $isReauthentication ) {
2888 $session->set( 'AuthManager:lastAuthId', $user->getId() );
2889 $session->set( 'AuthManager:lastAuthTimestamp', time() );
2890 }
2891 $session->persist();
2892
2893 \Wikimedia\ScopedCallback::consume( $delay );
2894
2895 $this->getHookRunner()->onUserLoggedIn( $user );
2896 }
2897
2898 /**
2899 * @param User $user
2900 * @param bool $useContextLang Use 'uselang' to set the user's language
2901 */
2902 private function setDefaultUserOptions( User $user, $useContextLang ) {
2903 $user->setToken();
2904
2905 $lang = $useContextLang ? RequestContext::getMain()->getLanguage() : $this->contentLanguage;
2906 $this->userOptionsManager->setOption(
2907 $user,
2908 'language',
2909 $this->languageConverterFactory->getLanguageConverter( $lang )->getPreferredVariant()
2910 );
2911
2912 $contLangConverter = $this->languageConverterFactory->getLanguageConverter( $this->contentLanguage );
2913 if ( $contLangConverter->hasVariants() ) {
2914 $this->userOptionsManager->setOption(
2915 $user,
2916 'variant',
2917 $contLangConverter->getPreferredVariant()
2918 );
2919 }
2920 }
2921
2922 /**
2923 * @see AuthManagerVerifyAuthenticationHook::onAuthManagerVerifyAuthentication()
2924 */
2925 private function runVerifyHook(
2926 string $action,
2927 ?UserIdentity $user,
2928 AuthenticationResponse &$response,
2929 string $primaryId
2930 ): bool {
2931 $oldResponse = $response;
2932 $info = [
2933 'action' => $action,
2934 'primaryId' => $primaryId,
2935 ];
2936 $proceed = $this->getHookRunner()->onAuthManagerVerifyAuthentication( $user, $response, $this, $info );
2937 if ( !( $response instanceof AuthenticationResponse ) ) {
2938 throw new LogicException( '$response must be an AuthenticationResponse' );
2939 } elseif ( $proceed && $response !== $oldResponse ) {
2940 throw new LogicException(
2941 'AuthManagerVerifyAuthenticationHook must not modify the response unless it returns false' );
2942 } elseif ( !$proceed && $response->status !== AuthenticationResponse::FAIL ) {
2943 throw new LogicException(
2944 'AuthManagerVerifyAuthenticationHook must set the response to FAIL if it returns false' );
2945 }
2946 if ( !$proceed ) {
2947 $this->logger->info(
2948 $action . ' action for {user} from {clientIp} prevented by '
2949 . 'AuthManagerVerifyAuthentication hook: {reason}',
2950 [
2951 'user' => $user ? $user->getName() : '<null>',
2952 'reason' => $response->message->getKey(),
2953 'primaryId' => $primaryId,
2954 ] + $this->request->getSecurityLogContext( $user )
2955 );
2956 }
2957 return $proceed;
2958 }
2959
2960 /**
2961 * @param int $which Bitmask of values of the self::CALL_* constants
2962 * @param string $method
2963 * @param array $args
2964 */
2965 private function callMethodOnProviders( $which, $method, array $args ) {
2966 $providers = [];
2967 if ( $which & self::CALL_PRE ) {
2968 $providers += $this->getPreAuthenticationProviders();
2969 }
2970 if ( $which & self::CALL_PRIMARY ) {
2971 $providers += $this->getPrimaryAuthenticationProviders();
2972 }
2973 if ( $which & self::CALL_SECONDARY ) {
2974 $providers += $this->getSecondaryAuthenticationProviders();
2975 }
2976 foreach ( $providers as $provider ) {
2977 $provider->$method( ...$args );
2978 }
2979 }
2980
2981 /**
2982 * @return HookContainer
2983 */
2984 private function getHookContainer() {
2985 return $this->hookContainer;
2986 }
2987
2988 /**
2989 * @return HookRunner
2990 */
2991 private function getHookRunner() {
2992 return $this->hookRunner;
2993 }
2994
2995 // endregion -- end of Internal methods
2996
2997 }
2998
2999 /*
3000 * This file uses VisualStudio style region/endregion fold markers which are
3001 * recognised by PHPStorm. If modelines are enabled, the following editor
3002 * configuration will also enable folding in vim, if it is in the last 5 lines
3003 * of the file. We also use "@name" which creates sections in Doxygen.
3004 *
3005 * vim: foldmarker=//\ region,//\ endregion foldmethod=marker
3006 */