Merge "ResourceLoader: Deprecate ResourceLoader::makeConfigSetScript"
[mediawiki.git] / includes / session / SessionManager.php
blob63bd6362d518403ed8be6ed2b05ecd206681b7db
1 <?php
2 /**
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
20 * @file
21 * @ingroup Session
24 namespace MediaWiki\Session;
26 use InvalidArgumentException;
27 use LogicException;
28 use MediaWiki\Config\Config;
29 use MediaWiki\Context\RequestContext;
30 use MediaWiki\HookContainer\HookContainer;
31 use MediaWiki\HookContainer\HookRunner;
32 use MediaWiki\MainConfigNames;
33 use MediaWiki\MediaWikiServices;
34 use MediaWiki\Request\FauxRequest;
35 use MediaWiki\Request\WebRequest;
36 use MediaWiki\User\User;
37 use MediaWiki\User\UserNameUtils;
38 use MWException;
39 use Psr\Log\LoggerInterface;
40 use Psr\Log\LogLevel;
41 use Wikimedia\ObjectCache\BagOStuff;
42 use Wikimedia\ObjectCache\CachedBagOStuff;
44 /**
45 * This serves as the entry point to the MediaWiki session handling system.
47 * Most methods here are for internal use by session handling code. Other callers
48 * should only use getGlobalSession and the methods of SessionManagerInterface;
49 * the rest of the functionality is exposed via MediaWiki\Session\Session methods.
51 * To provide custom session handling, implement a MediaWiki\Session\SessionProvider.
53 * @anchor SessionManager-storage-expectations
55 * ## Storage expectations
57 * The SessionManager should be configured with a very fast storage system that is
58 * optimized for holding key-value pairs. It expects:
60 * - Low latencies. Session data is read or written to during nearly all web requests from
61 * people that have contributed to or otherwise engaged with the site, including those not
62 * logged in with a registered account.
64 * - Locally writable data. The data must be writable from both primary and secondary
65 * data centres.
67 * - Locally latest reads. Writes must by default be immediately consistent within
68 * the local data centre, and visible to other reads from web servers in that data centre.
70 * - Replication. The data must be eventually consistent across all data centres. Writes
71 * are either synced to all remote data centres, or locally overwritten by another write
72 * that is.
74 * The SessionManager uses `set()` and `delete()` for write operations, which should be
75 * synchronous in the local data centre, and replicate asynchronously to any others.
77 * @ingroup Session
78 * @since 1.27
79 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
81 class SessionManager implements SessionManagerInterface {
82 private static ?SessionManager $instance = null;
83 private static ?Session $globalSession = null;
84 private static ?WebRequest $globalSessionRequest = null;
86 private LoggerInterface $logger;
87 private HookContainer $hookContainer;
88 private HookRunner $hookRunner;
89 private Config $config;
90 private UserNameUtils $userNameUtils;
92 /** @var CachedBagOStuff|null */
93 private $store;
95 /** @var SessionProvider[] */
96 private $sessionProviders = null;
98 /** @var string[] */
99 private $varyCookies = null;
101 /** @var array */
102 private $varyHeaders = null;
104 /** @var SessionBackend[] */
105 private $allSessionBackends = [];
107 /** @var SessionId[] */
108 private $allSessionIds = [];
110 /** @var true[] */
111 private $preventUsers = [];
114 * Get the global SessionManager
115 * @return self
117 public static function singleton() {
118 if ( self::$instance === null ) {
119 self::$instance = new self();
121 return self::$instance;
125 * If PHP's session_id() has been set, returns that session. Otherwise
126 * returns the session for RequestContext::getMain()->getRequest().
128 * @return Session
130 public static function getGlobalSession(): Session {
131 if ( !PHPSessionHandler::isEnabled() ) {
132 $id = '';
133 } else {
134 $id = session_id();
137 $request = RequestContext::getMain()->getRequest();
138 if (
139 !self::$globalSession // No global session is set up yet
140 || self::$globalSessionRequest !== $request // The global WebRequest changed
141 || ( $id !== '' && self::$globalSession->getId() !== $id ) // Someone messed with session_id()
143 self::$globalSessionRequest = $request;
144 if ( $id === '' ) {
145 // session_id() wasn't used, so fetch the Session from the WebRequest.
146 // We use $request->getSession() instead of $singleton->getSessionForRequest()
147 // because doing the latter would require a public
148 // "$request->getSessionId()" method that would confuse end
149 // users by returning SessionId|null where they'd expect it to
150 // be short for $request->getSession()->getId(), and would
151 // wind up being a duplicate of the code in
152 // $request->getSession() anyway.
153 self::$globalSession = $request->getSession();
154 } else {
155 // Someone used session_id(), so we need to follow suit.
156 // Note this overwrites whatever session might already be
157 // associated with $request with the one for $id.
158 self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
159 ?: $request->getSession();
162 return self::$globalSession;
166 * @param array $options
167 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
168 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
169 * - store: BagOStuff to store session data in.
171 public function __construct( $options = [] ) {
172 $services = MediaWikiServices::getInstance();
173 if ( isset( $options['config'] ) ) {
174 if ( !$options['config'] instanceof Config ) {
175 throw new InvalidArgumentException(
176 '$options[\'config\'] must be an instance of Config'
179 $this->config = $options['config'];
180 } else {
181 $this->config = $services->getMainConfig();
184 if ( isset( $options['logger'] ) ) {
185 if ( !$options['logger'] instanceof LoggerInterface ) {
186 throw new InvalidArgumentException(
187 '$options[\'logger\'] must be an instance of LoggerInterface'
190 $this->setLogger( $options['logger'] );
191 } else {
192 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
195 if ( isset( $options['hookContainer'] ) ) {
196 $this->setHookContainer( $options['hookContainer'] );
197 } else {
198 $this->setHookContainer( $services->getHookContainer() );
201 if ( isset( $options['store'] ) ) {
202 if ( !$options['store'] instanceof BagOStuff ) {
203 throw new InvalidArgumentException(
204 '$options[\'store\'] must be an instance of BagOStuff'
207 $store = $options['store'];
208 } else {
209 $store = $services->getObjectCacheFactory()
210 ->getInstance( $this->config->get( MainConfigNames::SessionCacheType ) );
213 $this->logger->debug( 'SessionManager using store ' . get_class( $store ) );
214 $this->store = $store instanceof CachedBagOStuff ? $store : new CachedBagOStuff( $store );
215 $this->userNameUtils = $services->getUserNameUtils();
217 register_shutdown_function( [ $this, 'shutdown' ] );
220 public function setLogger( LoggerInterface $logger ) {
221 $this->logger = $logger;
225 * @internal
226 * @param HookContainer $hookContainer
228 public function setHookContainer( HookContainer $hookContainer ) {
229 $this->hookContainer = $hookContainer;
230 $this->hookRunner = new HookRunner( $hookContainer );
233 public function getSessionForRequest( WebRequest $request ) {
234 $info = $this->getSessionInfoForRequest( $request );
236 if ( !$info ) {
237 $session = $this->getInitialSession( $request );
238 } else {
239 $session = $this->getSessionFromInfo( $info, $request );
241 return $session;
244 public function getSessionById( $id, $create = false, ?WebRequest $request = null ) {
245 if ( !self::validateSessionId( $id ) ) {
246 throw new InvalidArgumentException( 'Invalid session ID' );
248 if ( !$request ) {
249 $request = new FauxRequest;
252 $session = null;
253 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [ 'id' => $id, 'idIsSafe' => true ] );
255 // If we already have the backend loaded, use it directly
256 if ( isset( $this->allSessionBackends[$id] ) ) {
257 return $this->getSessionFromInfo( $info, $request );
260 // Test if the session is in storage, and if so try to load it.
261 $key = $this->store->makeKey( 'MWSession', $id );
262 if ( is_array( $this->store->get( $key ) ) ) {
263 $create = false; // If loading fails, don't bother creating because it probably will fail too.
264 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
265 $session = $this->getSessionFromInfo( $info, $request );
269 if ( $create && $session === null ) {
270 try {
271 $session = $this->getEmptySessionInternal( $request, $id );
272 } catch ( \Exception $ex ) {
273 $this->logger->error( 'Failed to create empty session: {exception}',
275 'method' => __METHOD__,
276 'exception' => $ex,
277 ] );
278 $session = null;
282 return $session;
285 public function getEmptySession( ?WebRequest $request = null ) {
286 return $this->getEmptySessionInternal( $request );
290 * @see SessionManagerInterface::getEmptySession
291 * @param WebRequest|null $request
292 * @param string|null $id ID to force on the new session
293 * @return Session
295 private function getEmptySessionInternal( ?WebRequest $request = null, $id = null ) {
296 if ( $id !== null ) {
297 if ( !self::validateSessionId( $id ) ) {
298 throw new InvalidArgumentException( 'Invalid session ID' );
301 $key = $this->store->makeKey( 'MWSession', $id );
302 if ( is_array( $this->store->get( $key ) ) ) {
303 throw new InvalidArgumentException( 'Session ID already exists' );
306 if ( !$request ) {
307 $request = new FauxRequest;
310 $infos = [];
311 foreach ( $this->getProviders() as $provider ) {
312 $info = $provider->newSessionInfo( $id );
313 if ( !$info ) {
314 continue;
316 if ( $info->getProvider() !== $provider ) {
317 throw new \UnexpectedValueException(
318 "$provider returned an empty session info for a different provider: $info"
321 if ( $id !== null && $info->getId() !== $id ) {
322 throw new \UnexpectedValueException(
323 "$provider returned empty session info with a wrong id: " .
324 $info->getId() . ' != ' . $id
327 if ( !$info->isIdSafe() ) {
328 throw new \UnexpectedValueException(
329 "$provider returned empty session info with id flagged unsafe"
332 $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
333 if ( $compare > 0 ) {
334 continue;
336 if ( $compare === 0 ) {
337 $infos[] = $info;
338 } else {
339 $infos = [ $info ];
343 // Make sure there's exactly one
344 if ( count( $infos ) > 1 ) {
345 throw new \UnexpectedValueException(
346 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
348 } elseif ( count( $infos ) < 1 ) {
349 throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
352 // @phan-suppress-next-line PhanTypePossiblyInvalidDimOffset False positive
353 return $this->getSessionFromInfo( $infos[0], $request );
357 * Create a new session. Populate it with a default secret token, to avoid
358 * a session replication race on a subsequent edit/save cycle (e.g. in
359 * a multi-dc setup, ref https://phabricator.wikimedia.org/T279664#8139533).
361 * @param WebRequest|null $request Corresponding request. Any existing
362 * session associated with this WebRequest object will be overwritten.
363 * @return Session
365 private function getInitialSession( ?WebRequest $request = null ) {
366 $session = $this->getEmptySession( $request );
367 $session->getToken();
368 return $session;
371 public function invalidateSessionsForUser( User $user ) {
372 $user->setToken();
373 $user->saveSettings();
375 foreach ( $this->getProviders() as $provider ) {
376 $provider->invalidateSessionsForUser( $user );
381 * @return array<string,null>
383 public function getVaryHeaders() {
384 // @codeCoverageIgnoreStart
385 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
386 return [];
388 // @codeCoverageIgnoreEnd
389 if ( $this->varyHeaders === null ) {
390 $headers = [];
391 foreach ( $this->getProviders() as $provider ) {
392 foreach ( $provider->getVaryHeaders() as $header => $_ ) {
393 $headers[$header] = null;
396 $this->varyHeaders = $headers;
398 return $this->varyHeaders;
401 public function getVaryCookies() {
402 // @codeCoverageIgnoreStart
403 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
404 return [];
406 // @codeCoverageIgnoreEnd
407 if ( $this->varyCookies === null ) {
408 $cookies = [];
409 foreach ( $this->getProviders() as $provider ) {
410 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
412 $this->varyCookies = array_values( array_unique( $cookies ) );
414 return $this->varyCookies;
418 * Validate a session ID
419 * @param string $id
420 * @return bool
422 public static function validateSessionId( $id ) {
423 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
426 /***************************************************************************/
427 // region Internal methods
428 /** @name Internal methods */
431 * Prevent future sessions for the user
433 * The intention is that the named account will never again be usable for
434 * normal login (i.e. there is no way to undo the prevention of access).
436 * @internal For use from \MediaWiki\User\User::newSystemUser only
437 * @param string $username
439 public function preventSessionsForUser( $username ) {
440 $this->preventUsers[$username] = true;
442 // Instruct the session providers to kill any other sessions too.
443 foreach ( $this->getProviders() as $provider ) {
444 $provider->preventSessionsForUser( $username );
449 * Test if a user is prevented
450 * @internal For use from SessionBackend only
451 * @param string $username
452 * @return bool
454 public function isUserSessionPrevented( $username ) {
455 return !empty( $this->preventUsers[$username] );
459 * Get the available SessionProviders
460 * @return SessionProvider[]
462 protected function getProviders() {
463 if ( $this->sessionProviders === null ) {
464 $this->sessionProviders = [];
465 $objectFactory = MediaWikiServices::getInstance()->getObjectFactory();
466 foreach ( $this->config->get( MainConfigNames::SessionProviders ) as $spec ) {
467 /** @var SessionProvider $provider */
468 $provider = $objectFactory->createObject( $spec );
469 $provider->init(
470 $this->logger,
471 $this->config,
472 $this,
473 $this->hookContainer,
474 $this->userNameUtils
476 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
477 // @phan-suppress-next-line PhanTypeSuspiciousStringExpression
478 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
480 $this->sessionProviders[(string)$provider] = $provider;
483 return $this->sessionProviders;
487 * Get a session provider by name
489 * Generally, this will only be used by internal implementation of some
490 * special session-providing mechanism. General purpose code, if it needs
491 * to access a SessionProvider at all, will use Session::getProvider().
493 * @param string $name
494 * @return SessionProvider|null
496 public function getProvider( $name ) {
497 $providers = $this->getProviders();
498 return $providers[$name] ?? null;
502 * Save all active sessions on shutdown
503 * @internal For internal use with register_shutdown_function()
505 public function shutdown() {
506 if ( $this->allSessionBackends ) {
507 $this->logger->debug( 'Saving all sessions on shutdown' );
508 if ( session_id() !== '' ) {
509 // @codeCoverageIgnoreStart
510 session_write_close();
512 // @codeCoverageIgnoreEnd
513 foreach ( $this->allSessionBackends as $backend ) {
514 $backend->shutdown();
520 * Fetch the SessionInfo(s) for a request
521 * @param WebRequest $request
522 * @return SessionInfo|null
524 private function getSessionInfoForRequest( WebRequest $request ) {
525 // Call all providers to fetch "the" session
526 $infos = [];
527 foreach ( $this->getProviders() as $provider ) {
528 $info = $provider->provideSessionInfo( $request );
529 if ( !$info ) {
530 continue;
532 if ( $info->getProvider() !== $provider ) {
533 throw new \UnexpectedValueException(
534 "$provider returned session info for a different provider: $info"
537 $infos[] = $info;
540 // Sort the SessionInfos. Then find the first one that can be
541 // successfully loaded, and then all the ones after it with the same
542 // priority.
543 usort( $infos, [ SessionInfo::class, 'compare' ] );
544 $retInfos = [];
545 while ( $infos ) {
546 $info = array_pop( $infos );
547 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
548 $retInfos[] = $info;
549 while ( $infos ) {
550 /** @var SessionInfo $info */
551 $info = array_pop( $infos );
552 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
553 // We hit a lower priority, stop checking.
554 break;
556 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
557 // This is going to error out below, but we want to
558 // provide a complete list.
559 $retInfos[] = $info;
560 } else {
561 // Session load failed, so unpersist it from this request
562 $this->logUnpersist( $info, $request );
563 $info->getProvider()->unpersistSession( $request );
566 } else {
567 // Session load failed, so unpersist it from this request
568 $this->logUnpersist( $info, $request );
569 $info->getProvider()->unpersistSession( $request );
573 if ( count( $retInfos ) > 1 ) {
574 throw new SessionOverflowException(
575 $retInfos,
576 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
580 return $retInfos[0] ?? null;
584 * Load and verify the session info against the store
586 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
587 * @param WebRequest $request
588 * @return bool Whether the session info matches the stored data (if any)
590 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
591 $key = $this->store->makeKey( 'MWSession', $info->getId() );
592 $blob = $this->store->get( $key );
594 // If we got data from the store and the SessionInfo says to force use,
595 // "fail" means to delete the data from the store and retry. Otherwise,
596 // "fail" is just return false.
597 if ( $info->forceUse() && $blob !== false ) {
598 $failHandler = function () use ( $key, &$info, $request ) {
599 $this->store->delete( $key );
600 return $this->loadSessionInfoFromStore( $info, $request );
602 } else {
603 $failHandler = static function () {
604 return false;
608 $newParams = [];
610 if ( $blob !== false ) {
611 // Double check: blob must be an array, if it's saved at all
612 if ( !is_array( $blob ) ) {
613 $this->logger->warning( 'Session "{session}": Bad data', [
614 'session' => $info->__toString(),
615 ] );
616 $this->store->delete( $key );
617 return $failHandler();
620 // Double check: blob has data and metadata arrays
621 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
622 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
624 $this->logger->warning( 'Session "{session}": Bad data structure', [
625 'session' => $info->__toString(),
626 ] );
627 $this->store->delete( $key );
628 return $failHandler();
631 $data = $blob['data'];
632 $metadata = $blob['metadata'];
634 // Double check: metadata must be an array and must contain certain
635 // keys, if it's saved at all
636 if ( !array_key_exists( 'userId', $metadata ) ||
637 !array_key_exists( 'userName', $metadata ) ||
638 !array_key_exists( 'userToken', $metadata ) ||
639 !array_key_exists( 'provider', $metadata )
641 $this->logger->warning( 'Session "{session}": Bad metadata', [
642 'session' => $info->__toString(),
643 ] );
644 $this->store->delete( $key );
645 return $failHandler();
648 // First, load the provider from metadata, or validate it against the metadata.
649 $provider = $info->getProvider();
650 if ( $provider === null ) {
651 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
652 if ( !$provider ) {
653 $this->logger->warning(
654 'Session "{session}": Unknown provider ' . $metadata['provider'],
656 'session' => $info->__toString(),
659 $this->store->delete( $key );
660 return $failHandler();
662 } elseif ( $metadata['provider'] !== (string)$provider ) {
663 $this->logger->warning( 'Session "{session}": Wrong provider ' .
664 $metadata['provider'] . ' !== ' . $provider,
666 'session' => $info->__toString(),
667 ] );
668 return $failHandler();
671 // Load provider metadata from metadata, or validate it against the metadata
672 $providerMetadata = $info->getProviderMetadata();
673 if ( isset( $metadata['providerMetadata'] ) ) {
674 if ( $providerMetadata === null ) {
675 $newParams['metadata'] = $metadata['providerMetadata'];
676 } else {
677 try {
678 $newProviderMetadata = $provider->mergeMetadata(
679 $metadata['providerMetadata'], $providerMetadata
681 if ( $newProviderMetadata !== $providerMetadata ) {
682 $newParams['metadata'] = $newProviderMetadata;
684 } catch ( MetadataMergeException $ex ) {
685 $this->logger->warning(
686 'Session "{session}": Metadata merge failed: {exception}',
688 'session' => $info->__toString(),
689 'exception' => $ex,
690 ] + $ex->getContext()
692 return $failHandler();
697 // Next, load the user from metadata, or validate it against the metadata.
698 $userInfo = $info->getUserInfo();
699 if ( !$userInfo ) {
700 // For loading, id is preferred to name.
701 try {
702 if ( $metadata['userId'] ) {
703 $userInfo = UserInfo::newFromId( $metadata['userId'] );
704 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
705 $userInfo = UserInfo::newFromName( $metadata['userName'] );
706 } else {
707 $userInfo = UserInfo::newAnonymous();
709 } catch ( InvalidArgumentException $ex ) {
710 $this->logger->error( 'Session "{session}": {exception}', [
711 'session' => $info->__toString(),
712 'exception' => $ex,
713 ] );
714 return $failHandler();
716 $newParams['userInfo'] = $userInfo;
717 } else {
718 // User validation passes if user ID matches, or if there
719 // is no saved ID and the names match.
720 if ( $metadata['userId'] ) {
721 if ( $metadata['userId'] !== $userInfo->getId() ) {
722 // Maybe something like UserMerge changed the user ID. Or it's manual tampering.
723 $this->logger->warning(
724 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
726 'session' => $info->__toString(),
727 'uid_a' => $metadata['userId'],
728 'uid_b' => $userInfo->getId(),
729 'uname_a' => $metadata['userName'] ?? '<null>',
730 'uname_b' => $userInfo->getName() ?? '<null>',
731 ] );
732 return $failHandler();
735 // If the user was renamed, probably best to fail here.
736 if ( $metadata['userName'] !== null &&
737 $userInfo->getName() !== $metadata['userName']
739 $this->logger->warning(
740 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
742 'session' => $info->__toString(),
743 'uname_a' => $metadata['userName'],
744 'uname_b' => $userInfo->getName(),
745 ] );
746 return $failHandler();
749 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
750 if ( $metadata['userName'] !== $userInfo->getName() ) {
751 $this->logger->warning(
752 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
754 'session' => $info->__toString(),
755 'uname_a' => $metadata['userName'],
756 'uname_b' => $userInfo->getName(),
757 ] );
758 return $failHandler();
760 } elseif ( !$userInfo->isAnon() ) {
761 // The metadata in the session store entry indicates this is an anonymous session,
762 // but the request metadata (e.g. the username cookie) says otherwise. Maybe the
763 // user logged out but unsetting the cookies failed?
764 $this->logger->warning(
765 'Session "{session}": the session store entry is for an anonymous user, '
766 . 'but the session metadata indicates a non-anonynmous user',
768 'session' => $info->__toString(),
769 ] );
770 return $failHandler();
774 // And if we have a token in the metadata, it must match the loaded/provided user.
775 // A mismatch probably means the session was invalidated.
776 if ( $metadata['userToken'] !== null &&
777 $userInfo->getToken() !== $metadata['userToken']
779 $this->logger->warning( 'Session "{session}": User token mismatch', [
780 'session' => $info->__toString(),
781 ] );
782 return $failHandler();
784 if ( !$userInfo->isVerified() ) {
785 $newParams['userInfo'] = $userInfo->verified();
788 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
789 $newParams['remembered'] = true;
791 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
792 $newParams['forceHTTPS'] = true;
794 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
795 $newParams['persisted'] = true;
798 if ( !$info->isIdSafe() ) {
799 $newParams['idIsSafe'] = true;
801 } else {
802 // No metadata, so we can't load the provider if one wasn't given.
803 if ( $info->getProvider() === null ) {
804 $this->logger->warning(
805 'Session "{session}": Null provider and no metadata',
807 'session' => $info->__toString(),
808 ] );
809 return $failHandler();
812 // If no user was provided and no metadata, it must be anon.
813 if ( !$info->getUserInfo() ) {
814 if ( $info->getProvider()->canChangeUser() ) {
815 $newParams['userInfo'] = UserInfo::newAnonymous();
816 } else {
817 // This is a session provider bug - providers with canChangeUser() === false
818 // should never return an anonymous SessionInfo.
819 $this->logger->info(
820 'Session "{session}": No user provided and provider cannot set user',
822 'session' => $info->__toString(),
823 ] );
824 return $failHandler();
826 } elseif ( !$info->getUserInfo()->isVerified() ) {
827 // The session was not found in the session store, and the request contains no
828 // information beyond the session ID that could be used to verify it.
829 // Probably just a session timeout.
830 $this->logger->info(
831 'Session "{session}": Unverified user provided and no metadata to auth it',
833 'session' => $info->__toString(),
834 ] );
835 return $failHandler();
838 $data = false;
839 $metadata = false;
841 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
842 // The ID doesn't come from the user, so it should be safe
843 // (and if not, nothing we can do about it anyway)
844 $newParams['idIsSafe'] = true;
848 // Construct the replacement SessionInfo, if necessary
849 if ( $newParams ) {
850 $newParams['copyFrom'] = $info;
851 $info = new SessionInfo( $info->getPriority(), $newParams );
854 // Allow the provider to check the loaded SessionInfo
855 $providerMetadata = $info->getProviderMetadata();
856 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
857 return $failHandler();
859 if ( $providerMetadata !== $info->getProviderMetadata() ) {
860 $info = new SessionInfo( $info->getPriority(), [
861 'metadata' => $providerMetadata,
862 'copyFrom' => $info,
863 ] );
866 // Give hooks a chance to abort. Combined with the SessionMetadata
867 // hook, this can allow for tying a session to an IP address or the
868 // like.
869 $reason = 'Hook aborted';
870 if ( !$this->hookRunner->onSessionCheckInfo(
871 $reason, $info, $request, $metadata, $data )
873 $this->logger->warning( 'Session "{session}": ' . $reason, [
874 'session' => $info->__toString(),
875 ] );
876 return $failHandler();
879 return true;
883 * Create a Session corresponding to the passed SessionInfo
884 * @internal For use by a SessionProvider that needs to specially create its
885 * own Session. Most session providers won't need this.
886 * @param SessionInfo $info
887 * @param WebRequest $request
888 * @return Session
890 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
891 // @codeCoverageIgnoreStart
892 if ( defined( 'MW_NO_SESSION' ) ) {
893 $ep = defined( 'MW_ENTRY_POINT' ) ? MW_ENTRY_POINT : 'this';
895 if ( MW_NO_SESSION === 'warn' ) {
896 // Undocumented safety case for converting existing entry points
897 $this->logger->error( 'Sessions are supposed to be disabled for this entry point', [
898 'exception' => new \BadMethodCallException( "Sessions are disabled for $ep entry point" ),
899 ] );
900 } else {
901 throw new \BadMethodCallException( "Sessions are disabled for $ep entry point" );
904 // @codeCoverageIgnoreEnd
906 $id = $info->getId();
908 if ( !isset( $this->allSessionBackends[$id] ) ) {
909 if ( !isset( $this->allSessionIds[$id] ) ) {
910 $this->allSessionIds[$id] = new SessionId( $id );
912 $backend = new SessionBackend(
913 $this->allSessionIds[$id],
914 $info,
915 $this->store,
916 $this->logger,
917 $this->hookContainer,
918 $this->config->get( MainConfigNames::ObjectCacheSessionExpiry )
920 $this->allSessionBackends[$id] = $backend;
921 $delay = $backend->delaySave();
922 } else {
923 $backend = $this->allSessionBackends[$id];
924 $delay = $backend->delaySave();
925 if ( $info->wasPersisted() ) {
926 $backend->persist();
928 if ( $info->wasRemembered() ) {
929 $backend->setRememberUser( true );
933 $request->setSessionId( $backend->getSessionId() );
934 $session = $backend->getSession( $request );
936 if ( !$info->isIdSafe() ) {
937 $session->resetId();
940 \Wikimedia\ScopedCallback::consume( $delay );
941 return $session;
945 * Deregister a SessionBackend
946 * @internal For use from \MediaWiki\Session\SessionBackend only
947 * @param SessionBackend $backend
949 public function deregisterSessionBackend( SessionBackend $backend ) {
950 $id = $backend->getId();
951 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
952 $this->allSessionBackends[$id] !== $backend ||
953 $this->allSessionIds[$id] !== $backend->getSessionId()
955 throw new InvalidArgumentException( 'Backend was not registered with this SessionManager' );
958 unset( $this->allSessionBackends[$id] );
959 // Explicitly do not unset $this->allSessionIds[$id]
963 * Change a SessionBackend's ID
964 * @internal For use from \MediaWiki\Session\SessionBackend only
965 * @param SessionBackend $backend
967 public function changeBackendId( SessionBackend $backend ) {
968 $sessionId = $backend->getSessionId();
969 $oldId = (string)$sessionId;
970 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
971 $this->allSessionBackends[$oldId] !== $backend ||
972 $this->allSessionIds[$oldId] !== $sessionId
974 throw new InvalidArgumentException( 'Backend was not registered with this SessionManager' );
977 $newId = $this->generateSessionId();
979 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
980 $sessionId->setId( $newId );
981 $this->allSessionBackends[$newId] = $backend;
982 $this->allSessionIds[$newId] = $sessionId;
986 * Generate a new random session ID
987 * @return string
989 public function generateSessionId() {
990 $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
991 // Cache non-existence to avoid a later fetch
992 $key = $this->store->makeKey( 'MWSession', $id );
993 $this->store->set( $key, false, 0, BagOStuff::WRITE_CACHE_ONLY );
994 return $id;
998 * Call setters on a PHPSessionHandler
999 * @internal Use PhpSessionHandler::install()
1000 * @param PHPSessionHandler $handler
1002 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
1003 $handler->setManager( $this, $this->store, $this->logger );
1007 * Reset the internal caching for unit testing
1008 * @note Unit tests only
1009 * @internal
1011 public static function resetCache() {
1012 if ( !defined( 'MW_PHPUNIT_TEST' ) && !defined( 'MW_PARSER_TEST' ) ) {
1013 // @codeCoverageIgnoreStart
1014 throw new LogicException( __METHOD__ . ' may only be called from unit tests!' );
1015 // @codeCoverageIgnoreEnd
1018 self::$globalSession = null;
1019 self::$globalSessionRequest = null;
1022 private function logUnpersist( SessionInfo $info, WebRequest $request ) {
1023 $logData = [
1024 'id' => $info->getId(),
1025 'provider' => get_class( $info->getProvider() ),
1026 'user' => '<anon>',
1027 'supposedUser' => $info->getUserInfo() ? $info->getUserInfo()->getName() : null,
1028 'clientip' => $request->getIP(),
1029 'userAgent' => $request->getHeader( 'user-agent' ),
1031 if ( $info->getUserInfo() ) {
1032 if ( !$info->getUserInfo()->isAnon() ) {
1033 $logData['user'] = $info->getUserInfo()->getName();
1035 $logData['userVerified'] = $info->getUserInfo()->isVerified();
1037 $this->logger->info( 'Failed to load session, unpersisting', $logData );
1041 * If the same session is suddenly used from a different IP, that's potentially due
1042 * to a session leak, so log it. In the vast majority of cases it is a false positive
1043 * due to a user switching connections, but we are interested in an audit track where
1044 * we can look up a specific username, so a noisy log is fine.
1045 * Also log changes to the mwuser cookie, an analytics cookie set by mediawiki.user.js
1046 * which should be a little less noisy.
1047 * @private For use in Setup.php only
1048 * @param Session|null $session For testing only
1050 public function logPotentialSessionLeakage( ?Session $session = null ) {
1051 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1052 $session = $session ?: self::getGlobalSession();
1053 $suspiciousIpExpiry = $this->config->get( MainConfigNames::SuspiciousIpExpiry );
1055 if ( $suspiciousIpExpiry === false
1056 // We only care about logged-in users.
1057 || !$session->isPersistent() || $session->getUser()->isAnon()
1058 // We only care about cookie-based sessions.
1059 || !( $session->getProvider() instanceof CookieSessionProvider )
1061 return;
1063 try {
1064 $ip = $session->getRequest()->getIP();
1065 } catch ( MWException $e ) {
1066 return;
1068 if ( $ip === '127.0.0.1' || $proxyLookup->isConfiguredProxy( $ip ) ) {
1069 return;
1071 $mwuser = $session->getRequest()->getCookie( 'mwuser-sessionId' );
1072 $now = (int)\MediaWiki\Utils\MWTimestamp::now( TS_UNIX );
1074 // Record (and possibly log) that the IP is using the current session.
1075 // Don't touch the stored data unless we are changing the IP or re-adding an expired one.
1076 // This is slightly inaccurate (when an existing IP is seen again, the expiry is not
1077 // extended) but that shouldn't make much difference and limits the session write frequency.
1078 $data = $session->get( 'SessionManager-logPotentialSessionLeakage', [] )
1079 + [ 'ip' => null, 'mwuser' => null, 'timestamp' => 0 ];
1080 // Ignore old IP records; users change networks over time. mwuser is a session cookie and the
1081 // SessionManager session id is also a session cookie so there shouldn't be any problem there.
1082 if ( $data['ip'] &&
1083 ( $now - $data['timestamp'] > $suspiciousIpExpiry )
1085 $data['ip'] = $data['timestamp'] = null;
1088 if ( $data['ip'] !== $ip || $data['mwuser'] !== $mwuser ) {
1089 $session->set( 'SessionManager-logPotentialSessionLeakage',
1090 [ 'ip' => $ip, 'mwuser' => $mwuser, 'timestamp' => $now ] );
1093 $ipChanged = ( $data['ip'] && $data['ip'] !== $ip );
1094 $mwuserChanged = ( $data['mwuser'] && $data['mwuser'] !== $mwuser );
1095 $logLevel = $message = null;
1096 $logData = [];
1097 // IPs change all the time. mwuser is a session cookie that's only set when missing,
1098 // so it should only change when the browser session ends which ends the SessionManager
1099 // session as well. Unless we are dealing with a very weird client, such as a bot that
1100 //manipulates cookies and can run Javascript, it should not change.
1101 // IP and mwuser changing at the same time would be *very* suspicious.
1102 if ( $ipChanged ) {
1103 $logLevel = LogLevel::INFO;
1104 $message = 'IP change within the same session';
1105 $logData += [
1106 'oldIp' => $data['ip'],
1107 'oldIpRecorded' => $data['timestamp'],
1110 if ( $mwuserChanged ) {
1111 $logLevel = LogLevel::NOTICE;
1112 $message = 'mwuser change within the same session';
1113 $logData += [
1114 'oldMwuser' => $data['mwuser'],
1115 'newMwuser' => $mwuser,
1118 if ( $ipChanged && $mwuserChanged ) {
1119 $logLevel = LogLevel::WARNING;
1120 $message = 'IP and mwuser change within the same session';
1122 if ( $logLevel ) {
1123 $logData += [
1124 'session' => $session->getId(),
1125 'user' => $session->getUser()->getName(),
1126 'clientip' => $ip,
1127 'userAgent' => $session->getRequest()->getHeader( 'user-agent' ),
1129 $logger = \MediaWiki\Logger\LoggerFactory::getInstance( 'session-ip' );
1130 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable message is set when used here
1131 $logger->log( $logLevel, $message, $logData );
1135 // endregion -- end of Internal methods