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