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