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