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 $logger->error( __METHOD__
. ': failed with message ' . $status->getWikiText(),
482 'username' => $userName,
487 // @codeCoverageIgnoreEnd
489 } catch ( \Exception
$ex ) {
490 // @codeCoverageIgnoreStart
491 $logger->error( __METHOD__
. ': failed with exception {exception}', [
493 'username' => $userName,
495 // Do not keep throwing errors for a while
496 $cache->set( $backoffKey, 1, 600 );
497 // Bubble up error; which should normally trigger DB rollbacks
499 // @codeCoverageIgnoreEnd
504 $wgAuth->initUser( $tmpUser, true );
505 if ( $tmpUser !== $user ) {
506 $logger->warning( __METHOD__
. ': ' .
507 get_class( $wgAuth ) . '::initUser() replaced the user object' );
510 # Notify hooks (e.g. Newuserlog)
511 \Hooks
::run( 'AuthPluginAutoCreate', [ $user ] );
512 \Hooks
::run( 'LocalUserCreated', [ $user, true ] );
514 $user->saveSettings();
517 \DeferredUpdates
::addUpdate( new \
SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
519 # Watch user's userpage and talk page
520 $user->addWatch( $user->getUserPage(), \WatchedItem
::IGNORE_USER_RIGHTS
);
526 * Prevent future sessions for the user
528 * The intention is that the named account will never again be usable for
529 * normal login (i.e. there is no way to undo the prevention of access).
531 * @private For use from \\User::newSystemUser only
532 * @param string $username
534 public function preventSessionsForUser( $username ) {
535 $this->preventUsers
[$username] = true;
537 // Instruct the session providers to kill any other sessions too.
538 foreach ( $this->getProviders() as $provider ) {
539 $provider->preventSessionsForUser( $username );
544 * Test if a user is prevented
545 * @private For use from SessionBackend only
546 * @param string $username
549 public function isUserSessionPrevented( $username ) {
550 return !empty( $this->preventUsers
[$username] );
554 * Get the available SessionProviders
555 * @return SessionProvider[]
557 protected function getProviders() {
558 if ( $this->sessionProviders
=== null ) {
559 $this->sessionProviders
= [];
560 foreach ( $this->config
->get( 'SessionProviders' ) as $spec ) {
561 $provider = \ObjectFactory
::getObjectFromSpec( $spec );
562 $provider->setLogger( $this->logger
);
563 $provider->setConfig( $this->config
);
564 $provider->setManager( $this );
565 if ( isset( $this->sessionProviders
[(string)$provider] ) ) {
566 throw new \
UnexpectedValueException( "Duplicate provider name \"$provider\"" );
568 $this->sessionProviders
[(string)$provider] = $provider;
571 return $this->sessionProviders
;
575 * Get a session provider by name
577 * Generally, this will only be used by internal implementation of some
578 * special session-providing mechanism. General purpose code, if it needs
579 * to access a SessionProvider at all, will use Session::getProvider().
581 * @param string $name
582 * @return SessionProvider|null
584 public function getProvider( $name ) {
585 $providers = $this->getProviders();
586 return isset( $providers[$name] ) ?
$providers[$name] : null;
590 * Save all active sessions on shutdown
591 * @private For internal use with register_shutdown_function()
593 public function shutdown() {
594 if ( $this->allSessionBackends
) {
595 $this->logger
->debug( 'Saving all sessions on shutdown' );
596 if ( session_id() !== '' ) {
597 // @codeCoverageIgnoreStart
598 session_write_close();
600 // @codeCoverageIgnoreEnd
601 foreach ( $this->allSessionBackends
as $backend ) {
602 $backend->save( true );
608 * Fetch the SessionInfo(s) for a request
609 * @param WebRequest $request
610 * @return SessionInfo|null
612 private function getSessionInfoForRequest( WebRequest
$request ) {
613 // Call all providers to fetch "the" session
615 foreach ( $this->getProviders() as $provider ) {
616 $info = $provider->provideSessionInfo( $request );
620 if ( $info->getProvider() !== $provider ) {
621 throw new \
UnexpectedValueException(
622 "$provider returned session info for a different provider: $info"
628 // Sort the SessionInfos. Then find the first one that can be
629 // successfully loaded, and then all the ones after it with the same
631 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
634 $info = array_pop( $infos );
635 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
638 $info = array_pop( $infos );
639 if ( SessionInfo
::compare( $retInfos[0], $info ) ) {
640 // We hit a lower priority, stop checking.
643 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
644 // This is going to error out below, but we want to
645 // provide a complete list.
652 if ( count( $retInfos ) > 1 ) {
653 $ex = new \
OverflowException(
654 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
656 $ex->sessionInfos
= $retInfos;
660 return $retInfos ?
$retInfos[0] : null;
664 * Load and verify the session info against the store
666 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
667 * @param WebRequest $request
668 * @return bool Whether the session info matches the stored data (if any)
670 private function loadSessionInfoFromStore( SessionInfo
&$info, WebRequest
$request ) {
671 $key = wfMemcKey( 'MWSession', $info->getId() );
672 $blob = $this->store
->get( $key );
676 if ( $blob !== false ) {
677 // Sanity check: blob must be an array, if it's saved at all
678 if ( !is_array( $blob ) ) {
679 $this->logger
->warning( 'Session "{session}": Bad data', [
682 $this->store
->delete( $key );
686 // Sanity check: blob has data and metadata arrays
687 if ( !isset( $blob['data'] ) ||
!is_array( $blob['data'] ) ||
688 !isset( $blob['metadata'] ) ||
!is_array( $blob['metadata'] )
690 $this->logger
->warning( 'Session "{session}": Bad data structure', [
693 $this->store
->delete( $key );
697 $data = $blob['data'];
698 $metadata = $blob['metadata'];
700 // Sanity check: metadata must be an array and must contain certain
701 // keys, if it's saved at all
702 if ( !array_key_exists( 'userId', $metadata ) ||
703 !array_key_exists( 'userName', $metadata ) ||
704 !array_key_exists( 'userToken', $metadata ) ||
705 !array_key_exists( 'provider', $metadata )
707 $this->logger
->warning( 'Session "{session}": Bad metadata', [
710 $this->store
->delete( $key );
714 // First, load the provider from metadata, or validate it against the metadata.
715 $provider = $info->getProvider();
716 if ( $provider === null ) {
717 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
719 $this->logger
->warning(
720 'Session "{session}": Unknown provider ' . $metadata['provider'],
725 $this->store
->delete( $key );
728 } elseif ( $metadata['provider'] !== (string)$provider ) {
729 $this->logger
->warning( 'Session "{session}": Wrong provider ' .
730 $metadata['provider'] . ' !== ' . $provider,
737 // Load provider metadata from metadata, or validate it against the metadata
738 $providerMetadata = $info->getProviderMetadata();
739 if ( isset( $metadata['providerMetadata'] ) ) {
740 if ( $providerMetadata === null ) {
741 $newParams['metadata'] = $metadata['providerMetadata'];
744 $newProviderMetadata = $provider->mergeMetadata(
745 $metadata['providerMetadata'], $providerMetadata
747 if ( $newProviderMetadata !== $providerMetadata ) {
748 $newParams['metadata'] = $newProviderMetadata;
750 } catch ( MetadataMergeException
$ex ) {
751 $this->logger
->warning(
752 'Session "{session}": Metadata merge failed: {exception}',
756 ] +
$ex->getContext()
763 // Next, load the user from metadata, or validate it against the metadata.
764 $userInfo = $info->getUserInfo();
766 // For loading, id is preferred to name.
768 if ( $metadata['userId'] ) {
769 $userInfo = UserInfo
::newFromId( $metadata['userId'] );
770 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
771 $userInfo = UserInfo
::newFromName( $metadata['userName'] );
773 $userInfo = UserInfo
::newAnonymous();
775 } catch ( \InvalidArgumentException
$ex ) {
776 $this->logger
->error( 'Session "{session}": {exception}', [
782 $newParams['userInfo'] = $userInfo;
784 // User validation passes if user ID matches, or if there
785 // is no saved ID and the names match.
786 if ( $metadata['userId'] ) {
787 if ( $metadata['userId'] !== $userInfo->getId() ) {
788 $this->logger
->warning(
789 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
792 'uid_a' => $metadata['userId'],
793 'uid_b' => $userInfo->getId(),
798 // If the user was renamed, probably best to fail here.
799 if ( $metadata['userName'] !== null &&
800 $userInfo->getName() !== $metadata['userName']
802 $this->logger
->warning(
803 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
806 'uname_a' => $metadata['userName'],
807 'uname_b' => $userInfo->getName(),
812 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
813 if ( $metadata['userName'] !== $userInfo->getName() ) {
814 $this->logger
->warning(
815 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
818 'uname_a' => $metadata['userName'],
819 'uname_b' => $userInfo->getName(),
823 } elseif ( !$userInfo->isAnon() ) {
824 // Metadata specifies an anonymous user, but the passed-in
825 // user isn't anonymous.
826 $this->logger
->warning(
827 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
835 // And if we have a token in the metadata, it must match the loaded/provided user.
836 if ( $metadata['userToken'] !== null &&
837 $userInfo->getToken() !== $metadata['userToken']
839 $this->logger
->warning( 'Session "{session}": User token mismatch', [
844 if ( !$userInfo->isVerified() ) {
845 $newParams['userInfo'] = $userInfo->verified();
848 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
849 $newParams['remembered'] = true;
851 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
852 $newParams['forceHTTPS'] = true;
854 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
855 $newParams['persisted'] = true;
858 if ( !$info->isIdSafe() ) {
859 $newParams['idIsSafe'] = true;
862 // No metadata, so we can't load the provider if one wasn't given.
863 if ( $info->getProvider() === null ) {
864 $this->logger
->warning(
865 'Session "{session}": Null provider and no metadata',
872 // If no user was provided and no metadata, it must be anon.
873 if ( !$info->getUserInfo() ) {
874 if ( $info->getProvider()->canChangeUser() ) {
875 $newParams['userInfo'] = UserInfo
::newAnonymous();
878 'Session "{session}": No user provided and provider cannot set user',
884 } elseif ( !$info->getUserInfo()->isVerified() ) {
885 $this->logger
->warning(
886 'Session "{session}": Unverified user provided and no metadata to auth it',
896 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
897 // The ID doesn't come from the user, so it should be safe
898 // (and if not, nothing we can do about it anyway)
899 $newParams['idIsSafe'] = true;
903 // Construct the replacement SessionInfo, if necessary
905 $newParams['copyFrom'] = $info;
906 $info = new SessionInfo( $info->getPriority(), $newParams );
909 // Allow the provider to check the loaded SessionInfo
910 $providerMetadata = $info->getProviderMetadata();
911 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
914 if ( $providerMetadata !== $info->getProviderMetadata() ) {
915 $info = new SessionInfo( $info->getPriority(), [
916 'metadata' => $providerMetadata,
921 // Give hooks a chance to abort. Combined with the SessionMetadata
922 // hook, this can allow for tying a session to an IP address or the
924 $reason = 'Hook aborted';
927 [ &$reason, $info, $request, $metadata, $data ]
929 $this->logger
->warning( 'Session "{session}": ' . $reason, [
939 * Create a session corresponding to the passed SessionInfo
940 * @private For use by a SessionProvider that needs to specially create its
942 * @param SessionInfo $info
943 * @param WebRequest $request
946 public function getSessionFromInfo( SessionInfo
$info, WebRequest
$request ) {
947 $id = $info->getId();
949 if ( !isset( $this->allSessionBackends
[$id] ) ) {
950 if ( !isset( $this->allSessionIds
[$id] ) ) {
951 $this->allSessionIds
[$id] = new SessionId( $id );
953 $backend = new SessionBackend(
954 $this->allSessionIds
[$id],
958 $this->config
->get( 'ObjectCacheSessionExpiry' )
960 $this->allSessionBackends
[$id] = $backend;
961 $delay = $backend->delaySave();
963 $backend = $this->allSessionBackends
[$id];
964 $delay = $backend->delaySave();
965 if ( $info->wasPersisted() ) {
968 if ( $info->wasRemembered() ) {
969 $backend->setRememberUser( true );
973 $request->setSessionId( $backend->getSessionId() );
974 $session = $backend->getSession( $request );
976 if ( !$info->isIdSafe() ) {
980 \ScopedCallback
::consume( $delay );
985 * Deregister a SessionBackend
986 * @private For use from \\MediaWiki\\Session\\SessionBackend only
987 * @param SessionBackend $backend
989 public function deregisterSessionBackend( SessionBackend
$backend ) {
990 $id = $backend->getId();
991 if ( !isset( $this->allSessionBackends
[$id] ) ||
!isset( $this->allSessionIds
[$id] ) ||
992 $this->allSessionBackends
[$id] !== $backend ||
993 $this->allSessionIds
[$id] !== $backend->getSessionId()
995 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
998 unset( $this->allSessionBackends
[$id] );
999 // Explicitly do not unset $this->allSessionIds[$id]
1003 * Change a SessionBackend's ID
1004 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1005 * @param SessionBackend $backend
1007 public function changeBackendId( SessionBackend
$backend ) {
1008 $sessionId = $backend->getSessionId();
1009 $oldId = (string)$sessionId;
1010 if ( !isset( $this->allSessionBackends
[$oldId] ) ||
!isset( $this->allSessionIds
[$oldId] ) ||
1011 $this->allSessionBackends
[$oldId] !== $backend ||
1012 $this->allSessionIds
[$oldId] !== $sessionId
1014 throw new \
InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1017 $newId = $this->generateSessionId();
1019 unset( $this->allSessionBackends
[$oldId], $this->allSessionIds
[$oldId] );
1020 $sessionId->setId( $newId );
1021 $this->allSessionBackends
[$newId] = $backend;
1022 $this->allSessionIds
[$newId] = $sessionId;
1026 * Generate a new random session ID
1029 public function generateSessionId() {
1031 $id = wfBaseConvert( \MWCryptRand
::generateHex( 40 ), 16, 32, 32 );
1032 $key = wfMemcKey( 'MWSession', $id );
1033 } while ( isset( $this->allSessionIds
[$id] ) ||
is_array( $this->store
->get( $key ) ) );
1038 * Call setters on a PHPSessionHandler
1039 * @private Use PhpSessionHandler::install()
1040 * @param PHPSessionHandler $handler
1042 public function setupPHPSessionHandler( PHPSessionHandler
$handler ) {
1043 $handler->setManager( $this, $this->store
, $this->logger
);
1047 * Reset the internal caching for unit testing
1049 public static function resetCache() {
1050 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1051 // @codeCoverageIgnoreStart
1052 throw new MWException( __METHOD__
. ' may only be called from unit tests!' );
1053 // @codeCoverageIgnoreEnd
1056 self
::$globalSession = null;
1057 self
::$globalSessionRequest = null;
1061 * Do a sanity check to make sure the session is not used from many different IP addresses
1062 * and store some data for later sanity checks.
1063 * FIXME remove this once SessionManager is considered stable
1064 * @private For use in Setup.php only
1065 * @param Session $session Defaults to the global session.
1067 public function checkIpLimits( Session
$session = null ) {
1068 $session = $session ?
: self
::getGlobalSession();
1071 $ip = $session->getRequest()->getIP();
1072 } catch ( \MWException
$e ) {
1075 if ( $ip === '127.0.0.1' || \IP
::isConfiguredProxy( $ip ) ) {
1080 // Record (and possibly log) that the IP is using the current session.
1081 // Don't touch the stored data unless we are adding a new IP or re-adding an expired one.
1082 // This is slightly inaccurate (when an existing IP is seen again, the expiry is not
1083 // extended) but that shouldn't make much difference and limits the session write frequency
1084 // to # of IPs / $wgSuspiciousIpExpiry.
1085 $data = $session->get( 'SessionManager-ip', [] );
1087 !isset( $data[$ip] )
1088 ||
$data[$ip] < $now
1090 $data[$ip] = time() +
$this->config
->get( 'SuspiciousIpExpiry' );
1091 foreach ( $data as $key => $expires ) {
1092 if ( $expires < $now ) {
1093 unset( $data[$key] );
1096 $session->set( 'SessionManager-ip', $data );
1098 $logger = \MediaWiki\Logger\LoggerFactory
::getInstance( 'session-ip' );
1099 $logLevel = count( $data ) >= $this->config
->get( 'SuspiciousIpPerSessionLimit' )
1100 ? LogLevel
::WARNING
: ( count( $data ) === 1 ? LogLevel
::DEBUG
: LogLevel
::INFO
);
1103 'Same session used from {count} IPs',
1105 'count' => count( $data ),
1107 'session' => $session->getId(),
1108 'user' => $session->getUser()->getName(),
1109 'persistent' => $session->isPersistent(),
1114 // Now do the same thing globally for the current user.
1115 // We are using the object cache and assume it is shared between all wikis of a farm,
1116 // and further assume that the same name belongs to the same user on all wikis. (It's either
1117 // that or a central ID lookup which would mean an extra SQL query on every request.)
1118 if ( $session->getUser()->isLoggedIn() ) {
1119 $userKey = 'SessionManager-ip:' . md5( $session->getUser()->getName() );
1120 $data = $this->store
->get( $userKey ) ?
: [];
1122 !isset( $data[$ip] )
1123 ||
$data[$ip] < $now
1125 $data[$ip] = time() +
$this->config
->get( 'SuspiciousIpExpiry' );
1126 foreach ( $data as $key => $expires ) {
1127 if ( $expires < $now ) {
1128 unset( $data[$key] );
1131 $this->store
->set( $userKey, $data, $this->config
->get( 'SuspiciousIpExpiry' ) );
1132 $logger = \MediaWiki\Logger\LoggerFactory
::getInstance( 'session-ip' );
1133 $logLevel = count( $data ) >= $this->config
->get( 'SuspiciousIpPerUserLimit' )
1134 ? LogLevel
::WARNING
: ( count( $data ) === 1 ? LogLevel
::DEBUG
: LogLevel
::INFO
);
1137 'Same user had sessions from {count} IPs',
1139 'count' => count( $data ),
1141 'session' => $session->getId(),
1142 'user' => $session->getUser()->getName(),
1143 'persistent' => $session->isPersistent(),