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