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