83 private static $instance =
null;
86 private static $globalSession =
null;
89 private static $globalSessionRequest =
null;
95 private $hookContainer;
104 private $userNameUtils;
110 private $sessionProviders =
null;
113 private $varyCookies =
null;
116 private $varyHeaders =
null;
119 private $allSessionBackends = [];
122 private $allSessionIds = [];
125 private $preventUsers = [];
132 if ( self::$instance ===
null ) {
133 self::$instance =
new self();
135 return self::$instance;
151 $request = RequestContext::getMain()->getRequest();
153 !self::$globalSession
154 || self::$globalSessionRequest !== $request
155 || ( $id !==
'' && self::$globalSession->getId() !== $id )
157 self::$globalSessionRequest = $request;
167 self::$globalSession = $request->
getSession();
172 self::$globalSession =
self::singleton()->getSessionById( $id,
true, $request )
176 return self::$globalSession;
187 if ( isset( $options[
'config'] ) ) {
188 $this->config = $options[
'config'];
189 if ( !$this->config instanceof
Config ) {
190 throw new InvalidArgumentException(
191 '$options[\'config\'] must be an instance of Config'
195 $this->config = $services->getMainConfig();
198 if ( isset( $options[
'logger'] ) ) {
199 if ( !$options[
'logger'] instanceof LoggerInterface ) {
200 throw new InvalidArgumentException(
201 '$options[\'logger\'] must be an instance of LoggerInterface'
204 $this->setLogger( $options[
'logger'] );
206 $this->setLogger( \
MediaWiki\Logger\LoggerFactory::getInstance(
'session' ) );
209 if ( isset( $options[
'hookContainer'] ) ) {
210 $this->setHookContainer( $options[
'hookContainer'] );
212 $this->setHookContainer( $services->getHookContainer() );
215 if ( isset( $options[
'store'] ) ) {
216 if ( !$options[
'store'] instanceof
BagOStuff ) {
217 throw new InvalidArgumentException(
218 '$options[\'store\'] must be an instance of BagOStuff'
221 $store = $options[
'store'];
223 $store = $services->getObjectCacheFactory()
227 $this->logger->debug(
'SessionManager using store ' . get_class( $store ) );
229 $this->userNameUtils = $services->getUserNameUtils();
231 register_shutdown_function( [ $this,
'shutdown' ] );
235 $this->logger = $logger;
243 $this->hookContainer = $hookContainer;
244 $this->hookRunner =
new HookRunner( $hookContainer );
248 $info = $this->getSessionInfoForRequest( $request );
251 $session = $this->getInitialSession( $request );
253 $session = $this->getSessionFromInfo( $info, $request );
259 if ( !self::validateSessionId( $id ) ) {
260 throw new InvalidArgumentException(
'Invalid session ID' );
270 if ( isset( $this->allSessionBackends[$id] ) ) {
271 return $this->getSessionFromInfo( $info, $request );
275 $key = $this->store->makeKey(
'MWSession', $id );
276 if ( is_array( $this->store->get( $key ) ) ) {
278 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
279 $session = $this->getSessionFromInfo( $info, $request );
283 if ( $create && $session ===
null ) {
285 $session = $this->getEmptySessionInternal( $request, $id );
286 }
catch ( \Exception $ex ) {
287 $this->logger->error(
'Failed to create empty session: {exception}',
289 'method' => __METHOD__,
300 return $this->getEmptySessionInternal( $request );
309 private function getEmptySessionInternal(
WebRequest $request =
null, $id =
null ) {
310 if ( $id !==
null ) {
311 if ( !self::validateSessionId( $id ) ) {
312 throw new InvalidArgumentException(
'Invalid session ID' );
315 $key = $this->store->makeKey(
'MWSession', $id );
316 if ( is_array( $this->store->get( $key ) ) ) {
317 throw new InvalidArgumentException(
'Session ID already exists' );
321 $request =
new FauxRequest;
325 foreach ( $this->getProviders() as $provider ) {
326 $info = $provider->newSessionInfo( $id );
331 throw new \UnexpectedValueException(
332 "$provider returned an empty session info for a different provider: $info"
335 if ( $id !==
null && $info->
getId() !== $id ) {
336 throw new \UnexpectedValueException(
337 "$provider returned empty session info with a wrong id: " .
338 $info->
getId() .
' != ' . $id
342 throw new \UnexpectedValueException(
343 "$provider returned empty session info with id flagged unsafe"
347 if ( $compare > 0 ) {
350 if ( $compare === 0 ) {
358 if ( count( $infos ) > 1 ) {
359 throw new \UnexpectedValueException(
360 'Multiple empty sessions tied for top priority: ' . implode(
', ', $infos )
362 } elseif ( count( $infos ) < 1 ) {
363 throw new \UnexpectedValueException(
'No provider could provide an empty session!' );
367 return $this->getSessionFromInfo( $infos[0], $request );
379 private function getInitialSession( WebRequest $request =
null ) {
380 $session = $this->getEmptySession( $request );
381 $session->getToken();
389 foreach ( $this->getProviders() as $provider ) {
390 $provider->invalidateSessionsForUser( $user );
399 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
403 if ( $this->varyHeaders ===
null ) {
405 foreach ( $this->getProviders() as $provider ) {
406 foreach ( $provider->getVaryHeaders() as
$header => $_ ) {
410 $this->varyHeaders = $headers;
412 return $this->varyHeaders;
417 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
421 if ( $this->varyCookies ===
null ) {
423 foreach ( $this->getProviders() as $provider ) {
424 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
426 $this->varyCookies = array_values( array_unique( $cookies ) );
428 return $this->varyCookies;
437 return is_string( $id ) && preg_match(
'/^[a-zA-Z0-9_-]{32,}$/', $id );
454 $this->preventUsers[$username] =
true;
457 foreach ( $this->getProviders() as $provider ) {
458 $provider->preventSessionsForUser( $username );
469 return !empty( $this->preventUsers[$username] );
477 if ( $this->sessionProviders ===
null ) {
478 $this->sessionProviders = [];
482 $provider = $objectFactory->createObject( $spec );
487 $this->hookContainer,
490 if ( isset( $this->sessionProviders[(
string)$provider] ) ) {
492 throw new \UnexpectedValueException(
"Duplicate provider name \"$provider\"" );
494 $this->sessionProviders[(string)$provider] = $provider;
497 return $this->sessionProviders;
511 $providers = $this->getProviders();
512 return $providers[$name] ??
null;
520 if ( $this->allSessionBackends ) {
521 $this->logger->debug(
'Saving all sessions on shutdown' );
522 if ( session_id() !==
'' ) {
524 session_write_close();
527 foreach ( $this->allSessionBackends as $backend ) {
528 $backend->shutdown();
538 private function getSessionInfoForRequest(
WebRequest $request ) {
541 foreach ( $this->getProviders() as $provider ) {
542 $info = $provider->provideSessionInfo( $request );
547 throw new \UnexpectedValueException(
548 "$provider returned session info for a different provider: $info"
557 usort( $infos, [ SessionInfo::class,
'compare' ] );
560 $info = array_pop( $infos );
561 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
565 $info = array_pop( $infos );
570 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
576 $this->logUnpersist( $info, $request );
577 $info->
getProvider()->unpersistSession( $request );
582 $this->logUnpersist( $info, $request );
583 $info->
getProvider()->unpersistSession( $request );
587 if ( count( $retInfos ) > 1 ) {
588 throw new SessionOverflowException(
590 'Multiple sessions for this request tied for top priority: ' . implode(
', ', $retInfos )
594 return $retInfos[0] ??
null;
604 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
605 $key = $this->store->makeKey(
'MWSession', $info->getId() );
606 $blob = $this->store->get( $key );
611 if ( $info->forceUse() && $blob !==
false ) {
612 $failHandler =
function () use ( $key, &$info, $request ) {
613 $this->store->delete( $key );
614 return $this->loadSessionInfoFromStore( $info, $request );
617 $failHandler =
static function () {
624 if ( $blob !==
false ) {
626 if ( !is_array( $blob ) ) {
627 $this->logger->warning(
'Session "{session}": Bad data', [
628 'session' => $info->__toString(),
630 $this->store->delete( $key );
631 return $failHandler();
635 if ( !isset( $blob[
'data'] ) || !is_array( $blob[
'data'] ) ||
636 !isset( $blob[
'metadata'] ) || !is_array( $blob[
'metadata'] )
638 $this->logger->warning(
'Session "{session}": Bad data structure', [
639 'session' => $info->__toString(),
641 $this->store->delete( $key );
642 return $failHandler();
645 $data = $blob[
'data'];
646 $metadata = $blob[
'metadata'];
650 if ( !array_key_exists(
'userId', $metadata ) ||
651 !array_key_exists(
'userName', $metadata ) ||
652 !array_key_exists(
'userToken', $metadata ) ||
653 !array_key_exists(
'provider', $metadata )
655 $this->logger->warning(
'Session "{session}": Bad metadata', [
656 'session' => $info->__toString(),
658 $this->store->delete( $key );
659 return $failHandler();
663 $provider = $info->getProvider();
664 if ( $provider ===
null ) {
665 $newParams[
'provider'] = $provider = $this->getProvider( $metadata[
'provider'] );
667 $this->logger->warning(
668 'Session "{session}": Unknown provider ' . $metadata[
'provider'],
670 'session' => $info->__toString(),
673 $this->store->delete( $key );
674 return $failHandler();
676 } elseif ( $metadata[
'provider'] !== (
string)$provider ) {
677 $this->logger->warning(
'Session "{session}": Wrong provider ' .
678 $metadata[
'provider'] .
' !== ' . $provider,
680 'session' => $info->__toString(),
682 return $failHandler();
686 $providerMetadata = $info->getProviderMetadata();
687 if ( isset( $metadata[
'providerMetadata'] ) ) {
688 if ( $providerMetadata ===
null ) {
689 $newParams[
'metadata'] = $metadata[
'providerMetadata'];
692 $newProviderMetadata = $provider->mergeMetadata(
693 $metadata[
'providerMetadata'], $providerMetadata
695 if ( $newProviderMetadata !== $providerMetadata ) {
696 $newParams[
'metadata'] = $newProviderMetadata;
698 }
catch ( MetadataMergeException $ex ) {
699 $this->logger->warning(
700 'Session "{session}": Metadata merge failed: {exception}',
702 'session' => $info->__toString(),
704 ] + $ex->getContext()
706 return $failHandler();
712 $userInfo = $info->getUserInfo();
716 if ( $metadata[
'userId'] ) {
718 } elseif ( $metadata[
'userName'] !==
null ) {
723 }
catch ( InvalidArgumentException $ex ) {
724 $this->logger->error(
'Session "{session}": {exception}', [
725 'session' => $info->__toString(),
728 return $failHandler();
730 $newParams[
'userInfo'] = $userInfo;
734 if ( $metadata[
'userId'] ) {
735 if ( $metadata[
'userId'] !== $userInfo->getId() ) {
737 $this->logger->warning(
738 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
740 'session' => $info->__toString(),
741 'uid_a' => $metadata[
'userId'],
742 'uid_b' => $userInfo->getId(),
743 'uname_a' => $metadata[
'userName'] ??
'<null>',
744 'uname_b' => $userInfo->getName() ??
'<null>',
746 return $failHandler();
750 if ( $metadata[
'userName'] !==
null &&
751 $userInfo->getName() !== $metadata[
'userName']
753 $this->logger->warning(
754 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
756 'session' => $info->__toString(),
757 'uname_a' => $metadata[
'userName'],
758 'uname_b' => $userInfo->getName(),
760 return $failHandler();
763 } elseif ( $metadata[
'userName'] !==
null ) {
764 if ( $metadata[
'userName'] !== $userInfo->getName() ) {
765 $this->logger->warning(
766 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
768 'session' => $info->__toString(),
769 'uname_a' => $metadata[
'userName'],
770 'uname_b' => $userInfo->getName(),
772 return $failHandler();
774 } elseif ( !$userInfo->isAnon() ) {
778 $this->logger->warning(
779 'Session "{session}": the session store entry is for an anonymous user, '
780 .
'but the session metadata indicates a non-anonynmous user',
782 'session' => $info->__toString(),
784 return $failHandler();
790 if ( $metadata[
'userToken'] !==
null &&
791 $userInfo->getToken() !== $metadata[
'userToken']
793 $this->logger->warning(
'Session "{session}": User token mismatch', [
794 'session' => $info->__toString(),
796 return $failHandler();
798 if ( !$userInfo->isVerified() ) {
799 $newParams[
'userInfo'] = $userInfo->verified();
802 if ( !empty( $metadata[
'remember'] ) && !$info->wasRemembered() ) {
803 $newParams[
'remembered'] =
true;
805 if ( !empty( $metadata[
'forceHTTPS'] ) && !$info->forceHTTPS() ) {
806 $newParams[
'forceHTTPS'] =
true;
808 if ( !empty( $metadata[
'persisted'] ) && !$info->wasPersisted() ) {
809 $newParams[
'persisted'] =
true;
812 if ( !$info->isIdSafe() ) {
813 $newParams[
'idIsSafe'] =
true;
817 if ( $info->getProvider() ===
null ) {
818 $this->logger->warning(
819 'Session "{session}": Null provider and no metadata',
821 'session' => $info->__toString(),
823 return $failHandler();
827 if ( !$info->getUserInfo() ) {
828 if ( $info->getProvider()->canChangeUser() ) {
834 'Session "{session}": No user provided and provider cannot set user',
836 'session' => $info->__toString(),
838 return $failHandler();
840 } elseif ( !$info->getUserInfo()->isVerified() ) {
845 'Session "{session}": Unverified user provided and no metadata to auth it',
847 'session' => $info->__toString(),
849 return $failHandler();
855 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
858 $newParams[
'idIsSafe'] =
true;
864 $newParams[
'copyFrom'] = $info;
865 $info =
new SessionInfo( $info->getPriority(), $newParams );
869 $providerMetadata = $info->getProviderMetadata();
870 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
871 return $failHandler();
873 if ( $providerMetadata !== $info->getProviderMetadata() ) {
874 $info =
new SessionInfo( $info->getPriority(), [
875 'metadata' => $providerMetadata,
883 $reason =
'Hook aborted';
884 if ( !$this->hookRunner->onSessionCheckInfo(
885 $reason, $info, $request, $metadata, $data )
887 $this->logger->warning(
'Session "{session}": ' . $reason, [
888 'session' => $info->__toString(),
890 return $failHandler();
906 if ( defined(
'MW_NO_SESSION' ) ) {
911 $this->logger->error(
'Sessions are supposed to be disabled for this entry point', [
912 'exception' =>
new \BadMethodCallException(
"Sessions are disabled for $ep entry point" ),
915 throw new \BadMethodCallException(
"Sessions are disabled for $ep entry point" );
920 $id = $info->
getId();
922 if ( !isset( $this->allSessionBackends[$id] ) ) {
923 if ( !isset( $this->allSessionIds[$id] ) ) {
924 $this->allSessionIds[$id] =
new SessionId( $id );
927 $this->allSessionIds[$id],
931 $this->hookContainer,
934 $this->allSessionBackends[$id] = $backend;
935 $delay = $backend->delaySave();
937 $backend = $this->allSessionBackends[$id];
938 $delay = $backend->delaySave();
943 $backend->setRememberUser(
true );
948 $session = $backend->getSession( $request );
954 \Wikimedia\ScopedCallback::consume( $delay );
964 $id = $backend->
getId();
965 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
966 $this->allSessionBackends[$id] !== $backend ||
969 throw new InvalidArgumentException(
'Backend was not registered with this SessionManager' );
972 unset( $this->allSessionBackends[$id] );
983 $oldId = (string)$sessionId;
984 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
985 $this->allSessionBackends[$oldId] !== $backend ||
986 $this->allSessionIds[$oldId] !== $sessionId
988 throw new InvalidArgumentException(
'Backend was not registered with this SessionManager' );
991 $newId = $this->generateSessionId();
993 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
994 $sessionId->setId( $newId );
995 $this->allSessionBackends[$newId] = $backend;
996 $this->allSessionIds[$newId] = $sessionId;
1004 $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
1006 $key = $this->store->makeKey(
'MWSession', $id );
1007 $this->store->set( $key,
false, 0, BagOStuff::WRITE_CACHE_ONLY );
1017 $handler->
setManager( $this, $this->store, $this->logger );
1026 if ( !defined(
'MW_PHPUNIT_TEST' ) && !defined(
'MW_PARSER_TEST' ) ) {
1028 throw new LogicException( __METHOD__ .
' may only be called from unit tests!' );
1032 self::$globalSession =
null;
1033 self::$globalSessionRequest =
null;
1038 'id' => $info->
getId(),
1041 'clientip' => $request->
getIP(),
1042 'userAgent' => $request->
getHeader(
'user-agent' ),
1046 $logData[
'user'] = $info->
getUserInfo()->getName();
1048 $logData[
'userVerified'] = $info->
getUserInfo()->isVerified();
1050 $this->logger->info(
'Failed to load session, unpersisting', $logData );
1065 $session = $session ?: self::getGlobalSession();
1068 if ( $suspiciousIpExpiry ===
false
1070 || !$session->isPersistent() || $session->getUser()->isAnon()
1077 $ip = $session->getRequest()->getIP();
1081 if ( $ip ===
'127.0.0.1' || $proxyLookup->isConfiguredProxy( $ip ) ) {
1084 $mwuser = $session->getRequest()->getCookie(
'mwuser-sessionId' );
1085 $now = (int)\
MediaWiki\Utils\MWTimestamp::now( TS_UNIX );
1091 $data = $session->get(
'SessionManager-logPotentialSessionLeakage', [] )
1092 + [
'ip' =>
null,
'mwuser' =>
null,
'timestamp' => 0 ];
1096 ( $now - $data[
'timestamp'] > $suspiciousIpExpiry )
1098 $data[
'ip'] = $data[
'timestamp'] =
null;
1101 if ( $data[
'ip'] !== $ip || $data[
'mwuser'] !== $mwuser ) {
1102 $session->set(
'SessionManager-logPotentialSessionLeakage',
1103 [
'ip' => $ip,
'mwuser' => $mwuser,
'timestamp' => $now ] );
1106 $ipChanged = ( $data[
'ip'] && $data[
'ip'] !== $ip );
1107 $mwuserChanged = ( $data[
'mwuser'] && $data[
'mwuser'] !== $mwuser );
1108 $logLevel = $message =
null;
1116 $logLevel = LogLevel::INFO;
1117 $message =
'IP change within the same session';
1119 'oldIp' => $data[
'ip'],
1120 'oldIpRecorded' => $data[
'timestamp'],
1123 if ( $mwuserChanged ) {
1124 $logLevel = LogLevel::NOTICE;
1125 $message =
'mwuser change within the same session';
1127 'oldMwuser' => $data[
'mwuser'],
1128 'newMwuser' => $mwuser,
1131 if ( $ipChanged && $mwuserChanged ) {
1132 $logLevel = LogLevel::WARNING;
1133 $message =
'IP and mwuser change within the same session';
1137 'session' => $session->getId(),
1138 'user' => $session->getUser()->getName(),
1140 'userAgent' => $session->getRequest()->getHeader(
'user-agent' ),
1142 $logger = \MediaWiki\Logger\LoggerFactory::getInstance(
'session-ip' );
1144 $logger->log( $logLevel, $message, $logData );