28 use Psr\Log\LoggerInterface;
35 use Wikimedia\ObjectFactory;
93 if ( self::$instance ===
null ) {
94 self::$instance =
new self();
116 !self::$globalSession
117 || self::$globalSessionRequest !==
$request
118 || $id !==
'' && self::$globalSession->getId() !== $id
120 self::$globalSessionRequest =
$request;
130 self::$globalSession =
$request->getSession();
149 if ( isset(
$options[
'config'] ) ) {
151 if ( !$this->config instanceof
Config ) {
152 throw new \InvalidArgumentException(
153 '$options[\'config\'] must be an instance of Config'
160 if ( isset(
$options[
'logger'] ) ) {
161 if ( !
$options[
'logger'] instanceof LoggerInterface ) {
162 throw new \InvalidArgumentException(
163 '$options[\'logger\'] must be an instance of LoggerInterface'
173 throw new \InvalidArgumentException(
174 '$options[\'store\'] must be an instance of BagOStuff'
183 register_shutdown_function( [ $this,
'shutdown' ] );
202 if ( !self::validateSessionId( $id ) ) {
203 throw new \InvalidArgumentException(
'Invalid session ID' );
213 if ( isset( $this->allSessionBackends[$id] ) ) {
218 $key = $this->store->makeKey(
'MWSession', $id );
219 if ( is_array( $this->store->get( $key ) ) ) {
226 if ( $create && $session ===
null ) {
230 }
catch ( \Exception $ex ) {
231 $this->logger->error(
'Failed to create empty session: {exception}',
233 'method' => __METHOD__,
254 if ( $id !==
null ) {
255 if ( !self::validateSessionId( $id ) ) {
256 throw new \InvalidArgumentException(
'Invalid session ID' );
259 $key = $this->store->makeKey(
'MWSession', $id );
260 if ( is_array( $this->store->get( $key ) ) ) {
261 throw new \InvalidArgumentException(
'Session ID already exists' );
270 $info = $provider->newSessionInfo( $id );
274 if ( $info->getProvider() !== $provider ) {
275 throw new \UnexpectedValueException(
276 "$provider returned an empty session info for a different provider: $info"
279 if ( $id !==
null && $info->getId() !== $id ) {
280 throw new \UnexpectedValueException(
281 "$provider returned empty session info with a wrong id: " .
282 $info->getId() .
' != ' . $id
285 if ( !$info->isIdSafe() ) {
286 throw new \UnexpectedValueException(
287 "$provider returned empty session info with id flagged unsafe"
291 if ( $compare > 0 ) {
294 if ( $compare === 0 ) {
302 if (
count( $infos ) > 1 ) {
303 throw new \UnexpectedValueException(
304 'Multiple empty sessions tied for top priority: ' . implode(
', ', $infos )
306 } elseif (
count( $infos ) < 1 ) {
307 throw new \UnexpectedValueException(
'No provider could provide an empty session!' );
315 $user->saveSettings();
318 $provider->invalidateSessionsForUser(
$user );
324 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
328 if ( $this->varyHeaders ===
null ) {
332 if ( !isset( $headers[
$header] ) ) {
340 $this->varyHeaders = $headers;
347 if ( defined(
'MW_NO_SESSION' ) &&
MW_NO_SESSION !==
'warn' ) {
351 if ( $this->varyCookies ===
null ) {
354 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
356 $this->varyCookies = array_values( array_unique( $cookies ) );
367 return is_string( $id ) && preg_match(
'/^[a-zA-Z0-9_-]{32,}$/', $id );
389 $provider->preventSessionsForUser(
$username );
400 return !empty( $this->preventUsers[
$username] );
408 if ( $this->sessionProviders ===
null ) {
409 $this->sessionProviders = [];
410 foreach ( $this->config->get(
'SessionProviders' )
as $spec ) {
411 $provider = ObjectFactory::getObjectFromSpec( $spec );
412 $provider->setLogger( $this->logger );
413 $provider->setConfig( $this->config );
414 $provider->setManager( $this );
415 if ( isset( $this->sessionProviders[(
string)$provider] ) ) {
416 throw new \UnexpectedValueException(
"Duplicate provider name \"$provider\"" );
418 $this->sessionProviders[(
string)$provider] = $provider;
436 return $providers[
$name] ??
null;
444 if ( $this->allSessionBackends ) {
445 $this->logger->debug(
'Saving all sessions on shutdown' );
446 if ( session_id() !==
'' ) {
448 session_write_close();
451 foreach ( $this->allSessionBackends
as $backend ) {
452 $backend->shutdown();
466 $info = $provider->provideSessionInfo(
$request );
470 if ( $info->getProvider() !== $provider ) {
471 throw new \UnexpectedValueException(
472 "$provider returned session info for a different provider: $info"
481 usort( $infos,
'MediaWiki\\Session\\SessionInfo::compare' );
484 $info = array_pop( $infos );
488 $info = array_pop( $infos );
499 $info->getProvider()->unpersistSession(
$request );
504 $info->getProvider()->unpersistSession(
$request );
508 if (
count( $retInfos ) > 1 ) {
509 $ex = new \OverflowException(
510 'Multiple sessions for this request tied for top priority: ' . implode(
', ', $retInfos )
512 $ex->sessionInfos = $retInfos;
516 return $retInfos ? $retInfos[0] :
null;
527 $key = $this->store->makeKey(
'MWSession', $info->
getId() );
528 $blob = $this->store->get( $key );
534 $failHandler =
function ()
use ( $key, &$info,
$request ) {
535 $this->store->delete( $key );
539 $failHandler =
function () {
546 if (
$blob !==
false ) {
548 if ( !is_array(
$blob ) ) {
549 $this->logger->warning(
'Session "{session}": Bad data', [
552 $this->store->delete( $key );
553 return $failHandler();
557 if ( !isset(
$blob[
'data'] ) || !is_array(
$blob[
'data'] ) ||
558 !isset(
$blob[
'metadata'] ) || !is_array(
$blob[
'metadata'] )
560 $this->logger->warning(
'Session "{session}": Bad data structure', [
563 $this->store->delete( $key );
564 return $failHandler();
568 $metadata =
$blob[
'metadata'];
572 if ( !array_key_exists(
'userId', $metadata ) ||
573 !array_key_exists(
'userName', $metadata ) ||
574 !array_key_exists(
'userToken', $metadata ) ||
575 !array_key_exists(
'provider', $metadata )
577 $this->logger->warning(
'Session "{session}": Bad metadata', [
580 $this->store->delete( $key );
581 return $failHandler();
586 if ( $provider ===
null ) {
587 $newParams[
'provider'] = $provider = $this->
getProvider( $metadata[
'provider'] );
589 $this->logger->warning(
590 'Session "{session}": Unknown provider ' . $metadata[
'provider'],
595 $this->store->delete( $key );
596 return $failHandler();
598 } elseif ( $metadata[
'provider'] !== (
string)$provider ) {
599 $this->logger->warning(
'Session "{session}": Wrong provider ' .
600 $metadata[
'provider'] .
' !== ' . $provider,
604 return $failHandler();
609 if ( isset( $metadata[
'providerMetadata'] ) ) {
610 if ( $providerMetadata ===
null ) {
611 $newParams[
'metadata'] = $metadata[
'providerMetadata'];
614 $newProviderMetadata = $provider->mergeMetadata(
615 $metadata[
'providerMetadata'], $providerMetadata
617 if ( $newProviderMetadata !== $providerMetadata ) {
618 $newParams[
'metadata'] = $newProviderMetadata;
621 $this->logger->warning(
622 'Session "{session}": Metadata merge failed: {exception}',
628 return $failHandler();
638 if ( $metadata[
'userId'] ) {
640 } elseif ( $metadata[
'userName'] !==
null ) {
645 }
catch ( \InvalidArgumentException $ex ) {
646 $this->logger->error(
'Session "{session}": {exception}', [
650 return $failHandler();
652 $newParams[
'userInfo'] = $userInfo;
656 if ( $metadata[
'userId'] ) {
657 if ( $metadata[
'userId'] !== $userInfo->getId() ) {
658 $this->logger->warning(
659 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
662 'uid_a' => $metadata[
'userId'],
663 'uid_b' => $userInfo->
getId(),
665 return $failHandler();
669 if ( $metadata[
'userName'] !==
null &&
670 $userInfo->getName() !== $metadata[
'userName']
672 $this->logger->warning(
673 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
676 'uname_a' => $metadata[
'userName'],
677 'uname_b' => $userInfo->getName(),
679 return $failHandler();
682 } elseif ( $metadata[
'userName'] !==
null ) {
683 if ( $metadata[
'userName'] !== $userInfo->getName() ) {
684 $this->logger->warning(
685 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
688 'uname_a' => $metadata[
'userName'],
689 'uname_b' => $userInfo->getName(),
691 return $failHandler();
693 } elseif ( !$userInfo->isAnon() ) {
696 $this->logger->warning(
697 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
701 return $failHandler();
706 if ( $metadata[
'userToken'] !==
null &&
707 $userInfo->getToken() !== $metadata[
'userToken']
709 $this->logger->warning(
'Session "{session}": User token mismatch', [
712 return $failHandler();
714 if ( !$userInfo->isVerified() ) {
715 $newParams[
'userInfo'] = $userInfo->verified();
718 if ( !empty( $metadata[
'remember'] ) && !$info->
wasRemembered() ) {
719 $newParams[
'remembered'] =
true;
721 if ( !empty( $metadata[
'forceHTTPS'] ) && !$info->
forceHTTPS() ) {
722 $newParams[
'forceHTTPS'] =
true;
724 if ( !empty( $metadata[
'persisted'] ) && !$info->
wasPersisted() ) {
725 $newParams[
'persisted'] =
true;
729 $newParams[
'idIsSafe'] =
true;
734 $this->logger->warning(
735 'Session "{session}": Null provider and no metadata',
739 return $failHandler();
748 'Session "{session}": No user provided and provider cannot set user',
752 return $failHandler();
757 'Session "{session}": Unverified user provided and no metadata to auth it',
761 return $failHandler();
770 $newParams[
'idIsSafe'] =
true;
776 $newParams[
'copyFrom'] = $info;
783 return $failHandler();
787 'metadata' => $providerMetadata,
795 $reason =
'Hook aborted';
800 $this->logger->warning(
'Session "{session}": ' . $reason, [
803 return $failHandler();
819 if ( defined(
'MW_NO_SESSION' ) ) {
822 $this->logger->error(
'Sessions are supposed to be disabled for this entry point', [
823 'exception' =>
new \BadMethodCallException(
'Sessions are disabled for this entry point' ),
826 throw new \BadMethodCallException(
'Sessions are disabled for this entry point' );
831 $id = $info->
getId();
833 if ( !isset( $this->allSessionBackends[$id] ) ) {
834 if ( !isset( $this->allSessionIds[$id] ) ) {
835 $this->allSessionIds[$id] =
new SessionId( $id );
838 $this->allSessionIds[$id],
842 $this->config->get(
'ObjectCacheSessionExpiry' )
844 $this->allSessionBackends[$id] = $backend;
847 $backend = $this->allSessionBackends[$id];
848 $delay = $backend->delaySave();
853 $backend->setRememberUser(
true );
857 $request->setSessionId( $backend->getSessionId() );
858 $session = $backend->getSession(
$request );
864 \Wikimedia\ScopedCallback::consume( $delay );
874 $id = $backend->
getId();
875 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
876 $this->allSessionBackends[$id] !== $backend ||
879 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
882 unset( $this->allSessionBackends[$id] );
893 $oldId = (
string)$sessionId;
894 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
895 $this->allSessionBackends[$oldId] !== $backend ||
896 $this->allSessionIds[$oldId] !== $sessionId
898 throw new \InvalidArgumentException(
'Backend was not registered with this SessionManager' );
903 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
904 $sessionId->setId( $newId );
905 $this->allSessionBackends[$newId] = $backend;
906 $this->allSessionIds[$newId] = $sessionId;
916 $key = $this->store->makeKey(
'MWSession', $id );
917 }
while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
927 $handler->setManager( $this, $this->store, $this->logger );
935 if ( !defined(
'MW_PHPUNIT_TEST' ) ) {
937 throw new MWException( __METHOD__ .
' may only be called from unit tests!' );
941 self::$globalSession =
null;
942 self::$globalSessionRequest =
null;