36 use Psr\Log\LoggerInterface;
134 if ( self::$instance ===
null ) {
135 self::$instance =
new self();
155 !self::$globalSession
156 || self::$globalSessionRequest !== $request
157 || $id !==
'' && self::$globalSession->getId() !== $id
159 self::$globalSessionRequest = $request;
169 self::$globalSession = $request->getSession();
174 self::$globalSession =
self::singleton()->getSessionById( $id,
true, $request )
175 ?: $request->getSession();
188 if ( isset( $options[
'config'] ) ) {
189 $this->config = $options[
'config'];
190 if ( !$this->config instanceof
Config ) {
191 throw new \InvalidArgumentException(
192 '$options[\'config\'] must be an instance of Config'
199 if ( isset( $options[
'logger'] ) ) {
200 if ( !$options[
'logger'] instanceof LoggerInterface ) {
201 throw new \InvalidArgumentException(
202 '$options[\'logger\'] must be an instance of LoggerInterface'
205 $this->setLogger( $options[
'logger'] );
210 if ( isset( $options[
'hookContainer'] ) ) {
211 $this->setHookContainer( $options[
'hookContainer'] );
216 if ( isset( $options[
'store'] ) ) {
217 if ( !$options[
'store'] instanceof
BagOStuff ) {
218 throw new \InvalidArgumentException(
219 '$options[\'store\'] must be an instance of BagOStuff'
222 $store = $options[
'store'];
227 $this->logger->debug(
'SessionManager using store ' . get_class( $store ) );
229 $this->userNameUtils = MediawikiServices::getInstance()->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->getEmptySession( $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 ) {
286 $session = $this->getEmptySessionInternal( $request, $id );
287 }
catch ( \Exception $ex ) {
288 $this->logger->error(
'Failed to create empty session: {exception}',
290 'method' => __METHOD__,
301 return $this->getEmptySessionInternal( $request );
311 if ( $id !==
null ) {
312 if ( !self::validateSessionId( $id ) ) {
313 throw new \InvalidArgumentException(
'Invalid session ID' );
316 $key = $this->store->makeKey(
'MWSession', $id );
317 if ( is_array( $this->store->get( $key ) ) ) {
318 throw new \InvalidArgumentException(
'Session ID already exists' );
326 foreach ( $this->getProviders() as $provider ) {
327 $info = $provider->newSessionInfo( $id );
331 if ( $info->getProvider() !== $provider ) {
332 throw new \UnexpectedValueException(
333 "$provider returned an empty session info for a different provider: $info"
336 if ( $id !==
null && $info->getId() !== $id ) {
337 throw new \UnexpectedValueException(
338 "$provider returned empty session info with a wrong id: " .
339 $info->getId() .
' != ' . $id
342 if ( !$info->isIdSafe() ) {
343 throw new \UnexpectedValueException(
344 "$provider returned empty session info with id flagged unsafe"
348 if ( $compare > 0 ) {
351 if ( $compare === 0 ) {
359 if ( count( $infos ) > 1 ) {
360 throw new \UnexpectedValueException(
361 'Multiple empty sessions tied for top priority: ' . implode(
', ', $infos )
363 } elseif ( count( $infos ) < 1 ) {
364 throw new \UnexpectedValueException(
'No provider could provide an empty session!' );
368 return $this->getSessionFromInfo( $infos[0], $request );
375 foreach ( $this->getProviders() as $provider ) {
376 $provider->invalidateSessionsForUser( $user );
382 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
386 if ( $this->varyHeaders ===
null ) {
388 foreach ( $this->getProviders() as $provider ) {
389 foreach ( $provider->getVaryHeaders() as
$header => $options ) {
390 # Note that the $options value returned has been deprecated
395 $this->varyHeaders = $headers;
397 return $this->varyHeaders;
402 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
406 if ( $this->varyCookies ===
null ) {
408 foreach ( $this->getProviders() as $provider ) {
409 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
411 $this->varyCookies = array_values( array_unique( $cookies ) );
413 return $this->varyCookies;
422 return is_string( $id ) && preg_match(
'/^[a-zA-Z0-9_-]{32,}$/', $id );
439 $this->preventUsers[$username] =
true;
442 foreach ( $this->getProviders() as $provider ) {
443 $provider->preventSessionsForUser( $username );
454 return !empty( $this->preventUsers[$username] );
462 if ( $this->sessionProviders ===
null ) {
463 $this->sessionProviders = [];
467 $provider = $objectFactory->createObject( $spec );
472 $this->hookContainer,
475 if ( isset( $this->sessionProviders[(
string)$provider] ) ) {
477 throw new \UnexpectedValueException(
"Duplicate provider name \"$provider\"" );
479 $this->sessionProviders[(string)$provider] = $provider;
482 return $this->sessionProviders;
496 $providers = $this->getProviders();
497 return $providers[$name] ??
null;
505 if ( $this->allSessionBackends ) {
506 $this->logger->debug(
'Saving all sessions on shutdown' );
507 if ( session_id() !==
'' ) {
509 session_write_close();
512 foreach ( $this->allSessionBackends as $backend ) {
513 $backend->shutdown();
526 foreach ( $this->getProviders() as $provider ) {
527 $info = $provider->provideSessionInfo( $request );
531 if ( $info->getProvider() !== $provider ) {
532 throw new \UnexpectedValueException(
533 "$provider returned session info for a different provider: $info"
542 usort( $infos, [ SessionInfo::class,
'compare' ] );
545 $info = array_pop( $infos );
546 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
550 $info = array_pop( $infos );
555 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
561 $this->logUnpersist( $info, $request );
562 $info->getProvider()->unpersistSession( $request );
567 $this->logUnpersist( $info, $request );
568 $info->getProvider()->unpersistSession( $request );
572 if ( count( $retInfos ) > 1 ) {
575 'Multiple sessions for this request tied for top priority: ' . implode(
', ', $retInfos )
579 return $retInfos ? $retInfos[0] :
null;
590 $key = $this->store->makeKey(
'MWSession', $info->
getId() );
591 $blob = $this->store->get( $key );
597 $failHandler =
function () use ( $key, &$info, $request ) {
598 $this->store->delete( $key );
599 return $this->loadSessionInfoFromStore( $info, $request );
602 $failHandler =
static function () {
609 if (
$blob !==
false ) {
611 if ( !is_array(
$blob ) ) {
612 $this->logger->warning(
'Session "{session}": Bad data', [
615 $this->store->delete( $key );
616 return $failHandler();
620 if ( !isset(
$blob[
'data'] ) || !is_array(
$blob[
'data'] ) ||
621 !isset(
$blob[
'metadata'] ) || !is_array(
$blob[
'metadata'] )
623 $this->logger->warning(
'Session "{session}": Bad data structure', [
626 $this->store->delete( $key );
627 return $failHandler();
630 $data =
$blob[
'data'];
631 $metadata =
$blob[
'metadata'];
635 if ( !array_key_exists(
'userId', $metadata ) ||
636 !array_key_exists(
'userName', $metadata ) ||
637 !array_key_exists(
'userToken', $metadata ) ||
638 !array_key_exists(
'provider', $metadata )
640 $this->logger->warning(
'Session "{session}": Bad metadata', [
643 $this->store->delete( $key );
644 return $failHandler();
649 if ( $provider ===
null ) {
650 $newParams[
'provider'] = $provider = $this->getProvider( $metadata[
'provider'] );
652 $this->logger->warning(
653 'Session "{session}": Unknown provider ' . $metadata[
'provider'],
658 $this->store->delete( $key );
659 return $failHandler();
661 } elseif ( $metadata[
'provider'] !== (
string)$provider ) {
662 $this->logger->warning(
'Session "{session}": Wrong provider ' .
663 $metadata[
'provider'] .
' !== ' . $provider,
667 return $failHandler();
672 if ( isset( $metadata[
'providerMetadata'] ) ) {
673 if ( $providerMetadata ===
null ) {
674 $newParams[
'metadata'] = $metadata[
'providerMetadata'];
677 $newProviderMetadata = $provider->mergeMetadata(
678 $metadata[
'providerMetadata'], $providerMetadata
680 if ( $newProviderMetadata !== $providerMetadata ) {
681 $newParams[
'metadata'] = $newProviderMetadata;
684 $this->logger->warning(
685 'Session "{session}": Metadata merge failed: {exception}',
691 return $failHandler();
701 if ( $metadata[
'userId'] ) {
703 } elseif ( $metadata[
'userName'] !==
null ) {
708 }
catch ( \InvalidArgumentException $ex ) {
709 $this->logger->error(
'Session "{session}": {exception}', [
713 return $failHandler();
715 $newParams[
'userInfo'] = $userInfo;
719 if ( $metadata[
'userId'] ) {
720 if ( $metadata[
'userId'] !== $userInfo->getId() ) {
721 $this->logger->warning(
722 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
725 'uid_a' => $metadata[
'userId'],
726 'uid_b' => $userInfo->getId(),
728 return $failHandler();
732 if ( $metadata[
'userName'] !==
null &&
733 $userInfo->getName() !== $metadata[
'userName']
735 $this->logger->warning(
736 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
739 'uname_a' => $metadata[
'userName'],
740 'uname_b' => $userInfo->getName(),
742 return $failHandler();
745 } elseif ( $metadata[
'userName'] !==
null ) {
746 if ( $metadata[
'userName'] !== $userInfo->getName() ) {
747 $this->logger->warning(
748 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
751 'uname_a' => $metadata[
'userName'],
752 'uname_b' => $userInfo->getName(),
754 return $failHandler();
756 } elseif ( !$userInfo->isAnon() ) {
759 $this->logger->warning(
760 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
764 return $failHandler();
769 if ( $metadata[
'userToken'] !==
null &&
770 $userInfo->getToken() !== $metadata[
'userToken']
772 $this->logger->warning(
'Session "{session}": User token mismatch', [
775 return $failHandler();
777 if ( !$userInfo->isVerified() ) {
778 $newParams[
'userInfo'] = $userInfo->verified();
781 if ( !empty( $metadata[
'remember'] ) && !$info->
wasRemembered() ) {
782 $newParams[
'remembered'] =
true;
784 if ( !empty( $metadata[
'forceHTTPS'] ) && !$info->
forceHTTPS() ) {
785 $newParams[
'forceHTTPS'] =
true;
787 if ( !empty( $metadata[
'persisted'] ) && !$info->
wasPersisted() ) {
788 $newParams[
'persisted'] =
true;
792 $newParams[
'idIsSafe'] =
true;
797 $this->logger->warning(
798 'Session "{session}": Null provider and no metadata',
802 return $failHandler();
811 'Session "{session}": No user provided and provider cannot set user',
815 return $failHandler();
820 'Session "{session}": Unverified user provided and no metadata to auth it',
824 return $failHandler();
833 $newParams[
'idIsSafe'] =
true;
839 $newParams[
'copyFrom'] = $info;
845 if ( !$info->
getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
846 return $failHandler();
850 'metadata' => $providerMetadata,
858 $reason =
'Hook aborted';
859 if ( !$this->hookRunner->onSessionCheckInfo(
860 $reason, $info, $request, $metadata, $data )
862 $this->logger->warning(
'Session "{session}": ' . $reason, [
865 return $failHandler();
881 if ( defined(
'MW_NO_SESSION' ) ) {
886 $this->logger->error(
'Sessions are supposed to be disabled for this entry point', [
887 'exception' =>
new \BadMethodCallException(
"Sessions are disabled for $ep entry point" ),
890 throw new \BadMethodCallException(
"Sessions are disabled for $ep entry point" );
895 $id = $info->
getId();
897 if ( !isset( $this->allSessionBackends[$id] ) ) {
898 if ( !isset( $this->allSessionIds[$id] ) ) {
899 $this->allSessionIds[$id] =
new SessionId( $id );
902 $this->allSessionIds[$id],
906 $this->hookContainer,
909 $this->allSessionBackends[$id] = $backend;
910 $delay = $backend->delaySave();
912 $backend = $this->allSessionBackends[$id];
913 $delay = $backend->delaySave();
918 $backend->setRememberUser(
true );
923 $session = $backend->getSession( $request );
929 \Wikimedia\ScopedCallback::consume( $delay );
939 $id = $backend->
getId();
940 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
941 $this->allSessionBackends[$id] !== $backend ||
944 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
947 unset( $this->allSessionBackends[$id] );
958 $oldId = (string)$sessionId;
959 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
960 $this->allSessionBackends[$oldId] !== $backend ||
961 $this->allSessionIds[$oldId] !== $sessionId
963 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
966 $newId = $this->generateSessionId();
968 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
969 $sessionId->setId( $newId );
970 $this->allSessionBackends[$newId] = $backend;
971 $this->allSessionIds[$newId] = $sessionId;
981 $key = $this->store->makeKey(
'MWSession', $id );
982 }
while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
992 $handler->
setManager( $this, $this->store, $this->logger );
1001 if ( !defined(
'MW_PHPUNIT_TEST' ) && !defined(
'MW_PARSER_TEST' ) ) {
1003 throw new MWException( __METHOD__ .
' may only be called from unit tests!' );
1007 self::$globalSession =
null;
1008 self::$globalSessionRequest =
null;
1013 'id' => $info->
getId(),
1016 'clientip' => $request->
getIP(),
1017 'userAgent' => $request->
getHeader(
'user-agent' ),
1021 $logData[
'user'] = $info->
getUserInfo()->getName();
1023 $logData[
'userVerified'] = $info->
getUserInfo()->isVerified();
1025 $this->logger->info(
'Failed to load session, unpersisting', $logData );
1040 $session = $session ?: self::getGlobalSession();
1043 if ( $suspiciousIpExpiry ===
false
1045 || !$session->isPersistent() || $session->getUser()->isAnon()
1052 $ip = $session->getRequest()->getIP();
1056 if ( $ip ===
'127.0.0.1' || $proxyLookup->isConfiguredProxy( $ip ) ) {
1059 $mwuser = $session->getRequest()->getCookie(
'mwuser-sessionId' );
1060 $now = (int)\MWTimestamp::now( TS_UNIX );
1066 $data = $session->get(
'SessionManager-logPotentialSessionLeakage', [] )
1067 + [
'ip' =>
null,
'mwuser' =>
null,
'timestamp' => 0 ];
1071 ( $now - $data[
'timestamp'] > $suspiciousIpExpiry )
1073 $data[
'ip'] = $data[
'timestamp'] =
null;
1076 if ( $data[
'ip'] !== $ip || $data[
'mwuser'] !== $mwuser ) {
1077 $session->set(
'SessionManager-logPotentialSessionLeakage',
1078 [
'ip' => $ip,
'mwuser' => $mwuser,
'timestamp' => $now ] );
1081 $ipChanged = ( $data[
'ip'] && $data[
'ip'] !== $ip );
1082 $mwuserChanged = ( $data[
'mwuser'] && $data[
'mwuser'] !== $mwuser );
1083 $logLevel = $message =
null;
1091 $logLevel = LogLevel::INFO;
1092 $message =
'IP change within the same session';
1094 'oldIp' => $data[
'ip'],
1095 'oldIpRecorded' => $data[
'timestamp'],
1098 if ( $mwuserChanged ) {
1099 $logLevel = LogLevel::NOTICE;
1100 $message =
'mwuser change within the same session';
1102 'oldMwuser' => $data[
'mwuser'],
1103 'newMwuser' => $mwuser,
1106 if ( $ipChanged && $mwuserChanged ) {
1107 $logLevel = LogLevel::WARNING;
1108 $message =
'IP and mwuser change within the same session';
1112 'session' => $session->getId(),
1113 'user' => $session->getUser()->getName(),
1115 'userAgent' => $session->getRequest()->getHeader(
'user-agent' ),
1119 $logger->log( $logLevel, $message, $logData );
if(!defined('MW_SETUP_CALLBACK'))
The persistent session ID (if any) loaded at startup.
Class representing a cache/ephemeral data store.
Wrapper around a BagOStuff that caches data in memory.
WebRequest clone which takes values from a provided array.
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
A class containing constants representing the names of configuration variables.
const SuspiciousIpExpiry
Name constant for the SuspiciousIpExpiry setting, for use with Config::get()
const SessionCacheType
Name constant for the SessionCacheType setting, for use with Config::get()
const SessionProviders
Name constant for the SessionProviders setting, for use with Config::get()
const ObjectCacheSessionExpiry
Name constant for the ObjectCacheSessionExpiry setting, for use with Config::get()
static getInstance( $id)
Get a cached instance of the specified type of cache object.
static getMain()
Get the RequestContext object associated with the main request.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
saveSettings()
Save this user's settings into the database.
setToken( $token=false)
Set the random token (used for persistent authentication) Called from loadDefaults() among other plac...
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
getIP()
Work out the IP address based on various globals For trusted proxies, use the XFF client IP (first of...
setSessionId(SessionId $sessionId)
Set the session for this request.
getHeader( $name, $flags=0)
Get a request header, or false if it isn't set.
Interface for configuration instances.