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