82 private static $instance =
null;
85 private static $globalSession =
null;
88 private static $globalSessionRequest =
null;
94 private $hookContainer;
103 private $userNameUtils;
109 private $sessionProviders =
null;
112 private $varyCookies =
null;
115 private $varyHeaders =
null;
118 private $allSessionBackends = [];
121 private $allSessionIds = [];
124 private $preventUsers = [];
131 if ( self::$instance ===
null ) {
132 self::$instance =
new self();
134 return self::$instance;
150 $request = RequestContext::getMain()->getRequest();
152 !self::$globalSession
153 || self::$globalSessionRequest !== $request
154 || ( $id !==
'' && self::$globalSession->getId() !== $id )
156 self::$globalSessionRequest = $request;
166 self::$globalSession = $request->
getSession();
171 self::$globalSession =
self::singleton()->getSessionById( $id,
true, $request )
175 return self::$globalSession;
185 if ( isset( $options[
'config'] ) ) {
186 $this->config = $options[
'config'];
187 if ( !$this->config instanceof
Config ) {
188 throw new \InvalidArgumentException(
189 '$options[\'config\'] must be an instance of Config'
196 if ( isset( $options[
'logger'] ) ) {
197 if ( !$options[
'logger'] instanceof LoggerInterface ) {
198 throw new \InvalidArgumentException(
199 '$options[\'logger\'] must be an instance of LoggerInterface'
202 $this->setLogger( $options[
'logger'] );
204 $this->setLogger( \
MediaWiki\Logger\LoggerFactory::getInstance(
'session' ) );
207 if ( isset( $options[
'hookContainer'] ) ) {
208 $this->setHookContainer( $options[
'hookContainer'] );
213 if ( isset( $options[
'store'] ) ) {
214 if ( !$options[
'store'] instanceof
BagOStuff ) {
215 throw new \InvalidArgumentException(
216 '$options[\'store\'] must be an instance of BagOStuff'
219 $store = $options[
'store'];
224 $this->logger->debug(
'SessionManager using store ' . get_class( $store ) );
228 register_shutdown_function( [ $this,
'shutdown' ] );
232 $this->logger = $logger;
240 $this->hookContainer = $hookContainer;
241 $this->hookRunner =
new HookRunner( $hookContainer );
245 $info = $this->getSessionInfoForRequest( $request );
248 $session = $this->getInitialSession( $request );
250 $session = $this->getSessionFromInfo( $info, $request );
256 if ( !self::validateSessionId( $id ) ) {
257 throw new \InvalidArgumentException(
'Invalid session ID' );
267 if ( isset( $this->allSessionBackends[$id] ) ) {
268 return $this->getSessionFromInfo( $info, $request );
272 $key = $this->store->makeKey(
'MWSession', $id );
273 if ( is_array( $this->store->get( $key ) ) ) {
275 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
276 $session = $this->getSessionFromInfo( $info, $request );
280 if ( $create && $session ===
null ) {
282 $session = $this->getEmptySessionInternal( $request, $id );
283 }
catch ( \Exception $ex ) {
284 $this->logger->error(
'Failed to create empty session: {exception}',
286 'method' => __METHOD__,
297 return $this->getEmptySessionInternal( $request );
306 private function getEmptySessionInternal(
WebRequest $request =
null, $id =
null ) {
307 if ( $id !==
null ) {
308 if ( !self::validateSessionId( $id ) ) {
309 throw new \InvalidArgumentException(
'Invalid session ID' );
312 $key = $this->store->makeKey(
'MWSession', $id );
313 if ( is_array( $this->store->get( $key ) ) ) {
314 throw new \InvalidArgumentException(
'Session ID already exists' );
318 $request =
new FauxRequest;
322 foreach ( $this->getProviders() as $provider ) {
323 $info = $provider->newSessionInfo( $id );
328 throw new \UnexpectedValueException(
329 "$provider returned an empty session info for a different provider: $info"
332 if ( $id !==
null && $info->
getId() !== $id ) {
333 throw new \UnexpectedValueException(
334 "$provider returned empty session info with a wrong id: " .
335 $info->
getId() .
' != ' . $id
339 throw new \UnexpectedValueException(
340 "$provider returned empty session info with id flagged unsafe"
344 if ( $compare > 0 ) {
347 if ( $compare === 0 ) {
355 if ( count( $infos ) > 1 ) {
356 throw new \UnexpectedValueException(
357 'Multiple empty sessions tied for top priority: ' . implode(
', ', $infos )
359 } elseif ( count( $infos ) < 1 ) {
360 throw new \UnexpectedValueException(
'No provider could provide an empty session!' );
364 return $this->getSessionFromInfo( $infos[0], $request );
376 private function getInitialSession( WebRequest $request =
null ) {
377 $session = $this->getEmptySession( $request );
378 $session->getToken();
386 foreach ( $this->getProviders() as $provider ) {
387 $provider->invalidateSessionsForUser( $user );
396 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
400 if ( $this->varyHeaders ===
null ) {
402 foreach ( $this->getProviders() as $provider ) {
403 foreach ( $provider->getVaryHeaders() as
$header => $_ ) {
407 $this->varyHeaders = $headers;
409 return $this->varyHeaders;
414 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
418 if ( $this->varyCookies ===
null ) {
420 foreach ( $this->getProviders() as $provider ) {
421 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
423 $this->varyCookies = array_values( array_unique( $cookies ) );
425 return $this->varyCookies;
434 return is_string( $id ) && preg_match(
'/^[a-zA-Z0-9_-]{32,}$/', $id );
451 $this->preventUsers[$username] =
true;
454 foreach ( $this->getProviders() as $provider ) {
455 $provider->preventSessionsForUser( $username );
466 return !empty( $this->preventUsers[$username] );
474 if ( $this->sessionProviders ===
null ) {
475 $this->sessionProviders = [];
479 $provider = $objectFactory->createObject( $spec );
484 $this->hookContainer,
487 if ( isset( $this->sessionProviders[(
string)$provider] ) ) {
489 throw new \UnexpectedValueException(
"Duplicate provider name \"$provider\"" );
491 $this->sessionProviders[(string)$provider] = $provider;
494 return $this->sessionProviders;
508 $providers = $this->getProviders();
509 return $providers[$name] ??
null;
517 if ( $this->allSessionBackends ) {
518 $this->logger->debug(
'Saving all sessions on shutdown' );
519 if ( session_id() !==
'' ) {
521 session_write_close();
524 foreach ( $this->allSessionBackends as $backend ) {
525 $backend->shutdown();
535 private function getSessionInfoForRequest(
WebRequest $request ) {
538 foreach ( $this->getProviders() as $provider ) {
539 $info = $provider->provideSessionInfo( $request );
544 throw new \UnexpectedValueException(
545 "$provider returned session info for a different provider: $info"
554 usort( $infos, [ SessionInfo::class,
'compare' ] );
557 $info = array_pop( $infos );
558 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
562 $info = array_pop( $infos );
567 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
573 $this->logUnpersist( $info, $request );
574 $info->
getProvider()->unpersistSession( $request );
579 $this->logUnpersist( $info, $request );
580 $info->
getProvider()->unpersistSession( $request );
584 if ( count( $retInfos ) > 1 ) {
585 throw new SessionOverflowException(
587 'Multiple sessions for this request tied for top priority: ' . implode(
', ', $retInfos )
591 return $retInfos[0] ??
null;
601 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
602 $key = $this->store->makeKey(
'MWSession', $info->getId() );
603 $blob = $this->store->get( $key );
608 if ( $info->forceUse() && $blob !==
false ) {
609 $failHandler =
function () use ( $key, &$info, $request ) {
610 $this->store->delete( $key );
611 return $this->loadSessionInfoFromStore( $info, $request );
614 $failHandler =
static function () {
621 if ( $blob !==
false ) {
623 if ( !is_array( $blob ) ) {
624 $this->logger->warning(
'Session "{session}": Bad data', [
625 'session' => $info->__toString(),
627 $this->store->delete( $key );
628 return $failHandler();
632 if ( !isset( $blob[
'data'] ) || !is_array( $blob[
'data'] ) ||
633 !isset( $blob[
'metadata'] ) || !is_array( $blob[
'metadata'] )
635 $this->logger->warning(
'Session "{session}": Bad data structure', [
636 'session' => $info->__toString(),
638 $this->store->delete( $key );
639 return $failHandler();
642 $data = $blob[
'data'];
643 $metadata = $blob[
'metadata'];
647 if ( !array_key_exists(
'userId', $metadata ) ||
648 !array_key_exists(
'userName', $metadata ) ||
649 !array_key_exists(
'userToken', $metadata ) ||
650 !array_key_exists(
'provider', $metadata )
652 $this->logger->warning(
'Session "{session}": Bad metadata', [
653 'session' => $info->__toString(),
655 $this->store->delete( $key );
656 return $failHandler();
660 $provider = $info->getProvider();
661 if ( $provider ===
null ) {
662 $newParams[
'provider'] = $provider = $this->getProvider( $metadata[
'provider'] );
664 $this->logger->warning(
665 'Session "{session}": Unknown provider ' . $metadata[
'provider'],
667 'session' => $info->__toString(),
670 $this->store->delete( $key );
671 return $failHandler();
673 } elseif ( $metadata[
'provider'] !== (
string)$provider ) {
674 $this->logger->warning(
'Session "{session}": Wrong provider ' .
675 $metadata[
'provider'] .
' !== ' . $provider,
677 'session' => $info->__toString(),
679 return $failHandler();
683 $providerMetadata = $info->getProviderMetadata();
684 if ( isset( $metadata[
'providerMetadata'] ) ) {
685 if ( $providerMetadata ===
null ) {
686 $newParams[
'metadata'] = $metadata[
'providerMetadata'];
689 $newProviderMetadata = $provider->mergeMetadata(
690 $metadata[
'providerMetadata'], $providerMetadata
692 if ( $newProviderMetadata !== $providerMetadata ) {
693 $newParams[
'metadata'] = $newProviderMetadata;
695 }
catch ( MetadataMergeException $ex ) {
696 $this->logger->warning(
697 'Session "{session}": Metadata merge failed: {exception}',
699 'session' => $info->__toString(),
701 ] + $ex->getContext()
703 return $failHandler();
709 $userInfo = $info->getUserInfo();
713 if ( $metadata[
'userId'] ) {
715 } elseif ( $metadata[
'userName'] !==
null ) {
720 }
catch ( \InvalidArgumentException $ex ) {
721 $this->logger->error(
'Session "{session}": {exception}', [
722 'session' => $info->__toString(),
725 return $failHandler();
727 $newParams[
'userInfo'] = $userInfo;
731 if ( $metadata[
'userId'] ) {
732 if ( $metadata[
'userId'] !== $userInfo->getId() ) {
734 $this->logger->warning(
735 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
737 'session' => $info->__toString(),
738 'uid_a' => $metadata[
'userId'],
739 'uid_b' => $userInfo->getId(),
740 'uname_a' => $metadata[
'userName'] ??
'<null>',
741 'uname_b' => $userInfo->getName() ??
'<null>',
743 return $failHandler();
747 if ( $metadata[
'userName'] !==
null &&
748 $userInfo->getName() !== $metadata[
'userName']
750 $this->logger->warning(
751 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
753 'session' => $info->__toString(),
754 'uname_a' => $metadata[
'userName'],
755 'uname_b' => $userInfo->getName(),
757 return $failHandler();
760 } elseif ( $metadata[
'userName'] !==
null ) {
761 if ( $metadata[
'userName'] !== $userInfo->getName() ) {
762 $this->logger->warning(
763 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
765 'session' => $info->__toString(),
766 'uname_a' => $metadata[
'userName'],
767 'uname_b' => $userInfo->getName(),
769 return $failHandler();
771 } elseif ( !$userInfo->isAnon() ) {
775 $this->logger->warning(
776 'Session "{session}": the session store entry is for an anonymous user, '
777 .
'but the session metadata indicates a non-anonynmous user',
779 'session' => $info->__toString(),
781 return $failHandler();
787 if ( $metadata[
'userToken'] !==
null &&
788 $userInfo->getToken() !== $metadata[
'userToken']
790 $this->logger->warning(
'Session "{session}": User token mismatch', [
791 'session' => $info->__toString(),
793 return $failHandler();
795 if ( !$userInfo->isVerified() ) {
796 $newParams[
'userInfo'] = $userInfo->verified();
799 if ( !empty( $metadata[
'remember'] ) && !$info->wasRemembered() ) {
800 $newParams[
'remembered'] =
true;
802 if ( !empty( $metadata[
'forceHTTPS'] ) && !$info->forceHTTPS() ) {
803 $newParams[
'forceHTTPS'] =
true;
805 if ( !empty( $metadata[
'persisted'] ) && !$info->wasPersisted() ) {
806 $newParams[
'persisted'] =
true;
809 if ( !$info->isIdSafe() ) {
810 $newParams[
'idIsSafe'] =
true;
814 if ( $info->getProvider() ===
null ) {
815 $this->logger->warning(
816 'Session "{session}": Null provider and no metadata',
818 'session' => $info->__toString(),
820 return $failHandler();
824 if ( !$info->getUserInfo() ) {
825 if ( $info->getProvider()->canChangeUser() ) {
831 'Session "{session}": No user provided and provider cannot set user',
833 'session' => $info->__toString(),
835 return $failHandler();
837 } elseif ( !$info->getUserInfo()->isVerified() ) {
842 'Session "{session}": Unverified user provided and no metadata to auth it',
844 'session' => $info->__toString(),
846 return $failHandler();
852 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
855 $newParams[
'idIsSafe'] =
true;
861 $newParams[
'copyFrom'] = $info;
862 $info =
new SessionInfo( $info->getPriority(), $newParams );
866 $providerMetadata = $info->getProviderMetadata();
867 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
868 return $failHandler();
870 if ( $providerMetadata !== $info->getProviderMetadata() ) {
871 $info =
new SessionInfo( $info->getPriority(), [
872 'metadata' => $providerMetadata,
880 $reason =
'Hook aborted';
881 if ( !$this->hookRunner->onSessionCheckInfo(
882 $reason, $info, $request, $metadata, $data )
884 $this->logger->warning(
'Session "{session}": ' . $reason, [
885 'session' => $info->__toString(),
887 return $failHandler();
903 if ( defined(
'MW_NO_SESSION' ) ) {
908 $this->logger->error(
'Sessions are supposed to be disabled for this entry point', [
909 'exception' =>
new \BadMethodCallException(
"Sessions are disabled for $ep entry point" ),
912 throw new \BadMethodCallException(
"Sessions are disabled for $ep entry point" );
917 $id = $info->
getId();
919 if ( !isset( $this->allSessionBackends[$id] ) ) {
920 if ( !isset( $this->allSessionIds[$id] ) ) {
921 $this->allSessionIds[$id] =
new SessionId( $id );
924 $this->allSessionIds[$id],
928 $this->hookContainer,
931 $this->allSessionBackends[$id] = $backend;
932 $delay = $backend->delaySave();
934 $backend = $this->allSessionBackends[$id];
935 $delay = $backend->delaySave();
940 $backend->setRememberUser(
true );
945 $session = $backend->getSession( $request );
951 \Wikimedia\ScopedCallback::consume( $delay );
961 $id = $backend->
getId();
962 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
963 $this->allSessionBackends[$id] !== $backend ||
966 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
969 unset( $this->allSessionBackends[$id] );
980 $oldId = (string)$sessionId;
981 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
982 $this->allSessionBackends[$oldId] !== $backend ||
983 $this->allSessionIds[$oldId] !== $sessionId
985 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
988 $newId = $this->generateSessionId();
990 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
991 $sessionId->setId( $newId );
992 $this->allSessionBackends[$newId] = $backend;
993 $this->allSessionIds[$newId] = $sessionId;
1001 $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
1003 $key = $this->store->makeKey(
'MWSession', $id );
1004 $this->store->set( $key,
false, 0, BagOStuff::WRITE_CACHE_ONLY );
1014 $handler->
setManager( $this, $this->store, $this->logger );
1023 if ( !defined(
'MW_PHPUNIT_TEST' ) && !defined(
'MW_PARSER_TEST' ) ) {
1025 throw new LogicException( __METHOD__ .
' may only be called from unit tests!' );
1029 self::$globalSession =
null;
1030 self::$globalSessionRequest =
null;
1035 'id' => $info->
getId(),
1038 'clientip' => $request->
getIP(),
1039 'userAgent' => $request->
getHeader(
'user-agent' ),
1043 $logData[
'user'] = $info->
getUserInfo()->getName();
1045 $logData[
'userVerified'] = $info->
getUserInfo()->isVerified();
1047 $this->logger->info(
'Failed to load session, unpersisting', $logData );
1062 $session = $session ?: self::getGlobalSession();
1065 if ( $suspiciousIpExpiry ===
false
1067 || !$session->isPersistent() || $session->getUser()->isAnon()
1074 $ip = $session->getRequest()->getIP();
1078 if ( $ip ===
'127.0.0.1' || $proxyLookup->isConfiguredProxy( $ip ) ) {
1081 $mwuser = $session->getRequest()->getCookie(
'mwuser-sessionId' );
1082 $now = (int)\
MediaWiki\Utils\MWTimestamp::now( TS_UNIX );
1088 $data = $session->get(
'SessionManager-logPotentialSessionLeakage', [] )
1089 + [
'ip' =>
null,
'mwuser' =>
null,
'timestamp' => 0 ];
1093 ( $now - $data[
'timestamp'] > $suspiciousIpExpiry )
1095 $data[
'ip'] = $data[
'timestamp'] =
null;
1098 if ( $data[
'ip'] !== $ip || $data[
'mwuser'] !== $mwuser ) {
1099 $session->set(
'SessionManager-logPotentialSessionLeakage',
1100 [
'ip' => $ip,
'mwuser' => $mwuser,
'timestamp' => $now ] );
1103 $ipChanged = ( $data[
'ip'] && $data[
'ip'] !== $ip );
1104 $mwuserChanged = ( $data[
'mwuser'] && $data[
'mwuser'] !== $mwuser );
1105 $logLevel = $message =
null;
1113 $logLevel = LogLevel::INFO;
1114 $message =
'IP change within the same session';
1116 'oldIp' => $data[
'ip'],
1117 'oldIpRecorded' => $data[
'timestamp'],
1120 if ( $mwuserChanged ) {
1121 $logLevel = LogLevel::NOTICE;
1122 $message =
'mwuser change within the same session';
1124 'oldMwuser' => $data[
'mwuser'],
1125 'newMwuser' => $mwuser,
1128 if ( $ipChanged && $mwuserChanged ) {
1129 $logLevel = LogLevel::WARNING;
1130 $message =
'IP and mwuser change within the same session';
1134 'session' => $session->getId(),
1135 'user' => $session->getUser()->getName(),
1137 'userAgent' => $session->getRequest()->getHeader(
'user-agent' ),
1139 $logger = \MediaWiki\Logger\LoggerFactory::getInstance(
'session-ip' );
1141 $logger->log( $logLevel, $message, $logData );