Merge "Correctly format null error reporting level"
[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 // @phan-suppress-next-line PhanTypeInvalidDimOffset
291 $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
292 if ( $compare > 0 ) {
293 continue;
294 }
295 if ( $compare === 0 ) {
296 $infos[] = $info;
297 } else {
298 $infos = [ $info ];
299 }
300 }
301
302 // Make sure there's exactly one
303 if ( count( $infos ) > 1 ) {
304 throw new \UnexpectedValueException(
305 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
306 );
307 } elseif ( count( $infos ) < 1 ) {
308 throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
309 }
310
311 return $this->getSessionFromInfo( $infos[0], $request );
312 }
313
314 public function invalidateSessionsForUser( User $user ) {
315 $user->setToken();
316 $user->saveSettings();
317
318 foreach ( $this->getProviders() as $provider ) {
319 $provider->invalidateSessionsForUser( $user );
320 }
321 }
322
323 public function getVaryHeaders() {
324 // @codeCoverageIgnoreStart
325 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
326 return [];
327 }
328 // @codeCoverageIgnoreEnd
329 if ( $this->varyHeaders === null ) {
330 $headers = [];
331 foreach ( $this->getProviders() as $provider ) {
332 foreach ( $provider->getVaryHeaders() as $header => $options ) {
333 # Note that the $options value returned has been deprecated
334 # and is ignored.
335 $headers[$header] = null;
336 }
337 }
338 $this->varyHeaders = $headers;
339 }
340 return $this->varyHeaders;
341 }
342
343 public function getVaryCookies() {
344 // @codeCoverageIgnoreStart
345 if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
346 return [];
347 }
348 // @codeCoverageIgnoreEnd
349 if ( $this->varyCookies === null ) {
350 $cookies = [];
351 foreach ( $this->getProviders() as $provider ) {
352 $cookies = array_merge( $cookies, $provider->getVaryCookies() );
353 }
354 $this->varyCookies = array_values( array_unique( $cookies ) );
355 }
356 return $this->varyCookies;
357 }
358
359 /**
360 * Validate a session ID
361 * @param string $id
362 * @return bool
363 */
364 public static function validateSessionId( $id ) {
365 return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
366 }
367
368 /**
369 * @name Internal methods
370 * @{
371 */
372
373 /**
374 * Prevent future sessions for the user
375 *
376 * The intention is that the named account will never again be usable for
377 * normal login (i.e. there is no way to undo the prevention of access).
378 *
379 * @private For use from \User::newSystemUser only
380 * @param string $username
381 */
382 public function preventSessionsForUser( $username ) {
383 $this->preventUsers[$username] = true;
384
385 // Instruct the session providers to kill any other sessions too.
386 foreach ( $this->getProviders() as $provider ) {
387 $provider->preventSessionsForUser( $username );
388 }
389 }
390
391 /**
392 * Test if a user is prevented
393 * @private For use from SessionBackend only
394 * @param string $username
395 * @return bool
396 */
397 public function isUserSessionPrevented( $username ) {
398 return !empty( $this->preventUsers[$username] );
399 }
400
401 /**
402 * Get the available SessionProviders
403 * @return SessionProvider[]
404 */
405 protected function getProviders() {
406 if ( $this->sessionProviders === null ) {
407 $this->sessionProviders = [];
408 foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
409 $provider = ObjectFactory::getObjectFromSpec( $spec );
410 $provider->setLogger( $this->logger );
411 $provider->setConfig( $this->config );
412 $provider->setManager( $this );
413 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
414 // @phan-suppress-next-line PhanTypeSuspiciousStringExpression
415 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
416 }
417 $this->sessionProviders[(string)$provider] = $provider;
418 }
419 }
420 return $this->sessionProviders;
421 }
422
423 /**
424 * Get a session provider by name
425 *
426 * Generally, this will only be used by internal implementation of some
427 * special session-providing mechanism. General purpose code, if it needs
428 * to access a SessionProvider at all, will use Session::getProvider().
429 *
430 * @param string $name
431 * @return SessionProvider|null
432 */
433 public function getProvider( $name ) {
434 $providers = $this->getProviders();
435 return $providers[$name] ?? null;
436 }
437
438 /**
439 * Save all active sessions on shutdown
440 * @private For internal use with register_shutdown_function()
441 */
442 public function shutdown() {
443 if ( $this->allSessionBackends ) {
444 $this->logger->debug( 'Saving all sessions on shutdown' );
445 if ( session_id() !== '' ) {
446 // @codeCoverageIgnoreStart
447 session_write_close();
448 }
449 // @codeCoverageIgnoreEnd
450 foreach ( $this->allSessionBackends as $backend ) {
451 $backend->shutdown();
452 }
453 }
454 }
455
456 /**
457 * Fetch the SessionInfo(s) for a request
458 * @param WebRequest $request
459 * @return SessionInfo|null
460 */
461 private function getSessionInfoForRequest( WebRequest $request ) {
462 // Call all providers to fetch "the" session
463 $infos = [];
464 foreach ( $this->getProviders() as $provider ) {
465 $info = $provider->provideSessionInfo( $request );
466 if ( !$info ) {
467 continue;
468 }
469 if ( $info->getProvider() !== $provider ) {
470 throw new \UnexpectedValueException(
471 "$provider returned session info for a different provider: $info"
472 );
473 }
474 $infos[] = $info;
475 }
476
477 // Sort the SessionInfos. Then find the first one that can be
478 // successfully loaded, and then all the ones after it with the same
479 // priority.
480 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
481 $retInfos = [];
482 while ( $infos ) {
483 $info = array_pop( $infos );
484 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
485 $retInfos[] = $info;
486 while ( $infos ) {
487 $info = array_pop( $infos );
488 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
489 // We hit a lower priority, stop checking.
490 break;
491 }
492 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
493 // This is going to error out below, but we want to
494 // provide a complete list.
495 $retInfos[] = $info;
496 } else {
497 // Session load failed, so unpersist it from this request
498 $info->getProvider()->unpersistSession( $request );
499 }
500 }
501 } else {
502 // Session load failed, so unpersist it from this request
503 $info->getProvider()->unpersistSession( $request );
504 }
505 }
506
507 if ( count( $retInfos ) > 1 ) {
508 $ex = new \OverflowException(
509 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
510 );
511 $ex->sessionInfos = $retInfos;
512 throw $ex;
513 }
514
515 return $retInfos ? $retInfos[0] : null;
516 }
517
518 /**
519 * Load and verify the session info against the store
520 *
521 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
522 * @param WebRequest $request
523 * @return bool Whether the session info matches the stored data (if any)
524 */
525 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
526 $key = $this->store->makeKey( 'MWSession', $info->getId() );
527 $blob = $this->store->get( $key );
528
529 // If we got data from the store and the SessionInfo says to force use,
530 // "fail" means to delete the data from the store and retry. Otherwise,
531 // "fail" is just return false.
532 if ( $info->forceUse() && $blob !== false ) {
533 $failHandler = function () use ( $key, &$info, $request ) {
534 $this->store->delete( $key );
535 return $this->loadSessionInfoFromStore( $info, $request );
536 };
537 } else {
538 $failHandler = function () {
539 return false;
540 };
541 }
542
543 $newParams = [];
544
545 if ( $blob !== false ) {
546 // Sanity check: blob must be an array, if it's saved at all
547 if ( !is_array( $blob ) ) {
548 $this->logger->warning( 'Session "{session}": Bad data', [
549 'session' => $info,
550 ] );
551 $this->store->delete( $key );
552 return $failHandler();
553 }
554
555 // Sanity check: blob has data and metadata arrays
556 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
557 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
558 ) {
559 $this->logger->warning( 'Session "{session}": Bad data structure', [
560 'session' => $info,
561 ] );
562 $this->store->delete( $key );
563 return $failHandler();
564 }
565
566 $data = $blob['data'];
567 $metadata = $blob['metadata'];
568
569 // Sanity check: metadata must be an array and must contain certain
570 // keys, if it's saved at all
571 if ( !array_key_exists( 'userId', $metadata ) ||
572 !array_key_exists( 'userName', $metadata ) ||
573 !array_key_exists( 'userToken', $metadata ) ||
574 !array_key_exists( 'provider', $metadata )
575 ) {
576 $this->logger->warning( 'Session "{session}": Bad metadata', [
577 'session' => $info,
578 ] );
579 $this->store->delete( $key );
580 return $failHandler();
581 }
582
583 // First, load the provider from metadata, or validate it against the metadata.
584 $provider = $info->getProvider();
585 if ( $provider === null ) {
586 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
587 if ( !$provider ) {
588 $this->logger->warning(
589 'Session "{session}": Unknown provider ' . $metadata['provider'],
590 [
591 'session' => $info,
592 ]
593 );
594 $this->store->delete( $key );
595 return $failHandler();
596 }
597 } elseif ( $metadata['provider'] !== (string)$provider ) {
598 $this->logger->warning( 'Session "{session}": Wrong provider ' .
599 $metadata['provider'] . ' !== ' . $provider,
600 [
601 'session' => $info,
602 ] );
603 return $failHandler();
604 }
605
606 // Load provider metadata from metadata, or validate it against the metadata
607 $providerMetadata = $info->getProviderMetadata();
608 if ( isset( $metadata['providerMetadata'] ) ) {
609 if ( $providerMetadata === null ) {
610 $newParams['metadata'] = $metadata['providerMetadata'];
611 } else {
612 try {
613 $newProviderMetadata = $provider->mergeMetadata(
614 $metadata['providerMetadata'], $providerMetadata
615 );
616 if ( $newProviderMetadata !== $providerMetadata ) {
617 $newParams['metadata'] = $newProviderMetadata;
618 }
619 } catch ( MetadataMergeException $ex ) {
620 $this->logger->warning(
621 'Session "{session}": Metadata merge failed: {exception}',
622 [
623 'session' => $info,
624 'exception' => $ex,
625 ] + $ex->getContext()
626 );
627 return $failHandler();
628 }
629 }
630 }
631
632 // Next, load the user from metadata, or validate it against the metadata.
633 $userInfo = $info->getUserInfo();
634 if ( !$userInfo ) {
635 // For loading, id is preferred to name.
636 try {
637 if ( $metadata['userId'] ) {
638 $userInfo = UserInfo::newFromId( $metadata['userId'] );
639 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
640 $userInfo = UserInfo::newFromName( $metadata['userName'] );
641 } else {
642 $userInfo = UserInfo::newAnonymous();
643 }
644 } catch ( \InvalidArgumentException $ex ) {
645 $this->logger->error( 'Session "{session}": {exception}', [
646 'session' => $info,
647 'exception' => $ex,
648 ] );
649 return $failHandler();
650 }
651 $newParams['userInfo'] = $userInfo;
652 } else {
653 // User validation passes if user ID matches, or if there
654 // is no saved ID and the names match.
655 if ( $metadata['userId'] ) {
656 if ( $metadata['userId'] !== $userInfo->getId() ) {
657 $this->logger->warning(
658 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
659 [
660 'session' => $info,
661 'uid_a' => $metadata['userId'],
662 'uid_b' => $userInfo->getId(),
663 ] );
664 return $failHandler();
665 }
666
667 // If the user was renamed, probably best to fail here.
668 if ( $metadata['userName'] !== null &&
669 $userInfo->getName() !== $metadata['userName']
670 ) {
671 $this->logger->warning(
672 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
673 [
674 'session' => $info,
675 'uname_a' => $metadata['userName'],
676 'uname_b' => $userInfo->getName(),
677 ] );
678 return $failHandler();
679 }
680
681 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
682 if ( $metadata['userName'] !== $userInfo->getName() ) {
683 $this->logger->warning(
684 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
685 [
686 'session' => $info,
687 'uname_a' => $metadata['userName'],
688 'uname_b' => $userInfo->getName(),
689 ] );
690 return $failHandler();
691 }
692 } elseif ( !$userInfo->isAnon() ) {
693 // Metadata specifies an anonymous user, but the passed-in
694 // user isn't anonymous.
695 $this->logger->warning(
696 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
697 [
698 'session' => $info,
699 ] );
700 return $failHandler();
701 }
702 }
703
704 // And if we have a token in the metadata, it must match the loaded/provided user.
705 if ( $metadata['userToken'] !== null &&
706 $userInfo->getToken() !== $metadata['userToken']
707 ) {
708 $this->logger->warning( 'Session "{session}": User token mismatch', [
709 'session' => $info,
710 ] );
711 return $failHandler();
712 }
713 if ( !$userInfo->isVerified() ) {
714 $newParams['userInfo'] = $userInfo->verified();
715 }
716
717 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
718 $newParams['remembered'] = true;
719 }
720 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
721 $newParams['forceHTTPS'] = true;
722 }
723 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
724 $newParams['persisted'] = true;
725 }
726
727 if ( !$info->isIdSafe() ) {
728 $newParams['idIsSafe'] = true;
729 }
730 } else {
731 // No metadata, so we can't load the provider if one wasn't given.
732 if ( $info->getProvider() === null ) {
733 $this->logger->warning(
734 'Session "{session}": Null provider and no metadata',
735 [
736 'session' => $info,
737 ] );
738 return $failHandler();
739 }
740
741 // If no user was provided and no metadata, it must be anon.
742 if ( !$info->getUserInfo() ) {
743 if ( $info->getProvider()->canChangeUser() ) {
744 $newParams['userInfo'] = UserInfo::newAnonymous();
745 } else {
746 $this->logger->info(
747 'Session "{session}": No user provided and provider cannot set user',
748 [
749 'session' => $info,
750 ] );
751 return $failHandler();
752 }
753 } elseif ( !$info->getUserInfo()->isVerified() ) {
754 // probably just a session timeout
755 $this->logger->info(
756 'Session "{session}": Unverified user provided and no metadata to auth it',
757 [
758 'session' => $info,
759 ] );
760 return $failHandler();
761 }
762
763 $data = false;
764 $metadata = false;
765
766 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
767 // The ID doesn't come from the user, so it should be safe
768 // (and if not, nothing we can do about it anyway)
769 $newParams['idIsSafe'] = true;
770 }
771 }
772
773 // Construct the replacement SessionInfo, if necessary
774 if ( $newParams ) {
775 $newParams['copyFrom'] = $info;
776 $info = new SessionInfo( $info->getPriority(), $newParams );
777 }
778
779 // Allow the provider to check the loaded SessionInfo
780 $providerMetadata = $info->getProviderMetadata();
781 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
782 return $failHandler();
783 }
784 if ( $providerMetadata !== $info->getProviderMetadata() ) {
785 $info = new SessionInfo( $info->getPriority(), [
786 'metadata' => $providerMetadata,
787 'copyFrom' => $info,
788 ] );
789 }
790
791 // Give hooks a chance to abort. Combined with the SessionMetadata
792 // hook, this can allow for tying a session to an IP address or the
793 // like.
794 $reason = 'Hook aborted';
795 if ( !\Hooks::run(
796 'SessionCheckInfo',
797 [ &$reason, $info, $request, $metadata, $data ]
798 ) ) {
799 $this->logger->warning( 'Session "{session}": ' . $reason, [
800 'session' => $info,
801 ] );
802 return $failHandler();
803 }
804
805 return true;
806 }
807
808 /**
809 * Create a Session corresponding to the passed SessionInfo
810 * @private For use by a SessionProvider that needs to specially create its
811 * own Session. Most session providers won't need this.
812 * @param SessionInfo $info
813 * @param WebRequest $request
814 * @return Session
815 */
816 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
817 // @codeCoverageIgnoreStart
818 if ( defined( 'MW_NO_SESSION' ) ) {
819 if ( MW_NO_SESSION === 'warn' ) {
820 // Undocumented safety case for converting existing entry points
821 $this->logger->error( 'Sessions are supposed to be disabled for this entry point', [
822 'exception' => new \BadMethodCallException( 'Sessions are disabled for this entry point' ),
823 ] );
824 } else {
825 throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
826 }
827 }
828 // @codeCoverageIgnoreEnd
829
830 $id = $info->getId();
831
832 if ( !isset( $this->allSessionBackends[$id] ) ) {
833 if ( !isset( $this->allSessionIds[$id] ) ) {
834 $this->allSessionIds[$id] = new SessionId( $id );
835 }
836 $backend = new SessionBackend(
837 $this->allSessionIds[$id],
838 $info,
839 $this->store,
840 $this->logger,
841 $this->config->get( 'ObjectCacheSessionExpiry' )
842 );
843 $this->allSessionBackends[$id] = $backend;
844 $delay = $backend->delaySave();
845 } else {
846 $backend = $this->allSessionBackends[$id];
847 $delay = $backend->delaySave();
848 if ( $info->wasPersisted() ) {
849 $backend->persist();
850 }
851 if ( $info->wasRemembered() ) {
852 $backend->setRememberUser( true );
853 }
854 }
855
856 $request->setSessionId( $backend->getSessionId() );
857 $session = $backend->getSession( $request );
858
859 if ( !$info->isIdSafe() ) {
860 $session->resetId();
861 }
862
863 \Wikimedia\ScopedCallback::consume( $delay );
864 return $session;
865 }
866
867 /**
868 * Deregister a SessionBackend
869 * @private For use from \MediaWiki\Session\SessionBackend only
870 * @param SessionBackend $backend
871 */
872 public function deregisterSessionBackend( SessionBackend $backend ) {
873 $id = $backend->getId();
874 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
875 $this->allSessionBackends[$id] !== $backend ||
876 $this->allSessionIds[$id] !== $backend->getSessionId()
877 ) {
878 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
879 }
880
881 unset( $this->allSessionBackends[$id] );
882 // Explicitly do not unset $this->allSessionIds[$id]
883 }
884
885 /**
886 * Change a SessionBackend's ID
887 * @private For use from \MediaWiki\Session\SessionBackend only
888 * @param SessionBackend $backend
889 */
890 public function changeBackendId( SessionBackend $backend ) {
891 $sessionId = $backend->getSessionId();
892 $oldId = (string)$sessionId;
893 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
894 $this->allSessionBackends[$oldId] !== $backend ||
895 $this->allSessionIds[$oldId] !== $sessionId
896 ) {
897 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
898 }
899
900 $newId = $this->generateSessionId();
901
902 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
903 $sessionId->setId( $newId );
904 $this->allSessionBackends[$newId] = $backend;
905 $this->allSessionIds[$newId] = $sessionId;
906 }
907
908 /**
909 * Generate a new random session ID
910 * @return string
911 */
912 public function generateSessionId() {
913 do {
914 $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
915 $key = $this->store->makeKey( 'MWSession', $id );
916 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
917 return $id;
918 }
919
920 /**
921 * Call setters on a PHPSessionHandler
922 * @private Use PhpSessionHandler::install()
923 * @param PHPSessionHandler $handler
924 */
925 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
926 $handler->setManager( $this, $this->store, $this->logger );
927 }
928
929 /**
930 * Reset the internal caching for unit testing
931 * @protected Unit tests only
932 */
933 public static function resetCache() {
934 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
935 // @codeCoverageIgnoreStart
936 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
937 // @codeCoverageIgnoreEnd
938 }
939
940 self::$globalSession = null;
941 self::$globalSessionRequest = null;
942 }
943
944 /** @} */
945
946 }