Merge "mw.widgets: Use CSS grid for the calendar in supporting browsers"
[lhc/web/wiklou.git] / includes / session / SessionManager.php
1 <?php
2 /**
3 * MediaWiki\Session entry point
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Session
22 */
23
24 namespace MediaWiki\Session;
25
26 use MediaWiki\MediaWikiServices;
27 use MWException;
28 use Psr\Log\LoggerInterface;
29 use BagOStuff;
30 use CachedBagOStuff;
31 use Config;
32 use FauxRequest;
33 use User;
34 use WebRequest;
35 use Wikimedia\ObjectFactory;
36
37 /**
38 * This serves as the entry point to the MediaWiki session handling system.
39 *
40 * Most methods here are for internal use by session handling code. Other callers
41 * should only use getGlobalSession and the methods of SessionManagerInterface;
42 * the rest of the functionality is exposed via MediaWiki\Session\Session methods.
43 *
44 * To provide custom session handling, implement a MediaWiki\Session\SessionProvider.
45 *
46 * @ingroup Session
47 * @since 1.27
48 * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
49 */
50 final class SessionManager implements SessionManagerInterface {
51 /** @var SessionManager|null */
52 private static $instance = null;
53
54 /** @var Session|null */
55 private static $globalSession = null;
56
57 /** @var WebRequest|null */
58 private static $globalSessionRequest = null;
59
60 /** @var LoggerInterface */
61 private $logger;
62
63 /** @var Config */
64 private $config;
65
66 /** @var CachedBagOStuff|null */
67 private $store;
68
69 /** @var SessionProvider[] */
70 private $sessionProviders = null;
71
72 /** @var string[] */
73 private $varyCookies = null;
74
75 /** @var array */
76 private $varyHeaders = null;
77
78 /** @var SessionBackend[] */
79 private $allSessionBackends = [];
80
81 /** @var SessionId[] */
82 private $allSessionIds = [];
83
84 /** @var string[] */
85 private $preventUsers = [];
86
87 /**
88 * Get the global SessionManager
89 * @return SessionManagerInterface
90 * (really a SessionManager, but this is to make IDEs less confused)
91 */
92 public static function singleton() {
93 if ( self::$instance === null ) {
94 self::$instance = new self();
95 }
96 return self::$instance;
97 }
98
99 /**
100 * Get the "global" session
101 *
102 * If PHP's session_id() has been set, returns that session. Otherwise
103 * returns the session for RequestContext::getMain()->getRequest().
104 *
105 * @return Session
106 */
107 public static function getGlobalSession() {
108 if ( !PHPSessionHandler::isEnabled() ) {
109 $id = '';
110 } else {
111 $id = session_id();
112 }
113
114 $request = \RequestContext::getMain()->getRequest();
115 if (
116 !self::$globalSession // No global session is set up yet
117 || self::$globalSessionRequest !== $request // The global WebRequest changed
118 || $id !== '' && self::$globalSession->getId() !== $id // Someone messed with session_id()
119 ) {
120 self::$globalSessionRequest = $request;
121 if ( $id === '' ) {
122 // session_id() wasn't used, so fetch the Session from the WebRequest.
123 // We use $request->getSession() instead of $singleton->getSessionForRequest()
124 // because doing the latter would require a public
125 // "$request->getSessionId()" method that would confuse end
126 // users by returning SessionId|null where they'd expect it to
127 // be short for $request->getSession()->getId(), and would
128 // wind up being a duplicate of the code in
129 // $request->getSession() anyway.
130 self::$globalSession = $request->getSession();
131 } else {
132 // Someone used session_id(), so we need to follow suit.
133 // Note this overwrites whatever session might already be
134 // associated with $request with the one for $id.
135 self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
136 ?: $request->getSession();
137 }
138 }
139 return self::$globalSession;
140 }
141
142 /**
143 * @param array $options
144 * - config: Config to fetch configuration from. Defaults to the default 'main' config.
145 * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
146 * - store: BagOStuff to store session data in.
147 */
148 public function __construct( $options = [] ) {
149 if ( isset( $options['config'] ) ) {
150 $this->config = $options['config'];
151 if ( !$this->config instanceof Config ) {
152 throw new \InvalidArgumentException(
153 '$options[\'config\'] must be an instance of Config'
154 );
155 }
156 } else {
157 $this->config = MediaWikiServices::getInstance()->getMainConfig();
158 }
159
160 if ( isset( $options['logger'] ) ) {
161 if ( !$options['logger'] instanceof LoggerInterface ) {
162 throw new \InvalidArgumentException(
163 '$options[\'logger\'] must be an instance of LoggerInterface'
164 );
165 }
166 $this->setLogger( $options['logger'] );
167 } else {
168 $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
169 }
170
171 if ( isset( $options['store'] ) ) {
172 if ( !$options['store'] instanceof BagOStuff ) {
173 throw new \InvalidArgumentException(
174 '$options[\'store\'] must be an instance of BagOStuff'
175 );
176 }
177 $store = $options['store'];
178 } else {
179 $store = \ObjectCache::getInstance( $this->config->get( 'SessionCacheType' ) );
180 }
181 $this->store = $store instanceof CachedBagOStuff ? $store : new CachedBagOStuff( $store );
182
183 register_shutdown_function( [ $this, 'shutdown' ] );
184 }
185
186 public function setLogger( LoggerInterface $logger ) {
187 $this->logger = $logger;
188 }
189
190 public function getSessionForRequest( WebRequest $request ) {
191 $info = $this->getSessionInfoForRequest( $request );
192
193 if ( !$info ) {
194 $session = $this->getEmptySession( $request );
195 } else {
196 $session = $this->getSessionFromInfo( $info, $request );
197 }
198 return $session;
199 }
200
201 public function getSessionById( $id, $create = false, WebRequest $request = null ) {
202 if ( !self::validateSessionId( $id ) ) {
203 throw new \InvalidArgumentException( 'Invalid session ID' );
204 }
205 if ( !$request ) {
206 $request = new FauxRequest;
207 }
208
209 $session = null;
210 $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [ 'id' => $id, 'idIsSafe' => true ] );
211
212 // If we already have the backend loaded, use it directly
213 if ( isset( $this->allSessionBackends[$id] ) ) {
214 return $this->getSessionFromInfo( $info, $request );
215 }
216
217 // Test if the session is in storage, and if so try to load it.
218 $key = $this->store->makeKey( 'MWSession', $id );
219 if ( is_array( $this->store->get( $key ) ) ) {
220 $create = false; // If loading fails, don't bother creating because it probably will fail too.
221 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
222 $session = $this->getSessionFromInfo( $info, $request );
223 }
224 }
225
226 if ( $create && $session === null ) {
227 $ex = null;
228 try {
229 $session = $this->getEmptySessionInternal( $request, $id );
230 } catch ( \Exception $ex ) {
231 $this->logger->error( 'Failed to create empty session: {exception}',
232 [
233 'method' => __METHOD__,
234 'exception' => $ex,
235 ] );
236 $session = null;
237 }
238 }
239
240 return $session;
241 }
242
243 public function getEmptySession( WebRequest $request = null ) {
244 return $this->getEmptySessionInternal( $request );
245 }
246
247 /**
248 * @see SessionManagerInterface::getEmptySession
249 * @param WebRequest|null $request
250 * @param string|null $id ID to force on the new session
251 * @return Session
252 */
253 private function getEmptySessionInternal( WebRequest $request = null, $id = null ) {
254 if ( $id !== null ) {
255 if ( !self::validateSessionId( $id ) ) {
256 throw new \InvalidArgumentException( 'Invalid session ID' );
257 }
258
259 $key = $this->store->makeKey( 'MWSession', $id );
260 if ( is_array( $this->store->get( $key ) ) ) {
261 throw new \InvalidArgumentException( 'Session ID already exists' );
262 }
263 }
264 if ( !$request ) {
265 $request = new FauxRequest;
266 }
267
268 $infos = [];
269 foreach ( $this->getProviders() as $provider ) {
270 $info = $provider->newSessionInfo( $id );
271 if ( !$info ) {
272 continue;
273 }
274 if ( $info->getProvider() !== $provider ) {
275 throw new \UnexpectedValueException(
276 "$provider returned an empty session info for a different provider: $info"
277 );
278 }
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
283 );
284 }
285 if ( !$info->isIdSafe() ) {
286 throw new \UnexpectedValueException(
287 "$provider returned empty session info with id flagged unsafe"
288 );
289 }
290 $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
291 if ( $compare > 0 ) {
292 continue;
293 }
294 if ( $compare === 0 ) {
295 $infos[] = $info;
296 } else {
297 $infos = [ $info ];
298 }
299 }
300
301 // Make sure there's exactly one
302 if ( count( $infos ) > 1 ) {
303 throw new \UnexpectedValueException(
304 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
305 );
306 } elseif ( count( $infos ) < 1 ) {
307 throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
308 }
309
310 return $this->getSessionFromInfo( $infos[0], $request );
311 }
312
313 public function invalidateSessionsForUser( User $user ) {
314 $user->setToken();
315 $user->saveSettings();
316
317 $authUser = \MediaWiki\Auth\AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$user ] );
318 if ( $authUser ) {
319 $authUser->resetAuthToken();
320 }
321
322 foreach ( $this->getProviders() as $provider ) {
323 $provider->invalidateSessionsForUser( $user );
324 }
325 }
326
327 public function getVaryHeaders() {
328 // @codeCoverageIgnoreStart
329 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
330 return [];
331 }
332 // @codeCoverageIgnoreEnd
333 if ( $this->varyHeaders === null ) {
334 $headers = [];
335 foreach ( $this->getProviders() as $provider ) {
336 foreach ( $provider->getVaryHeaders() as $header => $options ) {
337 if ( !isset( $headers[$header] ) ) {
338 $headers[$header] = [];
339 }
340 if ( is_array( $options ) ) {
341 $headers[$header] = array_unique( array_merge( $headers[$header], $options ) );
342 }
343 }
344 }
345 $this->varyHeaders = $headers;
346 }
347 return $this->varyHeaders;
348 }
349
350 public function getVaryCookies() {
351 // @codeCoverageIgnoreStart
352 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
353 return [];
354 }
355 // @codeCoverageIgnoreEnd
356 if ( $this->varyCookies === null ) {
357 $cookies = [];
358 foreach ( $this->getProviders() as $provider ) {
359 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
360 }
361 $this->varyCookies = array_values( array_unique( $cookies ) );
362 }
363 return $this->varyCookies;
364 }
365
366 /**
367 * Validate a session ID
368 * @param string $id
369 * @return bool
370 */
371 public static function validateSessionId( $id ) {
372 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
373 }
374
375 /**
376 * @name Internal methods
377 * @{
378 */
379
380 /**
381 * Prevent future sessions for the user
382 *
383 * The intention is that the named account will never again be usable for
384 * normal login (i.e. there is no way to undo the prevention of access).
385 *
386 * @private For use from \User::newSystemUser only
387 * @param string $username
388 */
389 public function preventSessionsForUser( $username ) {
390 $this->preventUsers[$username] = true;
391
392 // Instruct the session providers to kill any other sessions too.
393 foreach ( $this->getProviders() as $provider ) {
394 $provider->preventSessionsForUser( $username );
395 }
396 }
397
398 /**
399 * Test if a user is prevented
400 * @private For use from SessionBackend only
401 * @param string $username
402 * @return bool
403 */
404 public function isUserSessionPrevented( $username ) {
405 return !empty( $this->preventUsers[$username] );
406 }
407
408 /**
409 * Get the available SessionProviders
410 * @return SessionProvider[]
411 */
412 protected function getProviders() {
413 if ( $this->sessionProviders === null ) {
414 $this->sessionProviders = [];
415 foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
416 $provider = ObjectFactory::getObjectFromSpec( $spec );
417 $provider->setLogger( $this->logger );
418 $provider->setConfig( $this->config );
419 $provider->setManager( $this );
420 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
421 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
422 }
423 $this->sessionProviders[(string)$provider] = $provider;
424 }
425 }
426 return $this->sessionProviders;
427 }
428
429 /**
430 * Get a session provider by name
431 *
432 * Generally, this will only be used by internal implementation of some
433 * special session-providing mechanism. General purpose code, if it needs
434 * to access a SessionProvider at all, will use Session::getProvider().
435 *
436 * @param string $name
437 * @return SessionProvider|null
438 */
439 public function getProvider( $name ) {
440 $providers = $this->getProviders();
441 return $providers[$name] ?? null;
442 }
443
444 /**
445 * Save all active sessions on shutdown
446 * @private For internal use with register_shutdown_function()
447 */
448 public function shutdown() {
449 if ( $this->allSessionBackends ) {
450 $this->logger->debug( 'Saving all sessions on shutdown' );
451 if ( session_id() !== '' ) {
452 // @codeCoverageIgnoreStart
453 session_write_close();
454 }
455 // @codeCoverageIgnoreEnd
456 foreach ( $this->allSessionBackends as $backend ) {
457 $backend->shutdown();
458 }
459 }
460 }
461
462 /**
463 * Fetch the SessionInfo(s) for a request
464 * @param WebRequest $request
465 * @return SessionInfo|null
466 */
467 private function getSessionInfoForRequest( WebRequest $request ) {
468 // Call all providers to fetch "the" session
469 $infos = [];
470 foreach ( $this->getProviders() as $provider ) {
471 $info = $provider->provideSessionInfo( $request );
472 if ( !$info ) {
473 continue;
474 }
475 if ( $info->getProvider() !== $provider ) {
476 throw new \UnexpectedValueException(
477 "$provider returned session info for a different provider: $info"
478 );
479 }
480 $infos[] = $info;
481 }
482
483 // Sort the SessionInfos. Then find the first one that can be
484 // successfully loaded, and then all the ones after it with the same
485 // priority.
486 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
487 $retInfos = [];
488 while ( $infos ) {
489 $info = array_pop( $infos );
490 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
491 $retInfos[] = $info;
492 while ( $infos ) {
493 $info = array_pop( $infos );
494 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
495 // We hit a lower priority, stop checking.
496 break;
497 }
498 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
499 // This is going to error out below, but we want to
500 // provide a complete list.
501 $retInfos[] = $info;
502 } else {
503 // Session load failed, so unpersist it from this request
504 $info->getProvider()->unpersistSession( $request );
505 }
506 }
507 } else {
508 // Session load failed, so unpersist it from this request
509 $info->getProvider()->unpersistSession( $request );
510 }
511 }
512
513 if ( count( $retInfos ) > 1 ) {
514 $ex = new \OverflowException(
515 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
516 );
517 $ex->sessionInfos = $retInfos;
518 throw $ex;
519 }
520
521 return $retInfos ? $retInfos[0] : null;
522 }
523
524 /**
525 * Load and verify the session info against the store
526 *
527 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
528 * @param WebRequest $request
529 * @return bool Whether the session info matches the stored data (if any)
530 */
531 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
532 $key = $this->store->makeKey( 'MWSession', $info->getId() );
533 $blob = $this->store->get( $key );
534
535 // If we got data from the store and the SessionInfo says to force use,
536 // "fail" means to delete the data from the store and retry. Otherwise,
537 // "fail" is just return false.
538 if ( $info->forceUse() && $blob !== false ) {
539 $failHandler = function () use ( $key, &$info, $request ) {
540 $this->store->delete( $key );
541 return $this->loadSessionInfoFromStore( $info, $request );
542 };
543 } else {
544 $failHandler = function () {
545 return false;
546 };
547 }
548
549 $newParams = [];
550
551 if ( $blob !== false ) {
552 // Sanity check: blob must be an array, if it's saved at all
553 if ( !is_array( $blob ) ) {
554 $this->logger->warning( 'Session "{session}": Bad data', [
555 'session' => $info,
556 ] );
557 $this->store->delete( $key );
558 return $failHandler();
559 }
560
561 // Sanity check: blob has data and metadata arrays
562 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
563 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
564 ) {
565 $this->logger->warning( 'Session "{session}": Bad data structure', [
566 'session' => $info,
567 ] );
568 $this->store->delete( $key );
569 return $failHandler();
570 }
571
572 $data = $blob['data'];
573 $metadata = $blob['metadata'];
574
575 // Sanity check: metadata must be an array and must contain certain
576 // keys, if it's saved at all
577 if ( !array_key_exists( 'userId', $metadata ) ||
578 !array_key_exists( 'userName', $metadata ) ||
579 !array_key_exists( 'userToken', $metadata ) ||
580 !array_key_exists( 'provider', $metadata )
581 ) {
582 $this->logger->warning( 'Session "{session}": Bad metadata', [
583 'session' => $info,
584 ] );
585 $this->store->delete( $key );
586 return $failHandler();
587 }
588
589 // First, load the provider from metadata, or validate it against the metadata.
590 $provider = $info->getProvider();
591 if ( $provider === null ) {
592 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
593 if ( !$provider ) {
594 $this->logger->warning(
595 'Session "{session}": Unknown provider ' . $metadata['provider'],
596 [
597 'session' => $info,
598 ]
599 );
600 $this->store->delete( $key );
601 return $failHandler();
602 }
603 } elseif ( $metadata['provider'] !== (string)$provider ) {
604 $this->logger->warning( 'Session "{session}": Wrong provider ' .
605 $metadata['provider'] . ' !== ' . $provider,
606 [
607 'session' => $info,
608 ] );
609 return $failHandler();
610 }
611
612 // Load provider metadata from metadata, or validate it against the metadata
613 $providerMetadata = $info->getProviderMetadata();
614 if ( isset( $metadata['providerMetadata'] ) ) {
615 if ( $providerMetadata === null ) {
616 $newParams['metadata'] = $metadata['providerMetadata'];
617 } else {
618 try {
619 $newProviderMetadata = $provider->mergeMetadata(
620 $metadata['providerMetadata'], $providerMetadata
621 );
622 if ( $newProviderMetadata !== $providerMetadata ) {
623 $newParams['metadata'] = $newProviderMetadata;
624 }
625 } catch ( MetadataMergeException $ex ) {
626 $this->logger->warning(
627 'Session "{session}": Metadata merge failed: {exception}',
628 [
629 'session' => $info,
630 'exception' => $ex,
631 ] + $ex->getContext()
632 );
633 return $failHandler();
634 }
635 }
636 }
637
638 // Next, load the user from metadata, or validate it against the metadata.
639 $userInfo = $info->getUserInfo();
640 if ( !$userInfo ) {
641 // For loading, id is preferred to name.
642 try {
643 if ( $metadata['userId'] ) {
644 $userInfo = UserInfo::newFromId( $metadata['userId'] );
645 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
646 $userInfo = UserInfo::newFromName( $metadata['userName'] );
647 } else {
648 $userInfo = UserInfo::newAnonymous();
649 }
650 } catch ( \InvalidArgumentException $ex ) {
651 $this->logger->error( 'Session "{session}": {exception}', [
652 'session' => $info,
653 'exception' => $ex,
654 ] );
655 return $failHandler();
656 }
657 $newParams['userInfo'] = $userInfo;
658 } else {
659 // User validation passes if user ID matches, or if there
660 // is no saved ID and the names match.
661 if ( $metadata['userId'] ) {
662 if ( $metadata['userId'] !== $userInfo->getId() ) {
663 $this->logger->warning(
664 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
665 [
666 'session' => $info,
667 'uid_a' => $metadata['userId'],
668 'uid_b' => $userInfo->getId(),
669 ] );
670 return $failHandler();
671 }
672
673 // If the user was renamed, probably best to fail here.
674 if ( $metadata['userName'] !== null &&
675 $userInfo->getName() !== $metadata['userName']
676 ) {
677 $this->logger->warning(
678 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
679 [
680 'session' => $info,
681 'uname_a' => $metadata['userName'],
682 'uname_b' => $userInfo->getName(),
683 ] );
684 return $failHandler();
685 }
686
687 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
688 if ( $metadata['userName'] !== $userInfo->getName() ) {
689 $this->logger->warning(
690 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
691 [
692 'session' => $info,
693 'uname_a' => $metadata['userName'],
694 'uname_b' => $userInfo->getName(),
695 ] );
696 return $failHandler();
697 }
698 } elseif ( !$userInfo->isAnon() ) {
699 // Metadata specifies an anonymous user, but the passed-in
700 // user isn't anonymous.
701 $this->logger->warning(
702 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
703 [
704 'session' => $info,
705 ] );
706 return $failHandler();
707 }
708 }
709
710 // And if we have a token in the metadata, it must match the loaded/provided user.
711 if ( $metadata['userToken'] !== null &&
712 $userInfo->getToken() !== $metadata['userToken']
713 ) {
714 $this->logger->warning( 'Session "{session}": User token mismatch', [
715 'session' => $info,
716 ] );
717 return $failHandler();
718 }
719 if ( !$userInfo->isVerified() ) {
720 $newParams['userInfo'] = $userInfo->verified();
721 }
722
723 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
724 $newParams['remembered'] = true;
725 }
726 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
727 $newParams['forceHTTPS'] = true;
728 }
729 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
730 $newParams['persisted'] = true;
731 }
732
733 if ( !$info->isIdSafe() ) {
734 $newParams['idIsSafe'] = true;
735 }
736 } else {
737 // No metadata, so we can't load the provider if one wasn't given.
738 if ( $info->getProvider() === null ) {
739 $this->logger->warning(
740 'Session "{session}": Null provider and no metadata',
741 [
742 'session' => $info,
743 ] );
744 return $failHandler();
745 }
746
747 // If no user was provided and no metadata, it must be anon.
748 if ( !$info->getUserInfo() ) {
749 if ( $info->getProvider()->canChangeUser() ) {
750 $newParams['userInfo'] = UserInfo::newAnonymous();
751 } else {
752 $this->logger->info(
753 'Session "{session}": No user provided and provider cannot set user',
754 [
755 'session' => $info,
756 ] );
757 return $failHandler();
758 }
759 } elseif ( !$info->getUserInfo()->isVerified() ) {
760 // probably just a session timeout
761 $this->logger->info(
762 'Session "{session}": Unverified user provided and no metadata to auth it',
763 [
764 'session' => $info,
765 ] );
766 return $failHandler();
767 }
768
769 $data = false;
770 $metadata = false;
771
772 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
773 // The ID doesn't come from the user, so it should be safe
774 // (and if not, nothing we can do about it anyway)
775 $newParams['idIsSafe'] = true;
776 }
777 }
778
779 // Construct the replacement SessionInfo, if necessary
780 if ( $newParams ) {
781 $newParams['copyFrom'] = $info;
782 $info = new SessionInfo( $info->getPriority(), $newParams );
783 }
784
785 // Allow the provider to check the loaded SessionInfo
786 $providerMetadata = $info->getProviderMetadata();
787 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
788 return $failHandler();
789 }
790 if ( $providerMetadata !== $info->getProviderMetadata() ) {
791 $info = new SessionInfo( $info->getPriority(), [
792 'metadata' => $providerMetadata,
793 'copyFrom' => $info,
794 ] );
795 }
796
797 // Give hooks a chance to abort. Combined with the SessionMetadata
798 // hook, this can allow for tying a session to an IP address or the
799 // like.
800 $reason = 'Hook aborted';
801 if ( !\Hooks::run(
802 'SessionCheckInfo',
803 [ &$reason, $info, $request, $metadata, $data ]
804 ) ) {
805 $this->logger->warning( 'Session "{session}": ' . $reason, [
806 'session' => $info,
807 ] );
808 return $failHandler();
809 }
810
811 return true;
812 }
813
814 /**
815 * Create a Session corresponding to the passed SessionInfo
816 * @private For use by a SessionProvider that needs to specially create its
817 * own Session. Most session providers won't need this.
818 * @param SessionInfo $info
819 * @param WebRequest $request
820 * @return Session
821 */
822 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
823 // @codeCoverageIgnoreStart
824 if ( defined( 'MW_NO_SESSION' ) ) {
825 if ( MW_NO_SESSION === 'warn' ) {
826 // Undocumented safety case for converting existing entry points
827 $this->logger->error( 'Sessions are supposed to be disabled for this entry point', [
828 'exception' => new \BadMethodCallException( 'Sessions are disabled for this entry point' ),
829 ] );
830 } else {
831 throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
832 }
833 }
834 // @codeCoverageIgnoreEnd
835
836 $id = $info->getId();
837
838 if ( !isset( $this->allSessionBackends[$id] ) ) {
839 if ( !isset( $this->allSessionIds[$id] ) ) {
840 $this->allSessionIds[$id] = new SessionId( $id );
841 }
842 $backend = new SessionBackend(
843 $this->allSessionIds[$id],
844 $info,
845 $this->store,
846 $this->logger,
847 $this->config->get( 'ObjectCacheSessionExpiry' )
848 );
849 $this->allSessionBackends[$id] = $backend;
850 $delay = $backend->delaySave();
851 } else {
852 $backend = $this->allSessionBackends[$id];
853 $delay = $backend->delaySave();
854 if ( $info->wasPersisted() ) {
855 $backend->persist();
856 }
857 if ( $info->wasRemembered() ) {
858 $backend->setRememberUser( true );
859 }
860 }
861
862 $request->setSessionId( $backend->getSessionId() );
863 $session = $backend->getSession( $request );
864
865 if ( !$info->isIdSafe() ) {
866 $session->resetId();
867 }
868
869 \Wikimedia\ScopedCallback::consume( $delay );
870 return $session;
871 }
872
873 /**
874 * Deregister a SessionBackend
875 * @private For use from \MediaWiki\Session\SessionBackend only
876 * @param SessionBackend $backend
877 */
878 public function deregisterSessionBackend( SessionBackend $backend ) {
879 $id = $backend->getId();
880 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
881 $this->allSessionBackends[$id] !== $backend ||
882 $this->allSessionIds[$id] !== $backend->getSessionId()
883 ) {
884 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
885 }
886
887 unset( $this->allSessionBackends[$id] );
888 // Explicitly do not unset $this->allSessionIds[$id]
889 }
890
891 /**
892 * Change a SessionBackend's ID
893 * @private For use from \MediaWiki\Session\SessionBackend only
894 * @param SessionBackend $backend
895 */
896 public function changeBackendId( SessionBackend $backend ) {
897 $sessionId = $backend->getSessionId();
898 $oldId = (string)$sessionId;
899 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
900 $this->allSessionBackends[$oldId] !== $backend ||
901 $this->allSessionIds[$oldId] !== $sessionId
902 ) {
903 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
904 }
905
906 $newId = $this->generateSessionId();
907
908 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
909 $sessionId->setId( $newId );
910 $this->allSessionBackends[$newId] = $backend;
911 $this->allSessionIds[$newId] = $sessionId;
912 }
913
914 /**
915 * Generate a new random session ID
916 * @return string
917 */
918 public function generateSessionId() {
919 do {
920 $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
921 $key = $this->store->makeKey( 'MWSession', $id );
922 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
923 return $id;
924 }
925
926 /**
927 * Call setters on a PHPSessionHandler
928 * @private Use PhpSessionHandler::install()
929 * @param PHPSessionHandler $handler
930 */
931 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
932 $handler->setManager( $this, $this->store, $this->logger );
933 }
934
935 /**
936 * Reset the internal caching for unit testing
937 * @protected Unit tests only
938 */
939 public static function resetCache() {
940 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
941 // @codeCoverageIgnoreStart
942 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
943 // @codeCoverageIgnoreEnd
944 }
945
946 self::$globalSession = null;
947 self::$globalSessionRequest = null;
948 }
949
950 /**@}*/
951
952 }