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