Merge "Misc fixes for file patrol"
[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 # Notify AuthPlugin too
500 $tmpUser = $user;
501 $wgAuth->initUser( $tmpUser, true );
502 if ( $tmpUser !== $user ) {
503 $logger->warning( __METHOD__ . ': ' .
504 get_class( $wgAuth ) . '::initUser() replaced the user object' );
505 }
506
507 $user->saveSettings();
508
509 # Update user count
510 \DeferredUpdates::addUpdate( new \SiteStatsUpdate( 0, 0, 0, 0, 1 ) );
511
512 # Watch user's userpage and talk page
513 $user->addWatch( $user->getUserPage(), \WatchedItem::IGNORE_USER_RIGHTS );
514
515 return true;
516 }
517
518 /**
519 * Prevent future sessions for the user
520 *
521 * The intention is that the named account will never again be usable for
522 * normal login (i.e. there is no way to undo the prevention of access).
523 *
524 * @private For use from \\User::newSystemUser only
525 * @param string $username
526 */
527 public function preventSessionsForUser( $username ) {
528 $this->preventUsers[$username] = true;
529
530 // Reset the user's token to kill existing sessions
531 $user = User::newFromName( $username );
532 if ( $user && $user->getToken() ) {
533 $user->setToken( true );
534 $user->saveSettings();
535 }
536
537 // Instruct the session providers to kill any other sessions too.
538 foreach ( $this->getProviders() as $provider ) {
539 $provider->preventSessionsForUser( $username );
540 }
541 }
542
543 /**
544 * Test if a user is prevented
545 * @private For use from SessionBackend only
546 * @param string $username
547 * @return bool
548 */
549 public function isUserSessionPrevented( $username ) {
550 return !empty( $this->preventUsers[$username] );
551 }
552
553 /**
554 * Get the available SessionProviders
555 * @return SessionProvider[]
556 */
557 protected function getProviders() {
558 if ( $this->sessionProviders === null ) {
559 $this->sessionProviders = array();
560 foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
561 $provider = \ObjectFactory::getObjectFromSpec( $spec );
562 $provider->setLogger( $this->logger );
563 $provider->setConfig( $this->config );
564 $provider->setManager( $this );
565 if ( isset( $this->sessionProviders[(string)$provider] ) ) {
566 throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
567 }
568 $this->sessionProviders[(string)$provider] = $provider;
569 }
570 }
571 return $this->sessionProviders;
572 }
573
574 /**
575 * Get a session provider by name
576 *
577 * Generally, this will only be used by internal implementation of some
578 * special session-providing mechanism. General purpose code, if it needs
579 * to access a SessionProvider at all, will use Session::getProvider().
580 *
581 * @param string $name
582 * @return SessionProvider|null
583 */
584 public function getProvider( $name ) {
585 $providers = $this->getProviders();
586 return isset( $providers[$name] ) ? $providers[$name] : null;
587 }
588
589 /**
590 * Save all active sessions on shutdown
591 * @private For internal use with register_shutdown_function()
592 */
593 public function shutdown() {
594 if ( $this->allSessionBackends ) {
595 $this->logger->debug( 'Saving all sessions on shutdown' );
596 if ( session_id() !== '' ) {
597 // @codeCoverageIgnoreStart
598 session_write_close();
599 }
600 // @codeCoverageIgnoreEnd
601 foreach ( $this->allSessionBackends as $backend ) {
602 $backend->save( true );
603 }
604 }
605 }
606
607 /**
608 * Fetch the SessionInfo(s) for a request
609 * @param WebRequest $request
610 * @return SessionInfo|null
611 */
612 private function getSessionInfoForRequest( WebRequest $request ) {
613 // Call all providers to fetch "the" session
614 $infos = array();
615 foreach ( $this->getProviders() as $provider ) {
616 $info = $provider->provideSessionInfo( $request );
617 if ( !$info ) {
618 continue;
619 }
620 if ( $info->getProvider() !== $provider ) {
621 throw new \UnexpectedValueException(
622 "$provider returned session info for a different provider: $info"
623 );
624 }
625 $infos[] = $info;
626 }
627
628 // Sort the SessionInfos. Then find the first one that can be
629 // successfully loaded, and then all the ones after it with the same
630 // priority.
631 usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
632 $retInfos = array();
633 while ( $infos ) {
634 $info = array_pop( $infos );
635 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
636 $retInfos[] = $info;
637 while ( $infos ) {
638 $info = array_pop( $infos );
639 if ( SessionInfo::compare( $retInfos[0], $info ) ) {
640 // We hit a lower priority, stop checking.
641 break;
642 }
643 if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
644 // This is going to error out below, but we want to
645 // provide a complete list.
646 $retInfos[] = $info;
647 }
648 }
649 }
650 }
651
652 if ( count( $retInfos ) > 1 ) {
653 $ex = new \OverflowException(
654 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
655 );
656 $ex->sessionInfos = $retInfos;
657 throw $ex;
658 }
659
660 return $retInfos ? $retInfos[0] : null;
661 }
662
663 /**
664 * Load and verify the session info against the store
665 *
666 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
667 * @param WebRequest $request
668 * @return bool Whether the session info matches the stored data (if any)
669 */
670 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
671 $key = wfMemcKey( 'MWSession', $info->getId() );
672 $blob = $this->store->get( $key );
673
674 $newParams = array();
675
676 if ( $blob !== false ) {
677 // Sanity check: blob must be an array, if it's saved at all
678 if ( !is_array( $blob ) ) {
679 $this->logger->warning( "Session $info: Bad data" );
680 $this->store->delete( $key );
681 return false;
682 }
683
684 // Sanity check: blob has data and metadata arrays
685 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
686 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
687 ) {
688 $this->logger->warning( "Session $info: Bad data structure" );
689 $this->store->delete( $key );
690 return false;
691 }
692
693 $data = $blob['data'];
694 $metadata = $blob['metadata'];
695
696 // Sanity check: metadata must be an array and must contain certain
697 // keys, if it's saved at all
698 if ( !array_key_exists( 'userId', $metadata ) ||
699 !array_key_exists( 'userName', $metadata ) ||
700 !array_key_exists( 'userToken', $metadata ) ||
701 !array_key_exists( 'provider', $metadata )
702 ) {
703 $this->logger->warning( "Session $info: Bad metadata" );
704 $this->store->delete( $key );
705 return false;
706 }
707
708 // First, load the provider from metadata, or validate it against the metadata.
709 $provider = $info->getProvider();
710 if ( $provider === null ) {
711 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
712 if ( !$provider ) {
713 $this->logger->warning( "Session $info: Unknown provider, " . $metadata['provider'] );
714 $this->store->delete( $key );
715 return false;
716 }
717 } elseif ( $metadata['provider'] !== (string)$provider ) {
718 $this->logger->warning( "Session $info: Wrong provider, " .
719 $metadata['provider'] . ' !== ' . $provider );
720 return false;
721 }
722
723 // Load provider metadata from metadata, or validate it against the metadata
724 $providerMetadata = $info->getProviderMetadata();
725 if ( isset( $metadata['providerMetadata'] ) ) {
726 if ( $providerMetadata === null ) {
727 $newParams['metadata'] = $metadata['providerMetadata'];
728 } else {
729 try {
730 $newProviderMetadata = $provider->mergeMetadata(
731 $metadata['providerMetadata'], $providerMetadata
732 );
733 if ( $newProviderMetadata !== $providerMetadata ) {
734 $newParams['metadata'] = $newProviderMetadata;
735 }
736 } catch ( \UnexpectedValueException $ex ) {
737 $this->logger->warning( "Session $info: Metadata merge failed: " . $ex->getMessage() );
738 return false;
739 }
740 }
741 }
742
743 // Next, load the user from metadata, or validate it against the metadata.
744 $userInfo = $info->getUserInfo();
745 if ( !$userInfo ) {
746 // For loading, id is preferred to name.
747 try {
748 if ( $metadata['userId'] ) {
749 $userInfo = UserInfo::newFromId( $metadata['userId'] );
750 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
751 $userInfo = UserInfo::newFromName( $metadata['userName'] );
752 } else {
753 $userInfo = UserInfo::newAnonymous();
754 }
755 } catch ( \InvalidArgumentException $ex ) {
756 $this->logger->error( "Session $info: " . $ex->getMessage() );
757 return false;
758 }
759 $newParams['userInfo'] = $userInfo;
760 } else {
761 // User validation passes if user ID matches, or if there
762 // is no saved ID and the names match.
763 if ( $metadata['userId'] ) {
764 if ( $metadata['userId'] !== $userInfo->getId() ) {
765 $this->logger->warning( "Session $info: User ID mismatch, " .
766 $metadata['userId'] . ' !== ' . $userInfo->getId() );
767 return false;
768 }
769
770 // If the user was renamed, probably best to fail here.
771 if ( $metadata['userName'] !== null &&
772 $userInfo->getName() !== $metadata['userName']
773 ) {
774 $this->logger->warning( "Session $info: User ID matched but name didn't (rename?), " .
775 $metadata['userName'] . ' !== ' . $userInfo->getName() );
776 return false;
777 }
778
779 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
780 if ( $metadata['userName'] !== $userInfo->getName() ) {
781 $this->logger->warning( "Session $info: User name mismatch, " .
782 $metadata['userName'] . ' !== ' . $userInfo->getName() );
783 return false;
784 }
785 } elseif ( !$userInfo->isAnon() ) {
786 // Metadata specifies an anonymous user, but the passed-in
787 // user isn't anonymous.
788 $this->logger->warning(
789 "Session $info: Metadata has an anonymous user, " .
790 'but a non-anon user was provided'
791 );
792 return false;
793 }
794 }
795
796 // And if we have a token in the metadata, it must match the loaded/provided user.
797 if ( $metadata['userToken'] !== null &&
798 $userInfo->getToken() !== $metadata['userToken']
799 ) {
800 $this->logger->warning( "Session $info: User token mismatch" );
801 return false;
802 }
803 if ( !$userInfo->isVerified() ) {
804 $newParams['userInfo'] = $userInfo->verified();
805 }
806
807 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
808 $newParams['remembered'] = true;
809 }
810 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
811 $newParams['forceHTTPS'] = true;
812 }
813
814 if ( !$info->isIdSafe() ) {
815 $newParams['idIsSafe'] = true;
816 }
817 } else {
818 // No metadata, so we can't load the provider if one wasn't given.
819 if ( $info->getProvider() === null ) {
820 $this->logger->warning( "Session $info: Null provider and no metadata" );
821 return false;
822 }
823
824 // If no user was provided and no metadata, it must be anon.
825 if ( !$info->getUserInfo() ) {
826 if ( $info->getProvider()->canChangeUser() ) {
827 $newParams['userInfo'] = UserInfo::newAnonymous();
828 } else {
829 $this->logger->info(
830 "Session $info: No user provided and provider cannot set user"
831 );
832 return false;
833 }
834 } elseif ( !$info->getUserInfo()->isVerified() ) {
835 $this->logger->warning(
836 "Session $info: Unverified user provided and no metadata to auth it"
837 );
838 return false;
839 }
840
841 $data = false;
842 $metadata = false;
843
844 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
845 // The ID doesn't come from the user, so it should be safe
846 // (and if not, nothing we can do about it anyway)
847 $newParams['idIsSafe'] = true;
848 }
849 }
850
851 // Construct the replacement SessionInfo, if necessary
852 if ( $newParams ) {
853 $newParams['copyFrom'] = $info;
854 $info = new SessionInfo( $info->getPriority(), $newParams );
855 }
856
857 // Allow the provider to check the loaded SessionInfo
858 $providerMetadata = $info->getProviderMetadata();
859 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
860 return false;
861 }
862 if ( $providerMetadata !== $info->getProviderMetadata() ) {
863 $info = new SessionInfo( $info->getPriority(), array(
864 'metadata' => $providerMetadata,
865 'copyFrom' => $info,
866 ) );
867 }
868
869 // Give hooks a chance to abort. Combined with the SessionMetadata
870 // hook, this can allow for tying a session to an IP address or the
871 // like.
872 $reason = 'Hook aborted';
873 if ( !\Hooks::run(
874 'SessionCheckInfo',
875 array( &$reason, $info, $request, $metadata, $data )
876 ) ) {
877 $this->logger->warning( "Session $info: $reason" );
878 return false;
879 }
880
881 return true;
882 }
883
884 /**
885 * Create a session corresponding to the passed SessionInfo
886 * @private For use by a SessionProvider that needs to specially create its
887 * own session.
888 * @param SessionInfo $info
889 * @param WebRequest $request
890 * @return Session
891 */
892 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
893 $id = $info->getId();
894
895 if ( !isset( $this->allSessionBackends[$id] ) ) {
896 if ( !isset( $this->allSessionIds[$id] ) ) {
897 $this->allSessionIds[$id] = new SessionId( $id );
898 }
899 $backend = new SessionBackend(
900 $this->allSessionIds[$id],
901 $info,
902 $this->store,
903 $this->logger,
904 $this->config->get( 'ObjectCacheSessionExpiry' )
905 );
906 $this->allSessionBackends[$id] = $backend;
907 $delay = $backend->delaySave();
908 } else {
909 $backend = $this->allSessionBackends[$id];
910 $delay = $backend->delaySave();
911 if ( $info->wasPersisted() ) {
912 $backend->persist();
913 }
914 if ( $info->wasRemembered() ) {
915 $backend->setRememberUser( true );
916 }
917 }
918
919 $request->setSessionId( $backend->getSessionId() );
920 $session = $backend->getSession( $request );
921
922 if ( !$info->isIdSafe() ) {
923 $session->resetId();
924 }
925
926 \ScopedCallback::consume( $delay );
927 return $session;
928 }
929
930 /**
931 * Deregister a SessionBackend
932 * @private For use from \\MediaWiki\\Session\\SessionBackend only
933 * @param SessionBackend $backend
934 */
935 public function deregisterSessionBackend( SessionBackend $backend ) {
936 $id = $backend->getId();
937 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
938 $this->allSessionBackends[$id] !== $backend ||
939 $this->allSessionIds[$id] !== $backend->getSessionId()
940 ) {
941 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
942 }
943
944 unset( $this->allSessionBackends[$id] );
945 // Explicitly do not unset $this->allSessionIds[$id]
946 }
947
948 /**
949 * Change a SessionBackend's ID
950 * @private For use from \\MediaWiki\\Session\\SessionBackend only
951 * @param SessionBackend $backend
952 */
953 public function changeBackendId( SessionBackend $backend ) {
954 $sessionId = $backend->getSessionId();
955 $oldId = (string)$sessionId;
956 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
957 $this->allSessionBackends[$oldId] !== $backend ||
958 $this->allSessionIds[$oldId] !== $sessionId
959 ) {
960 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
961 }
962
963 $newId = $this->generateSessionId();
964
965 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
966 $sessionId->setId( $newId );
967 $this->allSessionBackends[$newId] = $backend;
968 $this->allSessionIds[$newId] = $sessionId;
969 }
970
971 /**
972 * Generate a new random session ID
973 * @return string
974 */
975 public function generateSessionId() {
976 do {
977 $id = wfBaseConvert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
978 $key = wfMemcKey( 'MWSession', $id );
979 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
980 return $id;
981 }
982
983 /**
984 * Call setters on a PHPSessionHandler
985 * @private Use PhpSessionHandler::install()
986 * @param PHPSessionHandler $handler
987 */
988 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
989 $handler->setManager( $this, $this->store, $this->logger );
990 }
991
992 /**
993 * Reset the internal caching for unit testing
994 */
995 public static function resetCache() {
996 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
997 // @codeCoverageIgnoreStart
998 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
999 // @codeCoverageIgnoreEnd
1000 }
1001
1002 self::$globalSession = null;
1003 self::$globalSessionRequest = null;
1004 }
1005
1006 /**@}*/
1007
1008 }