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