SessionManager: Ignore Session object destruction during global shutdown
[mediawiki.git] / includes / session / SessionManager.php
bloba364045aaeba76425bc5221f013a1210993e83b4
1 <?php
2 /**
3 * MediaWiki\Session entry point
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Session
24 namespace MediaWiki\Session;
26 use MWException;
27 use Psr\Log\LoggerInterface;
28 use BagOStuff;
29 use CachedBagOStuff;
30 use Config;
31 use FauxRequest;
32 use User;
33 use WebRequest;
35 /**
36 * This serves as the entry point to the MediaWiki session handling system.
38 * @ingroup Session
39 * @since 1.27
41 final class SessionManager implements SessionManagerInterface {
42 /** @var SessionManager|null */
43 private static $instance = null;
45 /** @var Session|null */
46 private static $globalSession = null;
48 /** @var WebRequest|null */
49 private static $globalSessionRequest = null;
51 /** @var LoggerInterface */
52 private $logger;
54 /** @var Config */
55 private $config;
57 /** @var CachedBagOStuff|null */
58 private $store;
60 /** @var SessionProvider[] */
61 private $sessionProviders = null;
63 /** @var string[] */
64 private $varyCookies = null;
66 /** @var array */
67 private $varyHeaders = null;
69 /** @var SessionBackend[] */
70 private $allSessionBackends = [];
72 /** @var SessionId[] */
73 private $allSessionIds = [];
75 /** @var string[] */
76 private $preventUsers = [];
78 /**
79 * Get the global SessionManager
80 * @return SessionManagerInterface
81 * (really a SessionManager, but this is to make IDEs less confused)
83 public static function singleton() {
84 if ( self::$instance === null ) {
85 self::$instance = new self();
87 return self::$instance;
90 /**
91 * Get the "global" session
93 * If PHP's session_id() has been set, returns that session. Otherwise
94 * returns the session for RequestContext::getMain()->getRequest().
96 * @return Session
98 public static function getGlobalSession() {
99 if ( !PHPSessionHandler::isEnabled() ) {
100 $id = '';
101 } else {
102 $id = session_id();
105 $request = \RequestContext::getMain()->getRequest();
106 if (
107 !self::$globalSession // No global session is set up yet
108 || self::$globalSessionRequest !== $request // The global WebRequest changed
109 || $id !== '' && self::$globalSession->getId() !== $id // Someone messed with session_id()
111 self::$globalSessionRequest = $request;
112 if ( $id === '' ) {
113 // session_id() wasn't used, so fetch the Session from the WebRequest.
114 // We use $request->getSession() instead of $singleton->getSessionForRequest()
115 // because doing the latter would require a public
116 // "$request->getSessionId()" method that would confuse end
117 // users by returning SessionId|null where they'd expect it to
118 // be short for $request->getSession()->getId(), and would
119 // wind up being a duplicate of the code in
120 // $request->getSession() anyway.
121 self::$globalSession = $request->getSession();
122 } else {
123 // Someone used session_id(), so we need to follow suit.
124 // Note this overwrites whatever session might already be
125 // associated with $request with the one for $id.
126 self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
127 ?: $request->getSession();
130 return self::$globalSession;
134 * @param array $options
135 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
136 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
137 * - store: BagOStuff to store session data in.
139 public function __construct( $options = [] ) {
140 if ( isset( $options['config'] ) ) {
141 $this->config = $options['config'];
142 if ( !$this->config instanceof Config ) {
143 throw new \InvalidArgumentException(
144 '$options[\'config\'] must be an instance of Config'
147 } else {
148 $this->config = \ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
151 if ( isset( $options['logger'] ) ) {
152 if ( !$options['logger'] instanceof LoggerInterface ) {
153 throw new \InvalidArgumentException(
154 '$options[\'logger\'] must be an instance of LoggerInterface'
157 $this->setLogger( $options['logger'] );
158 } else {
159 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
162 if ( isset( $options['store'] ) ) {
163 if ( !$options['store'] instanceof BagOStuff ) {
164 throw new \InvalidArgumentException(
165 '$options[\'store\'] must be an instance of BagOStuff'
168 $store = $options['store'];
169 } else {
170 $store = \ObjectCache::getInstance( $this->config->get( 'SessionCacheType' ) );
172 $this->store = $store instanceof CachedBagOStuff ? $store : new CachedBagOStuff( $store );
174 register_shutdown_function( [ $this, 'shutdown' ] );
177 public function setLogger( LoggerInterface $logger ) {
178 $this->logger = $logger;
181 public function getSessionForRequest( WebRequest $request ) {
182 $info = $this->getSessionInfoForRequest( $request );
184 if ( !$info ) {
185 $session = $this->getEmptySession( $request );
186 } else {
187 $session = $this->getSessionFromInfo( $info, $request );
189 return $session;
192 public function getSessionById( $id, $create = false, WebRequest $request = null ) {
193 if ( !self::validateSessionId( $id ) ) {
194 throw new \InvalidArgumentException( 'Invalid session ID' );
196 if ( !$request ) {
197 $request = new FauxRequest;
200 $session = null;
201 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [ 'id' => $id, 'idIsSafe' => true ] );
203 // If we already have the backend loaded, use it directly
204 if ( isset( $this->allSessionBackends[$id] ) ) {
205 return $this->getSessionFromInfo( $info, $request );
208 // Test if the session is in storage, and if so try to load it.
209 $key = wfMemcKey( 'MWSession', $id );
210 if ( is_array( $this->store->get( $key ) ) ) {
211 $create = false; // If loading fails, don't bother creating because it probably will fail too.
212 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
213 $session = $this->getSessionFromInfo( $info, $request );
217 if ( $create && $session === null ) {
218 $ex = null;
219 try {
220 $session = $this->getEmptySessionInternal( $request, $id );
221 } catch ( \Exception $ex ) {
222 $this->logger->error( 'Failed to create empty session: {exception}',
224 'method' => __METHOD__,
225 'exception' => $ex,
226 ] );
227 $session = null;
231 return $session;
234 public function getEmptySession( WebRequest $request = null ) {
235 return $this->getEmptySessionInternal( $request );
239 * @see SessionManagerInterface::getEmptySession
240 * @param WebRequest|null $request
241 * @param string|null $id ID to force on the new session
242 * @return Session
244 private function getEmptySessionInternal( WebRequest $request = null, $id = null ) {
245 if ( $id !== null ) {
246 if ( !self::validateSessionId( $id ) ) {
247 throw new \InvalidArgumentException( 'Invalid session ID' );
250 $key = wfMemcKey( 'MWSession', $id );
251 if ( is_array( $this->store->get( $key ) ) ) {
252 throw new \InvalidArgumentException( 'Session ID already exists' );
255 if ( !$request ) {
256 $request = new FauxRequest;
259 $infos = [];
260 foreach ( $this->getProviders() as $provider ) {
261 $info = $provider->newSessionInfo( $id );
262 if ( !$info ) {
263 continue;
265 if ( $info->getProvider() !== $provider ) {
266 throw new \UnexpectedValueException(
267 "$provider returned an empty session info for a different provider: $info"
270 if ( $id !== null && $info->getId() !== $id ) {
271 throw new \UnexpectedValueException(
272 "$provider returned empty session info with a wrong id: " .
273 $info->getId() . ' != ' . $id
276 if ( !$info->isIdSafe() ) {
277 throw new \UnexpectedValueException(
278 "$provider returned empty session info with id flagged unsafe"
281 $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
282 if ( $compare > 0 ) {
283 continue;
285 if ( $compare === 0 ) {
286 $infos[] = $info;
287 } else {
288 $infos = [ $info ];
292 // Make sure there's exactly one
293 if ( count( $infos ) > 1 ) {
294 throw new \UnexpectedValueException(
295 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
297 } elseif ( count( $infos ) < 1 ) {
298 throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
301 return $this->getSessionFromInfo( $infos[0], $request );
304 public function getVaryHeaders() {
305 // @codeCoverageIgnoreStart
306 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
307 return [];
309 // @codeCoverageIgnoreEnd
310 if ( $this->varyHeaders === null ) {
311 $headers = [];
312 foreach ( $this->getProviders() as $provider ) {
313 foreach ( $provider->getVaryHeaders() as $header => $options ) {
314 if ( !isset( $headers[$header] ) ) {
315 $headers[$header] = [];
317 if ( is_array( $options ) ) {
318 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
322 $this->varyHeaders = $headers;
324 return $this->varyHeaders;
327 public function getVaryCookies() {
328 // @codeCoverageIgnoreStart
329 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
330 return [];
332 // @codeCoverageIgnoreEnd
333 if ( $this->varyCookies === null ) {
334 $cookies = [];
335 foreach ( $this->getProviders() as $provider ) {
336 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
338 $this->varyCookies = array_values( array_unique( $cookies ) );
340 return $this->varyCookies;
344 * Validate a session ID
345 * @param string $id
346 * @return bool
348 public static function validateSessionId( $id ) {
349 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
353 * @name Internal methods
354 * @{
358 * Auto-create the given user, if necessary
359 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
360 * @note This more properly belongs in AuthManager, but we need it now.
361 * When AuthManager comes, this will be deprecated and will pass-through
362 * to the corresponding AuthManager method.
363 * @param User $user User to auto-create
364 * @return bool Success
366 public static function autoCreateUser( User $user ) {
367 global $wgAuth;
369 $logger = self::singleton()->logger;
371 // Much of this code is based on that in CentralAuth
373 // Try the local user from the slave DB
374 $localId = User::idFromName( $user->getName() );
375 $flags = 0;
377 // Fetch the user ID from the master, so that we don't try to create the user
378 // when they already exist, due to replication lag
379 // @codeCoverageIgnoreStart
380 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
381 $localId = User::idFromName( $user->getName(), User::READ_LATEST );
382 $flags = User::READ_LATEST;
384 // @codeCoverageIgnoreEnd
386 if ( $localId ) {
387 // User exists after all.
388 $user->setId( $localId );
389 $user->loadFromId( $flags );
390 return false;
393 // Denied by AuthPlugin? But ignore AuthPlugin itself.
394 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
395 $logger->debug( __METHOD__ . ': denied by AuthPlugin' );
396 $user->setId( 0 );
397 $user->loadFromId();
398 return false;
401 // Wiki is read-only?
402 if ( wfReadOnly() ) {
403 $logger->debug( __METHOD__ . ': denied by wfReadOnly()' );
404 $user->setId( 0 );
405 $user->loadFromId();
406 return false;
409 $userName = $user->getName();
411 // Check the session, if we tried to create this user already there's
412 // no point in retrying.
413 $session = self::getGlobalSession();
414 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
415 if ( $reason ) {
416 $logger->debug( __METHOD__ . ": blacklisted in session ($reason)" );
417 $user->setId( 0 );
418 $user->loadFromId();
419 return false;
422 // Is the IP user able to create accounts?
423 $anon = new User;
424 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
425 || $anon->isBlockedFromCreateAccount()
427 // Blacklist the user to avoid repeated DB queries subsequently
428 $logger->debug( __METHOD__ . ': user is blocked from this wiki, blacklisting' );
429 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
430 $session->persist();
431 $user->setId( 0 );
432 $user->loadFromId();
433 return false;
436 // Check for validity of username
437 if ( !User::isCreatableName( $userName ) ) {
438 $logger->debug( __METHOD__ . ': Invalid username, blacklisting' );
439 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
440 $session->persist();
441 $user->setId( 0 );
442 $user->loadFromId();
443 return false;
446 // Give other extensions a chance to stop auto creation.
447 $user->loadDefaults( $userName );
448 $abortMessage = '';
449 if ( !\Hooks::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
450 // In this case we have no way to return the message to the user,
451 // but we can log it.
452 $logger->debug( __METHOD__ . ": denied by hook: $abortMessage" );
453 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
454 $session->persist();
455 $user->setId( 0 );
456 $user->loadFromId();
457 return false;
460 // Make sure the name has not been changed
461 if ( $user->getName() !== $userName ) {
462 $user->setId( 0 );
463 $user->loadFromId();
464 throw new \UnexpectedValueException(
465 'AbortAutoAccount hook tried to change the user name'
469 // Ignore warnings about master connections/writes...hard to avoid here
470 \Profiler::instance()->getTransactionProfiler()->resetExpectations();
472 $cache = \ObjectCache::getLocalClusterInstance();
473 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
474 if ( $cache->get( $backoffKey ) ) {
475 $logger->debug( __METHOD__ . ': denied by prior creation attempt failures' );
476 $user->setId( 0 );
477 $user->loadFromId();
478 return false;
481 // Checks passed, create the user...
482 $from = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : 'CLI';
483 $logger->info( __METHOD__ . ': creating new user ({username}) - from: {url}',
485 'username' => $userName,
486 'url' => $from,
487 ] );
489 try {
490 // Insert the user into the local DB master
491 $status = $user->addToDatabase();
492 if ( !$status->isOK() ) {
493 // @codeCoverageIgnoreStart
494 // double-check for a race condition (T70012)
495 $id = User::idFromName( $user->getName(), User::READ_LATEST );
496 if ( $id ) {
497 $logger->info( __METHOD__ . ': tried to autocreate existing user',
499 'username' => $userName,
500 ] );
501 } else {
502 $logger->error(
503 __METHOD__ . ': failed with message ' . $status->getWikiText( false, false, 'en' ),
505 'username' => $userName,
509 $user->setId( $id );
510 $user->loadFromId( User::READ_LATEST );
511 return false;
512 // @codeCoverageIgnoreEnd
514 } catch ( \Exception $ex ) {
515 // @codeCoverageIgnoreStart
516 $logger->error( __METHOD__ . ': failed with exception {exception}', [
517 'exception' => $ex,
518 'username' => $userName,
519 ] );
520 // Do not keep throwing errors for a while
521 $cache->set( $backoffKey, 1, 600 );
522 // Bubble up error; which should normally trigger DB rollbacks
523 throw $ex;
524 // @codeCoverageIgnoreEnd
527 # Notify AuthPlugin
528 // @codeCoverageIgnoreStart
529 $tmpUser = $user;
530 $wgAuth->initUser( $tmpUser, true );
531 if ( $tmpUser !== $user ) {
532 $logger->warning( __METHOD__ . ': ' .
533 get_class( $wgAuth ) . '::initUser() replaced the user object' );
535 // @codeCoverageIgnoreEnd
537 # Notify hooks (e.g. Newuserlog)
538 \Hooks::run( 'AuthPluginAutoCreate', [ $user ] );
539 \Hooks::run( 'LocalUserCreated', [ $user, true ] );
541 $user->saveSettings();
543 # Update user count
544 \DeferredUpdates::addUpdate( new \SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
546 # Watch user's userpage and talk page
547 $user->addWatch( $user->getUserPage(), User::IGNORE_USER_RIGHTS );
549 return true;
553 * Prevent future sessions for the user
555 * The intention is that the named account will never again be usable for
556 * normal login (i.e. there is no way to undo the prevention of access).
558 * @private For use from \User::newSystemUser only
559 * @param string $username
561 public function preventSessionsForUser( $username ) {
562 $this->preventUsers[$username] = true;
564 // Instruct the session providers to kill any other sessions too.
565 foreach ( $this->getProviders() as $provider ) {
566 $provider->preventSessionsForUser( $username );
571 * Test if a user is prevented
572 * @private For use from SessionBackend only
573 * @param string $username
574 * @return bool
576 public function isUserSessionPrevented( $username ) {
577 return !empty( $this->preventUsers[$username] );
581 * Get the available SessionProviders
582 * @return SessionProvider[]
584 protected function getProviders() {
585 if ( $this->sessionProviders === null ) {
586 $this->sessionProviders = [];
587 foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
588 $provider = \ObjectFactory::getObjectFromSpec( $spec );
589 $provider->setLogger( $this->logger );
590 $provider->setConfig( $this->config );
591 $provider->setManager( $this );
592 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
593 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
595 $this->sessionProviders[(string)$provider] = $provider;
598 return $this->sessionProviders;
602 * Get a session provider by name
604 * Generally, this will only be used by internal implementation of some
605 * special session-providing mechanism. General purpose code, if it needs
606 * to access a SessionProvider at all, will use Session::getProvider().
608 * @param string $name
609 * @return SessionProvider|null
611 public function getProvider( $name ) {
612 $providers = $this->getProviders();
613 return isset( $providers[$name] ) ? $providers[$name] : null;
617 * Save all active sessions on shutdown
618 * @private For internal use with register_shutdown_function()
620 public function shutdown() {
621 if ( $this->allSessionBackends ) {
622 $this->logger->debug( 'Saving all sessions on shutdown' );
623 if ( session_id() !== '' ) {
624 // @codeCoverageIgnoreStart
625 session_write_close();
627 // @codeCoverageIgnoreEnd
628 foreach ( $this->allSessionBackends as $backend ) {
629 $backend->shutdown();
635 * Fetch the SessionInfo(s) for a request
636 * @param WebRequest $request
637 * @return SessionInfo|null
639 private function getSessionInfoForRequest( WebRequest $request ) {
640 // Call all providers to fetch "the" session
641 $infos = [];
642 foreach ( $this->getProviders() as $provider ) {
643 $info = $provider->provideSessionInfo( $request );
644 if ( !$info ) {
645 continue;
647 if ( $info->getProvider() !== $provider ) {
648 throw new \UnexpectedValueException(
649 "$provider returned session info for a different provider: $info"
652 $infos[] = $info;
655 // Sort the SessionInfos. Then find the first one that can be
656 // successfully loaded, and then all the ones after it with the same
657 // priority.
658 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
659 $retInfos = [];
660 while ( $infos ) {
661 $info = array_pop( $infos );
662 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
663 $retInfos[] = $info;
664 while ( $infos ) {
665 $info = array_pop( $infos );
666 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
667 // We hit a lower priority, stop checking.
668 break;
670 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
671 // This is going to error out below, but we want to
672 // provide a complete list.
673 $retInfos[] = $info;
674 } else {
675 // Session load failed, so unpersist it from this request
676 $info->getProvider()->unpersistSession( $request );
679 } else {
680 // Session load failed, so unpersist it from this request
681 $info->getProvider()->unpersistSession( $request );
685 if ( count( $retInfos ) > 1 ) {
686 $ex = new \OverflowException(
687 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
689 $ex->sessionInfos = $retInfos;
690 throw $ex;
693 return $retInfos ? $retInfos[0] : null;
697 * Load and verify the session info against the store
699 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
700 * @param WebRequest $request
701 * @return bool Whether the session info matches the stored data (if any)
703 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
704 $key = wfMemcKey( 'MWSession', $info->getId() );
705 $blob = $this->store->get( $key );
707 $newParams = [];
709 if ( $blob !== false ) {
710 // Sanity check: blob must be an array, if it's saved at all
711 if ( !is_array( $blob ) ) {
712 $this->logger->warning( 'Session "{session}": Bad data', [
713 'session' => $info,
714 ] );
715 $this->store->delete( $key );
716 return false;
719 // Sanity check: blob has data and metadata arrays
720 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
721 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
723 $this->logger->warning( 'Session "{session}": Bad data structure', [
724 'session' => $info,
725 ] );
726 $this->store->delete( $key );
727 return false;
730 $data = $blob['data'];
731 $metadata = $blob['metadata'];
733 // Sanity check: metadata must be an array and must contain certain
734 // keys, if it's saved at all
735 if ( !array_key_exists( 'userId', $metadata ) ||
736 !array_key_exists( 'userName', $metadata ) ||
737 !array_key_exists( 'userToken', $metadata ) ||
738 !array_key_exists( 'provider', $metadata )
740 $this->logger->warning( 'Session "{session}": Bad metadata', [
741 'session' => $info,
742 ] );
743 $this->store->delete( $key );
744 return false;
747 // First, load the provider from metadata, or validate it against the metadata.
748 $provider = $info->getProvider();
749 if ( $provider === null ) {
750 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
751 if ( !$provider ) {
752 $this->logger->warning(
753 'Session "{session}": Unknown provider ' . $metadata['provider'],
755 'session' => $info,
758 $this->store->delete( $key );
759 return false;
761 } elseif ( $metadata['provider'] !== (string)$provider ) {
762 $this->logger->warning( 'Session "{session}": Wrong provider ' .
763 $metadata['provider'] . ' !== ' . $provider,
765 'session' => $info,
766 ] );
767 return false;
770 // Load provider metadata from metadata, or validate it against the metadata
771 $providerMetadata = $info->getProviderMetadata();
772 if ( isset( $metadata['providerMetadata'] ) ) {
773 if ( $providerMetadata === null ) {
774 $newParams['metadata'] = $metadata['providerMetadata'];
775 } else {
776 try {
777 $newProviderMetadata = $provider->mergeMetadata(
778 $metadata['providerMetadata'], $providerMetadata
780 if ( $newProviderMetadata !== $providerMetadata ) {
781 $newParams['metadata'] = $newProviderMetadata;
783 } catch ( MetadataMergeException $ex ) {
784 $this->logger->warning(
785 'Session "{session}": Metadata merge failed: {exception}',
787 'session' => $info,
788 'exception' => $ex,
789 ] + $ex->getContext()
791 return false;
796 // Next, load the user from metadata, or validate it against the metadata.
797 $userInfo = $info->getUserInfo();
798 if ( !$userInfo ) {
799 // For loading, id is preferred to name.
800 try {
801 if ( $metadata['userId'] ) {
802 $userInfo = UserInfo::newFromId( $metadata['userId'] );
803 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
804 $userInfo = UserInfo::newFromName( $metadata['userName'] );
805 } else {
806 $userInfo = UserInfo::newAnonymous();
808 } catch ( \InvalidArgumentException $ex ) {
809 $this->logger->error( 'Session "{session}": {exception}', [
810 'session' => $info,
811 'exception' => $ex,
812 ] );
813 return false;
815 $newParams['userInfo'] = $userInfo;
816 } else {
817 // User validation passes if user ID matches, or if there
818 // is no saved ID and the names match.
819 if ( $metadata['userId'] ) {
820 if ( $metadata['userId'] !== $userInfo->getId() ) {
821 $this->logger->warning(
822 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
824 'session' => $info,
825 'uid_a' => $metadata['userId'],
826 'uid_b' => $userInfo->getId(),
827 ] );
828 return false;
831 // If the user was renamed, probably best to fail here.
832 if ( $metadata['userName'] !== null &&
833 $userInfo->getName() !== $metadata['userName']
835 $this->logger->warning(
836 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
838 'session' => $info,
839 'uname_a' => $metadata['userName'],
840 'uname_b' => $userInfo->getName(),
841 ] );
842 return false;
845 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
846 if ( $metadata['userName'] !== $userInfo->getName() ) {
847 $this->logger->warning(
848 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
850 'session' => $info,
851 'uname_a' => $metadata['userName'],
852 'uname_b' => $userInfo->getName(),
853 ] );
854 return false;
856 } elseif ( !$userInfo->isAnon() ) {
857 // Metadata specifies an anonymous user, but the passed-in
858 // user isn't anonymous.
859 $this->logger->warning(
860 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
862 'session' => $info,
863 ] );
864 return false;
868 // And if we have a token in the metadata, it must match the loaded/provided user.
869 if ( $metadata['userToken'] !== null &&
870 $userInfo->getToken() !== $metadata['userToken']
872 $this->logger->warning( 'Session "{session}": User token mismatch', [
873 'session' => $info,
874 ] );
875 return false;
877 if ( !$userInfo->isVerified() ) {
878 $newParams['userInfo'] = $userInfo->verified();
881 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
882 $newParams['remembered'] = true;
884 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
885 $newParams['forceHTTPS'] = true;
887 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
888 $newParams['persisted'] = true;
891 if ( !$info->isIdSafe() ) {
892 $newParams['idIsSafe'] = true;
894 } else {
895 // No metadata, so we can't load the provider if one wasn't given.
896 if ( $info->getProvider() === null ) {
897 $this->logger->warning(
898 'Session "{session}": Null provider and no metadata',
900 'session' => $info,
901 ] );
902 return false;
905 // If no user was provided and no metadata, it must be anon.
906 if ( !$info->getUserInfo() ) {
907 if ( $info->getProvider()->canChangeUser() ) {
908 $newParams['userInfo'] = UserInfo::newAnonymous();
909 } else {
910 $this->logger->info(
911 'Session "{session}": No user provided and provider cannot set user',
913 'session' => $info,
914 ] );
915 return false;
917 } elseif ( !$info->getUserInfo()->isVerified() ) {
918 $this->logger->warning(
919 'Session "{session}": Unverified user provided and no metadata to auth it',
921 'session' => $info,
922 ] );
923 return false;
926 $data = false;
927 $metadata = false;
929 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
930 // The ID doesn't come from the user, so it should be safe
931 // (and if not, nothing we can do about it anyway)
932 $newParams['idIsSafe'] = true;
936 // Construct the replacement SessionInfo, if necessary
937 if ( $newParams ) {
938 $newParams['copyFrom'] = $info;
939 $info = new SessionInfo( $info->getPriority(), $newParams );
942 // Allow the provider to check the loaded SessionInfo
943 $providerMetadata = $info->getProviderMetadata();
944 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
945 return false;
947 if ( $providerMetadata !== $info->getProviderMetadata() ) {
948 $info = new SessionInfo( $info->getPriority(), [
949 'metadata' => $providerMetadata,
950 'copyFrom' => $info,
951 ] );
954 // Give hooks a chance to abort. Combined with the SessionMetadata
955 // hook, this can allow for tying a session to an IP address or the
956 // like.
957 $reason = 'Hook aborted';
958 if ( !\Hooks::run(
959 'SessionCheckInfo',
960 [ &$reason, $info, $request, $metadata, $data ]
961 ) ) {
962 $this->logger->warning( 'Session "{session}": ' . $reason, [
963 'session' => $info,
964 ] );
965 return false;
968 return true;
972 * Create a session corresponding to the passed SessionInfo
973 * @private For use by a SessionProvider that needs to specially create its
974 * own session.
975 * @param SessionInfo $info
976 * @param WebRequest $request
977 * @return Session
979 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
980 // @codeCoverageIgnoreStart
981 if ( defined( 'MW_NO_SESSION' ) ) {
982 if ( MW_NO_SESSION === 'warn' ) {
983 // Undocumented safety case for converting existing entry points
984 $this->logger->error( 'Sessions are supposed to be disabled for this entry point', [
985 'exception' => new \BadMethodCallException( 'Sessions are disabled for this entry point' ),
986 ] );
987 } else {
988 throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
991 // @codeCoverageIgnoreEnd
993 $id = $info->getId();
995 if ( !isset( $this->allSessionBackends[$id] ) ) {
996 if ( !isset( $this->allSessionIds[$id] ) ) {
997 $this->allSessionIds[$id] = new SessionId( $id );
999 $backend = new SessionBackend(
1000 $this->allSessionIds[$id],
1001 $info,
1002 $this->store,
1003 $this->logger,
1004 $this->config->get( 'ObjectCacheSessionExpiry' )
1006 $this->allSessionBackends[$id] = $backend;
1007 $delay = $backend->delaySave();
1008 } else {
1009 $backend = $this->allSessionBackends[$id];
1010 $delay = $backend->delaySave();
1011 if ( $info->wasPersisted() ) {
1012 $backend->persist();
1014 if ( $info->wasRemembered() ) {
1015 $backend->setRememberUser( true );
1019 $request->setSessionId( $backend->getSessionId() );
1020 $session = $backend->getSession( $request );
1022 if ( !$info->isIdSafe() ) {
1023 $session->resetId();
1026 \ScopedCallback::consume( $delay );
1027 return $session;
1031 * Deregister a SessionBackend
1032 * @private For use from \MediaWiki\Session\SessionBackend only
1033 * @param SessionBackend $backend
1035 public function deregisterSessionBackend( SessionBackend $backend ) {
1036 $id = $backend->getId();
1037 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
1038 $this->allSessionBackends[$id] !== $backend ||
1039 $this->allSessionIds[$id] !== $backend->getSessionId()
1041 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1044 unset( $this->allSessionBackends[$id] );
1045 // Explicitly do not unset $this->allSessionIds[$id]
1049 * Change a SessionBackend's ID
1050 * @private For use from \MediaWiki\Session\SessionBackend only
1051 * @param SessionBackend $backend
1053 public function changeBackendId( SessionBackend $backend ) {
1054 $sessionId = $backend->getSessionId();
1055 $oldId = (string)$sessionId;
1056 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
1057 $this->allSessionBackends[$oldId] !== $backend ||
1058 $this->allSessionIds[$oldId] !== $sessionId
1060 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1063 $newId = $this->generateSessionId();
1065 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
1066 $sessionId->setId( $newId );
1067 $this->allSessionBackends[$newId] = $backend;
1068 $this->allSessionIds[$newId] = $sessionId;
1072 * Generate a new random session ID
1073 * @return string
1075 public function generateSessionId() {
1076 do {
1077 $id = wfBaseConvert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
1078 $key = wfMemcKey( 'MWSession', $id );
1079 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
1080 return $id;
1084 * Call setters on a PHPSessionHandler
1085 * @private Use PhpSessionHandler::install()
1086 * @param PHPSessionHandler $handler
1088 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
1089 $handler->setManager( $this, $this->store, $this->logger );
1093 * Reset the internal caching for unit testing
1095 public static function resetCache() {
1096 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1097 // @codeCoverageIgnoreStart
1098 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
1099 // @codeCoverageIgnoreEnd
1102 self::$globalSession = null;
1103 self::$globalSessionRequest = null;
1106 /**@}*/