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