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
24 namespace MediaWiki\Session
;
26 use Psr\Log\LoggerInterface
;
36 * This serves as the entry point to the MediaWiki session handling system.
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 */
57 /** @var CachedBagOStuff|null */
60 /** @var SessionProvider[] */
61 private $sessionProviders = null;
64 private $varyCookies = null;
67 private $varyHeaders = null;
69 /** @var SessionBackend[] */
70 private $allSessionBackends = [];
72 /** @var SessionId[] */
73 private $allSessionIds = [];
76 private $preventUsers = [];
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;
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().
98 public static function getGlobalSession() {
99 if ( !PHPSessionHandler
::isEnabled() ) {
105 $request = \RequestContext
::getMain()->getRequest();
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;
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();
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'
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'] );
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'];
170 $store = \ObjectCache
::getInstance( $this->config
->get( 'SessionCacheType' ) );
171 $store->setLogger( $this->logger
);
173 $this->store
= $store instanceof CachedBagOStuff ?
$store : new CachedBagOStuff( $store );
175 register_shutdown_function( [ $this, 'shutdown' ] );
178 public function setLogger( LoggerInterface
$logger ) {
179 $this->logger
= $logger;
182 public function getSessionForRequest( WebRequest
$request ) {
183 $info = $this->getSessionInfoForRequest( $request );
186 $session = $this->getEmptySession( $request );
188 $session = $this->getSessionFromInfo( $info, $request );
193 public function getSessionById( $id, $create = false, WebRequest
$request = null ) {
194 if ( !self
::validateSessionId( $id ) ) {
195 throw new \
InvalidArgumentException( 'Invalid session ID' );
198 $request = new FauxRequest
;
203 // Test this here to provide a better log message for the common case
205 $key = wfMemcKey( 'MWSession', $id );
206 if ( is_array( $this->store
->get( $key ) ) ) {
207 $info = new SessionInfo( SessionInfo
::MIN_PRIORITY
, [ 'id' => $id, 'idIsSafe' => true ] );
208 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
209 $session = $this->getSessionFromInfo( $info, $request );
213 if ( $create && $session === null ) {
216 $session = $this->getEmptySessionInternal( $request, $id );
217 } catch ( \Exception
$ex ) {
218 $this->logger
->error( 'Failed to create empty session: {exception}',
220 'method' => __METHOD__
,
230 public function getEmptySession( WebRequest
$request = null ) {
231 return $this->getEmptySessionInternal( $request );
235 * @see SessionManagerInterface::getEmptySession
236 * @param WebRequest|null $request
237 * @param string|null $id ID to force on the new session
240 private function getEmptySessionInternal( WebRequest
$request = null, $id = null ) {
241 if ( $id !== null ) {
242 if ( !self
::validateSessionId( $id ) ) {
243 throw new \
InvalidArgumentException( 'Invalid session ID' );
246 $key = wfMemcKey( 'MWSession', $id );
247 if ( is_array( $this->store
->get( $key ) ) ) {
248 throw new \
InvalidArgumentException( 'Session ID already exists' );
252 $request = new FauxRequest
;
256 foreach ( $this->getProviders() as $provider ) {
257 $info = $provider->newSessionInfo( $id );
261 if ( $info->getProvider() !== $provider ) {
262 throw new \
UnexpectedValueException(
263 "$provider returned an empty session info for a different provider: $info"
266 if ( $id !== null && $info->getId() !== $id ) {
267 throw new \
UnexpectedValueException(
268 "$provider returned empty session info with a wrong id: " .
269 $info->getId() . ' != ' . $id
272 if ( !$info->isIdSafe() ) {
273 throw new \
UnexpectedValueException(
274 "$provider returned empty session info with id flagged unsafe"
277 $compare = $infos ? SessionInfo
::compare( $infos[0], $info ) : -1;
278 if ( $compare > 0 ) {
281 if ( $compare === 0 ) {
288 // Make sure there's exactly one
289 if ( count( $infos ) > 1 ) {
290 throw new \
UnexpectedValueException(
291 'Multiple empty sessions tied for top priority: ' . join( ', ', $infos )
293 } elseif ( count( $infos ) < 1 ) {
294 throw new \
UnexpectedValueException( 'No provider could provide an empty session!' );
297 return $this->getSessionFromInfo( $infos[0], $request );
300 public function getVaryHeaders() {
301 if ( $this->varyHeaders
=== null ) {
303 foreach ( $this->getProviders() as $provider ) {
304 foreach ( $provider->getVaryHeaders() as $header => $options ) {
305 if ( !isset( $headers[$header] ) ) {
306 $headers[$header] = [];
308 if ( is_array( $options ) ) {
309 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
313 $this->varyHeaders
= $headers;
315 return $this->varyHeaders
;
318 public function getVaryCookies() {
319 if ( $this->varyCookies
=== null ) {
321 foreach ( $this->getProviders() as $provider ) {
322 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
324 $this->varyCookies
= array_values( array_unique( $cookies ) );
326 return $this->varyCookies
;
330 * Validate a session ID
334 public static function validateSessionId( $id ) {
335 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
339 * @name Internal methods
344 * Auto-create the given user, if necessary
345 * @private Don't call this yourself. Let Setup.php do it for you at the right time.
346 * @note This more properly belongs in AuthManager, but we need it now.
347 * When AuthManager comes, this will be deprecated and will pass-through
348 * to the corresponding AuthManager method.
349 * @param User $user User to auto-create
350 * @return bool Success
352 public static function autoCreateUser( User
$user ) {
355 $logger = self
::singleton()->logger
;
357 // Much of this code is based on that in CentralAuth
359 // Try the local user from the slave DB
360 $localId = User
::idFromName( $user->getName() );
363 // Fetch the user ID from the master, so that we don't try to create the user
364 // when they already exist, due to replication lag
365 // @codeCoverageIgnoreStart
366 if ( !$localId && wfGetLB()->getReaderIndex() != 0 ) {
367 $localId = User
::idFromName( $user->getName(), User
::READ_LATEST
);
368 $flags = User
::READ_LATEST
;
370 // @codeCoverageIgnoreEnd
373 // User exists after all.
374 $user->setId( $localId );
375 $user->loadFromId( $flags );
379 // Denied by AuthPlugin? But ignore AuthPlugin itself.
380 if ( get_class( $wgAuth ) !== 'AuthPlugin' && !$wgAuth->autoCreate() ) {
381 $logger->debug( __METHOD__
. ': denied by AuthPlugin' );
387 // Wiki is read-only?
388 if ( wfReadOnly() ) {
389 $logger->debug( __METHOD__
. ': denied by wfReadOnly()' );
395 $userName = $user->getName();
397 // Check the session, if we tried to create this user already there's
398 // no point in retrying.
399 $session = self
::getGlobalSession();
400 $reason = $session->get( 'MWSession::AutoCreateBlacklist' );
402 $logger->debug( __METHOD__
. ": blacklisted in session ($reason)" );
408 // Is the IP user able to create accounts?
410 if ( !$anon->isAllowedAny( 'createaccount', 'autocreateaccount' )
411 ||
$anon->isBlockedFromCreateAccount()
413 // Blacklist the user to avoid repeated DB queries subsequently
414 $logger->debug( __METHOD__
. ': user is blocked from this wiki, blacklisting' );
415 $session->set( 'MWSession::AutoCreateBlacklist', 'blocked', 600 );
422 // Check for validity of username
423 if ( !User
::isCreatableName( $userName ) ) {
424 $logger->debug( __METHOD__
. ': Invalid username, blacklisting' );
425 $session->set( 'MWSession::AutoCreateBlacklist', 'invalid username', 600 );
432 // Give other extensions a chance to stop auto creation.
433 $user->loadDefaults( $userName );
435 if ( !\Hooks
::run( 'AbortAutoAccount', [ $user, &$abortMessage ] ) ) {
436 // In this case we have no way to return the message to the user,
437 // but we can log it.
438 $logger->debug( __METHOD__
. ": denied by hook: $abortMessage" );
439 $session->set( 'MWSession::AutoCreateBlacklist', "hook aborted: $abortMessage", 600 );
446 // Make sure the name has not been changed
447 if ( $user->getName() !== $userName ) {
450 throw new \
UnexpectedValueException(
451 'AbortAutoAccount hook tried to change the user name'
455 // Ignore warnings about master connections/writes...hard to avoid here
456 \Profiler
::instance()->getTransactionProfiler()->resetExpectations();
458 $cache = \ObjectCache
::getLocalClusterInstance();
459 $backoffKey = wfMemcKey( 'MWSession', 'autocreate-failed', md5( $userName ) );
460 if ( $cache->get( $backoffKey ) ) {
461 $logger->debug( __METHOD__
. ': denied by prior creation attempt failures' );
467 // Checks passed, create the user...
468 $from = isset( $_SERVER['REQUEST_URI'] ) ?
$_SERVER['REQUEST_URI'] : 'CLI';
469 $logger->info( __METHOD__
. ': creating new user ({username}) - from: {url}',
471 'username' => $userName,
476 // Insert the user into the local DB master
477 $status = $user->addToDatabase();
478 if ( !$status->isOK() ) {
479 // @codeCoverageIgnoreStart
480 // double-check for a race condition (T70012)
481 $id = User
::idFromName( $user->getName(), User
::READ_LATEST
);
483 $logger->info( __METHOD__
. ': tried to autocreate existing user',
485 'username' => $userName,
488 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText(),
490 'username' => $userName,
494 $user->loadFromId( User
::READ_LATEST
);
496 // @codeCoverageIgnoreEnd
498 } catch ( \Exception
$ex ) {
499 // @codeCoverageIgnoreStart
500 $logger->error( __METHOD__
. ': failed with exception {exception}', [
502 'username' => $userName,
504 // Do not keep throwing errors for a while
505 $cache->set( $backoffKey, 1, 600 );
506 // Bubble up error; which should normally trigger DB rollbacks
508 // @codeCoverageIgnoreEnd
513 $wgAuth->initUser( $tmpUser, true );
514 if ( $tmpUser !== $user ) {
515 $logger->warning( __METHOD__
. ': ' .
516 get_class( $wgAuth ) . '::initUser() replaced the user object' );
519 # Notify hooks (e.g. Newuserlog)
520 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ] );
521 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
523 $user->saveSettings();
526 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
528 # Watch user's userpage and talk page
529 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
535 * Prevent future sessions for the user
537 * The intention is that the named account will never again be usable for
538 * normal login (i.e. there is no way to undo the prevention of access).
540 * @private For use from \\User::newSystemUser only
541 * @param string $username
543 public function preventSessionsForUser( $username ) {
544 $this->preventUsers
[$username] = true;
546 // Instruct the session providers to kill any other sessions too.
547 foreach ( $this->getProviders() as $provider ) {
548 $provider->preventSessionsForUser( $username );
553 * Test if a user is prevented
554 * @private For use from SessionBackend only
555 * @param string $username
558 public function isUserSessionPrevented( $username ) {
559 return !empty( $this->preventUsers
[$username] );
563 * Get the available SessionProviders
564 * @return SessionProvider[]
566 protected function getProviders() {
567 if ( $this->sessionProviders
=== null ) {
568 $this->sessionProviders
= [];
569 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
570 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
571 $provider->setLogger( $this->logger
);
572 $provider->setConfig( $this->config
);
573 $provider->setManager( $this );
574 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
575 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
577 $this->sessionProviders
[(string)$provider] = $provider;
580 return $this->sessionProviders
;
584 * Get a session provider by name
586 * Generally, this will only be used by internal implementation of some
587 * special session-providing mechanism. General purpose code, if it needs
588 * to access a SessionProvider at all, will use Session::getProvider().
590 * @param string $name
591 * @return SessionProvider|null
593 public function getProvider( $name ) {
594 $providers = $this->getProviders();
595 return isset( $providers[$name] ) ?
$providers[$name] : null;
599 * Save all active sessions on shutdown
600 * @private For internal use with register_shutdown_function()
602 public function shutdown() {
603 if ( $this->allSessionBackends
) {
604 $this->logger
->debug( 'Saving all sessions on shutdown' );
605 if ( session_id() !== '' ) {
606 // @codeCoverageIgnoreStart
607 session_write_close();
609 // @codeCoverageIgnoreEnd
610 foreach ( $this->allSessionBackends
as $backend ) {
611 $backend->save( true );
617 * Fetch the SessionInfo(s) for a request
618 * @param WebRequest $request
619 * @return SessionInfo|null
621 private function getSessionInfoForRequest( WebRequest
$request ) {
622 // Call all providers to fetch "the" session
624 foreach ( $this->getProviders() as $provider ) {
625 $info = $provider->provideSessionInfo( $request );
629 if ( $info->getProvider() !== $provider ) {
630 throw new \
UnexpectedValueException(
631 "$provider returned session info for a different provider: $info"
637 // Sort the SessionInfos. Then find the first one that can be
638 // successfully loaded, and then all the ones after it with the same
640 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
643 $info = array_pop( $infos );
644 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
647 $info = array_pop( $infos );
648 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
649 // We hit a lower priority, stop checking.
652 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
653 // This is going to error out below, but we want to
654 // provide a complete list.
661 if ( count( $retInfos ) > 1 ) {
662 $ex = new \
OverflowException(
663 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
665 $ex->sessionInfos
= $retInfos;
669 return $retInfos ?
$retInfos[0] : null;
673 * Load and verify the session info against the store
675 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
676 * @param WebRequest $request
677 * @return bool Whether the session info matches the stored data (if any)
679 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
680 $key = wfMemcKey( 'MWSession', $info->getId() );
681 $blob = $this->store
->get( $key );
685 if ( $blob !== false ) {
686 // Sanity check: blob must be an array, if it's saved at all
687 if ( !is_array( $blob ) ) {
688 $this->logger
->warning( 'Session "{session}": Bad data', [
691 $this->store
->delete( $key );
695 // Sanity check: blob has data and metadata arrays
696 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
697 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
699 $this->logger
->warning( 'Session "{session}": Bad data structure', [
702 $this->store
->delete( $key );
706 $data = $blob['data'];
707 $metadata = $blob['metadata'];
709 // Sanity check: metadata must be an array and must contain certain
710 // keys, if it's saved at all
711 if ( !array_key_exists( 'userId', $metadata ) ||
712 !array_key_exists( 'userName', $metadata ) ||
713 !array_key_exists( 'userToken', $metadata ) ||
714 !array_key_exists( 'provider', $metadata )
716 $this->logger
->warning( 'Session "{session}": Bad metadata', [
719 $this->store
->delete( $key );
723 // First, load the provider from metadata, or validate it against the metadata.
724 $provider = $info->getProvider();
725 if ( $provider === null ) {
726 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
728 $this->logger
->warning(
729 'Session "{session}": Unknown provider ' . $metadata['provider'],
734 $this->store
->delete( $key );
737 } elseif ( $metadata['provider'] !== (string)$provider ) {
738 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
739 $metadata['provider'] . ' !== ' . $provider,
746 // Load provider metadata from metadata, or validate it against the metadata
747 $providerMetadata = $info->getProviderMetadata();
748 if ( isset( $metadata['providerMetadata'] ) ) {
749 if ( $providerMetadata === null ) {
750 $newParams['metadata'] = $metadata['providerMetadata'];
753 $newProviderMetadata = $provider->mergeMetadata(
754 $metadata['providerMetadata'], $providerMetadata
756 if ( $newProviderMetadata !== $providerMetadata ) {
757 $newParams['metadata'] = $newProviderMetadata;
759 } catch ( MetadataMergeException
$ex ) {
760 $this->logger
->warning(
761 'Session "{session}": Metadata merge failed: {exception}',
765 ] +
$ex->getContext()
772 // Next, load the user from metadata, or validate it against the metadata.
773 $userInfo = $info->getUserInfo();
775 // For loading, id is preferred to name.
777 if ( $metadata['userId'] ) {
778 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
779 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
780 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
782 $userInfo = UserInfo
::newAnonymous();
784 } catch ( \InvalidArgumentException
$ex ) {
785 $this->logger
->error( 'Session "{session}": {exception}', [
791 $newParams['userInfo'] = $userInfo;
793 // User validation passes if user ID matches, or if there
794 // is no saved ID and the names match.
795 if ( $metadata['userId'] ) {
796 if ( $metadata['userId'] !== $userInfo->getId() ) {
797 $this->logger
->warning(
798 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
801 'uid_a' => $metadata['userId'],
802 'uid_b' => $userInfo->getId(),
807 // If the user was renamed, probably best to fail here.
808 if ( $metadata['userName'] !== null &&
809 $userInfo->getName() !== $metadata['userName']
811 $this->logger
->warning(
812 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
815 'uname_a' => $metadata['userName'],
816 'uname_b' => $userInfo->getName(),
821 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
822 if ( $metadata['userName'] !== $userInfo->getName() ) {
823 $this->logger
->warning(
824 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
827 'uname_a' => $metadata['userName'],
828 'uname_b' => $userInfo->getName(),
832 } elseif ( !$userInfo->isAnon() ) {
833 // Metadata specifies an anonymous user, but the passed-in
834 // user isn't anonymous.
835 $this->logger
->warning(
836 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
844 // And if we have a token in the metadata, it must match the loaded/provided user.
845 if ( $metadata['userToken'] !== null &&
846 $userInfo->getToken() !== $metadata['userToken']
848 $this->logger
->warning( 'Session "{session}": User token mismatch', [
853 if ( !$userInfo->isVerified() ) {
854 $newParams['userInfo'] = $userInfo->verified();
857 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
858 $newParams['remembered'] = true;
860 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
861 $newParams['forceHTTPS'] = true;
863 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
864 $newParams['persisted'] = true;
867 if ( !$info->isIdSafe() ) {
868 $newParams['idIsSafe'] = true;
871 // No metadata, so we can't load the provider if one wasn't given.
872 if ( $info->getProvider() === null ) {
873 $this->logger
->warning(
874 'Session "{session}": Null provider and no metadata',
881 // If no user was provided and no metadata, it must be anon.
882 if ( !$info->getUserInfo() ) {
883 if ( $info->getProvider()->canChangeUser() ) {
884 $newParams['userInfo'] = UserInfo
::newAnonymous();
887 'Session "{session}": No user provided and provider cannot set user',
893 } elseif ( !$info->getUserInfo()->isVerified() ) {
894 $this->logger
->warning(
895 'Session "{session}": Unverified user provided and no metadata to auth it',
905 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
906 // The ID doesn't come from the user, so it should be safe
907 // (and if not, nothing we can do about it anyway)
908 $newParams['idIsSafe'] = true;
912 // Construct the replacement SessionInfo, if necessary
914 $newParams['copyFrom'] = $info;
915 $info = new SessionInfo( $info->getPriority(), $newParams );
918 // Allow the provider to check the loaded SessionInfo
919 $providerMetadata = $info->getProviderMetadata();
920 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
923 if ( $providerMetadata !== $info->getProviderMetadata() ) {
924 $info = new SessionInfo( $info->getPriority(), [
925 'metadata' => $providerMetadata,
930 // Give hooks a chance to abort. Combined with the SessionMetadata
931 // hook, this can allow for tying a session to an IP address or the
933 $reason = 'Hook aborted';
936 [ &$reason, $info, $request, $metadata, $data ]
938 $this->logger
->warning( 'Session "{session}": ' . $reason, [
948 * Create a session corresponding to the passed SessionInfo
949 * @private For use by a SessionProvider that needs to specially create its
951 * @param SessionInfo $info
952 * @param WebRequest $request
955 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
956 $id = $info->getId();
958 if ( !isset( $this->allSessionBackends
[$id] ) ) {
959 if ( !isset( $this->allSessionIds
[$id] ) ) {
960 $this->allSessionIds
[$id] = new SessionId( $id );
962 $backend = new SessionBackend(
963 $this->allSessionIds
[$id],
967 $this->config
->get( 'ObjectCacheSessionExpiry' )
969 $this->allSessionBackends
[$id] = $backend;
970 $delay = $backend->delaySave();
972 $backend = $this->allSessionBackends
[$id];
973 $delay = $backend->delaySave();
974 if ( $info->wasPersisted() ) {
977 if ( $info->wasRemembered() ) {
978 $backend->setRememberUser( true );
982 $request->setSessionId( $backend->getSessionId() );
983 $session = $backend->getSession( $request );
985 if ( !$info->isIdSafe() ) {
989 \ScopedCallback
::consume( $delay );
994 * Deregister a SessionBackend
995 * @private For use from \\MediaWiki\\Session\\SessionBackend only
996 * @param SessionBackend $backend
998 public function deregisterSessionBackend( SessionBackend
$backend ) {
999 $id = $backend->getId();
1000 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
1001 $this->allSessionBackends
[$id] !== $backend ||
1002 $this->allSessionIds
[$id] !== $backend->getSessionId()
1004 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1007 unset( $this->allSessionBackends
[$id] );
1008 // Explicitly do not unset $this->allSessionIds[$id]
1012 * Change a SessionBackend's ID
1013 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1014 * @param SessionBackend $backend
1016 public function changeBackendId( SessionBackend
$backend ) {
1017 $sessionId = $backend->getSessionId();
1018 $oldId = (string)$sessionId;
1019 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1020 $this->allSessionBackends
[$oldId] !== $backend ||
1021 $this->allSessionIds
[$oldId] !== $sessionId
1023 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1026 $newId = $this->generateSessionId();
1028 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1029 $sessionId->setId( $newId );
1030 $this->allSessionBackends
[$newId] = $backend;
1031 $this->allSessionIds
[$newId] = $sessionId;
1035 * Generate a new random session ID
1038 public function generateSessionId() {
1040 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1041 $key = wfMemcKey( 'MWSession', $id );
1042 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1047 * Call setters on a PHPSessionHandler
1048 * @private Use PhpSessionHandler::install()
1049 * @param PHPSessionHandler $handler
1051 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1052 $handler->setManager( $this, $this->store
, $this->logger
);
1056 * Reset the internal caching for unit testing
1058 public static function resetCache() {
1059 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1060 // @codeCoverageIgnoreStart
1061 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1062 // @codeCoverageIgnoreEnd
1065 self
::$globalSession = null;
1066 self
::$globalSessionRequest = null;
1070 * Do a sanity check to make sure the session is not used from many different IP addresses
1071 * and store some data for later sanity checks.
1072 * FIXME remove this once SessionManager is considered stable
1073 * @private For use in Setup.php only
1074 * @param Session $session Defaults to the global session.
1076 public function checkIpLimits( Session
$session = null ) {
1077 $session = $session ?
: self
::getGlobalSession();
1080 $ip = $session->getRequest()->getIP();
1081 } catch ( \MWException
$e ) {
1084 if ( $ip === '127.0.0.1' || \IP
::isConfiguredProxy( $ip ) ) {
1089 // Record (and possibly log) that the IP is using the current session.
1090 // Don't touch the stored data unless we are adding a new IP or re-adding an expired one.
1091 // This is slightly inaccurate (when an existing IP is seen again, the expiry is not
1092 // extended) but that shouldn't make much difference and limits the session write frequency
1093 // to # of IPs / $wgSuspiciousIpExpiry.
1094 $data = $session->get( 'SessionManager-ip', [] );
1096 !isset( $data[$ip] )
1097 ||
$data[$ip] < $now
1099 $data[$ip] = time() +
$this->config
->get( 'SuspiciousIpExpiry' );
1100 foreach ( $data as $key => $expires ) {
1101 if ( $expires < $now ) {
1102 unset( $data[$key] );
1105 $session->set( 'SessionManager-ip', $data );
1107 $logger = \MediaWiki\Logger\LoggerFactory
::getInstance( 'session-ip' );
1108 $logLevel = count( $data ) >= $this->config
->get( 'SuspiciousIpPerSessionLimit' )
1109 ? LogLevel
::WARNING
: ( count( $data ) === 1 ? LogLevel
::DEBUG
: LogLevel
::INFO
);
1112 'Same session used from {count} IPs',
1114 'count' => count( $data ),
1116 'session' => $session->getId(),
1117 'user' => $session->getUser()->getName(),
1118 'persistent' => $session->isPersistent(),
1123 // Now do the same thing globally for the current user.
1124 // We are using the object cache and assume it is shared between all wikis of a farm,
1125 // and further assume that the same name belongs to the same user on all wikis. (It's either
1126 // that or a central ID lookup which would mean an extra SQL query on every request.)
1127 if ( $session->getUser()->isLoggedIn() ) {
1128 $userKey = 'SessionManager-ip:' . md5( $session->getUser()->getName() );
1129 $data = $this->store
->get( $userKey ) ?
: [];
1131 !isset( $data[$ip] )
1132 ||
$data[$ip] < $now
1134 $data[$ip] = time() +
$this->config
->get( 'SuspiciousIpExpiry' );
1135 foreach ( $data as $key => $expires ) {
1136 if ( $expires < $now ) {
1137 unset( $data[$key] );
1140 $this->store
->set( $userKey, $data, $this->config
->get( 'SuspiciousIpExpiry' ) );
1141 $logger = \MediaWiki\Logger\LoggerFactory
::getInstance( 'session-ip' );
1142 $logLevel = count( $data ) >= $this->config
->get( 'SuspiciousIpPerUserLimit' )
1143 ? LogLevel
::WARNING
: ( count( $data ) === 1 ? LogLevel
::DEBUG
: LogLevel
::INFO
);
1146 'Same user had sessions from {count} IPs',
1148 'count' => count( $data ),
1150 'session' => $session->getId(),
1151 'user' => $session->getUser()->getName(),
1152 'persistent' => $session->isPersistent(),