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