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