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