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