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