Merge "Reset scoped session for upload jobs after deferred updates"
[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 } else {
667 // Session load failed, so unpersist it from this request
668 $info->getProvider()->unpersistSession( $request );
669 }
670 }
671 } else {
672 // Session load failed, so unpersist it from this request
673 $info->getProvider()->unpersistSession( $request );
674 }
675 }
676
677 if ( count( $retInfos ) > 1 ) {
678 $ex = new \OverflowException(
679 'Multiple sessions for this request tied for top priority: ' . join( ', ', $retInfos )
680 );
681 $ex->sessionInfos = $retInfos;
682 throw $ex;
683 }
684
685 return $retInfos ? $retInfos[0] : null;
686 }
687
688 /**
689 * Load and verify the session info against the store
690 *
691 * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
692 * @param WebRequest $request
693 * @return bool Whether the session info matches the stored data (if any)
694 */
695 private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
696 $key = wfMemcKey( 'MWSession', $info->getId() );
697 $blob = $this->store->get( $key );
698
699 $newParams = [];
700
701 if ( $blob !== false ) {
702 // Sanity check: blob must be an array, if it's saved at all
703 if ( !is_array( $blob ) ) {
704 $this->logger->warning( 'Session "{session}": Bad data', [
705 'session' => $info,
706 ] );
707 $this->store->delete( $key );
708 return false;
709 }
710
711 // Sanity check: blob has data and metadata arrays
712 if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
713 !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
714 ) {
715 $this->logger->warning( 'Session "{session}": Bad data structure', [
716 'session' => $info,
717 ] );
718 $this->store->delete( $key );
719 return false;
720 }
721
722 $data = $blob['data'];
723 $metadata = $blob['metadata'];
724
725 // Sanity check: metadata must be an array and must contain certain
726 // keys, if it's saved at all
727 if ( !array_key_exists( 'userId', $metadata ) ||
728 !array_key_exists( 'userName', $metadata ) ||
729 !array_key_exists( 'userToken', $metadata ) ||
730 !array_key_exists( 'provider', $metadata )
731 ) {
732 $this->logger->warning( 'Session "{session}": Bad metadata', [
733 'session' => $info,
734 ] );
735 $this->store->delete( $key );
736 return false;
737 }
738
739 // First, load the provider from metadata, or validate it against the metadata.
740 $provider = $info->getProvider();
741 if ( $provider === null ) {
742 $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
743 if ( !$provider ) {
744 $this->logger->warning(
745 'Session "{session}": Unknown provider ' . $metadata['provider'],
746 [
747 'session' => $info,
748 ]
749 );
750 $this->store->delete( $key );
751 return false;
752 }
753 } elseif ( $metadata['provider'] !== (string)$provider ) {
754 $this->logger->warning( 'Session "{session}": Wrong provider ' .
755 $metadata['provider'] . ' !== ' . $provider,
756 [
757 'session' => $info,
758 ] );
759 return false;
760 }
761
762 // Load provider metadata from metadata, or validate it against the metadata
763 $providerMetadata = $info->getProviderMetadata();
764 if ( isset( $metadata['providerMetadata'] ) ) {
765 if ( $providerMetadata === null ) {
766 $newParams['metadata'] = $metadata['providerMetadata'];
767 } else {
768 try {
769 $newProviderMetadata = $provider->mergeMetadata(
770 $metadata['providerMetadata'], $providerMetadata
771 );
772 if ( $newProviderMetadata !== $providerMetadata ) {
773 $newParams['metadata'] = $newProviderMetadata;
774 }
775 } catch ( MetadataMergeException $ex ) {
776 $this->logger->warning(
777 'Session "{session}": Metadata merge failed: {exception}',
778 [
779 'session' => $info,
780 'exception' => $ex,
781 ] + $ex->getContext()
782 );
783 return false;
784 }
785 }
786 }
787
788 // Next, load the user from metadata, or validate it against the metadata.
789 $userInfo = $info->getUserInfo();
790 if ( !$userInfo ) {
791 // For loading, id is preferred to name.
792 try {
793 if ( $metadata['userId'] ) {
794 $userInfo = UserInfo::newFromId( $metadata['userId'] );
795 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
796 $userInfo = UserInfo::newFromName( $metadata['userName'] );
797 } else {
798 $userInfo = UserInfo::newAnonymous();
799 }
800 } catch ( \InvalidArgumentException $ex ) {
801 $this->logger->error( 'Session "{session}": {exception}', [
802 'session' => $info,
803 'exception' => $ex,
804 ] );
805 return false;
806 }
807 $newParams['userInfo'] = $userInfo;
808 } else {
809 // User validation passes if user ID matches, or if there
810 // is no saved ID and the names match.
811 if ( $metadata['userId'] ) {
812 if ( $metadata['userId'] !== $userInfo->getId() ) {
813 $this->logger->warning(
814 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
815 [
816 'session' => $info,
817 'uid_a' => $metadata['userId'],
818 'uid_b' => $userInfo->getId(),
819 ] );
820 return false;
821 }
822
823 // If the user was renamed, probably best to fail here.
824 if ( $metadata['userName'] !== null &&
825 $userInfo->getName() !== $metadata['userName']
826 ) {
827 $this->logger->warning(
828 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
829 [
830 'session' => $info,
831 'uname_a' => $metadata['userName'],
832 'uname_b' => $userInfo->getName(),
833 ] );
834 return false;
835 }
836
837 } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
838 if ( $metadata['userName'] !== $userInfo->getName() ) {
839 $this->logger->warning(
840 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
841 [
842 'session' => $info,
843 'uname_a' => $metadata['userName'],
844 'uname_b' => $userInfo->getName(),
845 ] );
846 return false;
847 }
848 } elseif ( !$userInfo->isAnon() ) {
849 // Metadata specifies an anonymous user, but the passed-in
850 // user isn't anonymous.
851 $this->logger->warning(
852 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
853 [
854 'session' => $info,
855 ] );
856 return false;
857 }
858 }
859
860 // And if we have a token in the metadata, it must match the loaded/provided user.
861 if ( $metadata['userToken'] !== null &&
862 $userInfo->getToken() !== $metadata['userToken']
863 ) {
864 $this->logger->warning( 'Session "{session}": User token mismatch', [
865 'session' => $info,
866 ] );
867 return false;
868 }
869 if ( !$userInfo->isVerified() ) {
870 $newParams['userInfo'] = $userInfo->verified();
871 }
872
873 if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
874 $newParams['remembered'] = true;
875 }
876 if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
877 $newParams['forceHTTPS'] = true;
878 }
879 if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
880 $newParams['persisted'] = true;
881 }
882
883 if ( !$info->isIdSafe() ) {
884 $newParams['idIsSafe'] = true;
885 }
886 } else {
887 // No metadata, so we can't load the provider if one wasn't given.
888 if ( $info->getProvider() === null ) {
889 $this->logger->warning(
890 'Session "{session}": Null provider and no metadata',
891 [
892 'session' => $info,
893 ] );
894 return false;
895 }
896
897 // If no user was provided and no metadata, it must be anon.
898 if ( !$info->getUserInfo() ) {
899 if ( $info->getProvider()->canChangeUser() ) {
900 $newParams['userInfo'] = UserInfo::newAnonymous();
901 } else {
902 $this->logger->info(
903 'Session "{session}": No user provided and provider cannot set user',
904 [
905 'session' => $info,
906 ] );
907 return false;
908 }
909 } elseif ( !$info->getUserInfo()->isVerified() ) {
910 $this->logger->warning(
911 'Session "{session}": Unverified user provided and no metadata to auth it',
912 [
913 'session' => $info,
914 ] );
915 return false;
916 }
917
918 $data = false;
919 $metadata = false;
920
921 if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
922 // The ID doesn't come from the user, so it should be safe
923 // (and if not, nothing we can do about it anyway)
924 $newParams['idIsSafe'] = true;
925 }
926 }
927
928 // Construct the replacement SessionInfo, if necessary
929 if ( $newParams ) {
930 $newParams['copyFrom'] = $info;
931 $info = new SessionInfo( $info->getPriority(), $newParams );
932 }
933
934 // Allow the provider to check the loaded SessionInfo
935 $providerMetadata = $info->getProviderMetadata();
936 if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
937 return false;
938 }
939 if ( $providerMetadata !== $info->getProviderMetadata() ) {
940 $info = new SessionInfo( $info->getPriority(), [
941 'metadata' => $providerMetadata,
942 'copyFrom' => $info,
943 ] );
944 }
945
946 // Give hooks a chance to abort. Combined with the SessionMetadata
947 // hook, this can allow for tying a session to an IP address or the
948 // like.
949 $reason = 'Hook aborted';
950 if ( !\Hooks::run(
951 'SessionCheckInfo',
952 [ &$reason, $info, $request, $metadata, $data ]
953 ) ) {
954 $this->logger->warning( 'Session "{session}": ' . $reason, [
955 'session' => $info,
956 ] );
957 return false;
958 }
959
960 return true;
961 }
962
963 /**
964 * Create a session corresponding to the passed SessionInfo
965 * @private For use by a SessionProvider that needs to specially create its
966 * own session.
967 * @param SessionInfo $info
968 * @param WebRequest $request
969 * @return Session
970 */
971 public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
972 // @codeCoverageIgnoreStart
973 if ( defined( 'MW_NO_SESSION' ) ) {
974 if ( MW_NO_SESSION === 'warn' ) {
975 // Undocumented safety case for converting existing entry points
976 $this->logger->error( 'Sessions are supposed to be disabled for this entry point' );
977 } else {
978 throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
979 }
980 }
981 // @codeCoverageIgnoreEnd
982
983 $id = $info->getId();
984
985 if ( !isset( $this->allSessionBackends[$id] ) ) {
986 if ( !isset( $this->allSessionIds[$id] ) ) {
987 $this->allSessionIds[$id] = new SessionId( $id );
988 }
989 $backend = new SessionBackend(
990 $this->allSessionIds[$id],
991 $info,
992 $this->store,
993 $this->logger,
994 $this->config->get( 'ObjectCacheSessionExpiry' )
995 );
996 $this->allSessionBackends[$id] = $backend;
997 $delay = $backend->delaySave();
998 } else {
999 $backend = $this->allSessionBackends[$id];
1000 $delay = $backend->delaySave();
1001 if ( $info->wasPersisted() ) {
1002 $backend->persist();
1003 }
1004 if ( $info->wasRemembered() ) {
1005 $backend->setRememberUser( true );
1006 }
1007 }
1008
1009 $request->setSessionId( $backend->getSessionId() );
1010 $session = $backend->getSession( $request );
1011
1012 if ( !$info->isIdSafe() ) {
1013 $session->resetId();
1014 }
1015
1016 \ScopedCallback::consume( $delay );
1017 return $session;
1018 }
1019
1020 /**
1021 * Deregister a SessionBackend
1022 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1023 * @param SessionBackend $backend
1024 */
1025 public function deregisterSessionBackend( SessionBackend $backend ) {
1026 $id = $backend->getId();
1027 if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
1028 $this->allSessionBackends[$id] !== $backend ||
1029 $this->allSessionIds[$id] !== $backend->getSessionId()
1030 ) {
1031 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1032 }
1033
1034 unset( $this->allSessionBackends[$id] );
1035 // Explicitly do not unset $this->allSessionIds[$id]
1036 }
1037
1038 /**
1039 * Change a SessionBackend's ID
1040 * @private For use from \\MediaWiki\\Session\\SessionBackend only
1041 * @param SessionBackend $backend
1042 */
1043 public function changeBackendId( SessionBackend $backend ) {
1044 $sessionId = $backend->getSessionId();
1045 $oldId = (string)$sessionId;
1046 if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
1047 $this->allSessionBackends[$oldId] !== $backend ||
1048 $this->allSessionIds[$oldId] !== $sessionId
1049 ) {
1050 throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
1051 }
1052
1053 $newId = $this->generateSessionId();
1054
1055 unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
1056 $sessionId->setId( $newId );
1057 $this->allSessionBackends[$newId] = $backend;
1058 $this->allSessionIds[$newId] = $sessionId;
1059 }
1060
1061 /**
1062 * Generate a new random session ID
1063 * @return string
1064 */
1065 public function generateSessionId() {
1066 do {
1067 $id = wfBaseConvert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
1068 $key = wfMemcKey( 'MWSession', $id );
1069 } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
1070 return $id;
1071 }
1072
1073 /**
1074 * Call setters on a PHPSessionHandler
1075 * @private Use PhpSessionHandler::install()
1076 * @param PHPSessionHandler $handler
1077 */
1078 public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
1079 $handler->setManager( $this, $this->store, $this->logger );
1080 }
1081
1082 /**
1083 * Reset the internal caching for unit testing
1084 */
1085 public static function resetCache() {
1086 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
1087 // @codeCoverageIgnoreStart
1088 throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
1089 // @codeCoverageIgnoreEnd
1090 }
1091
1092 self::$globalSession = null;
1093 self::$globalSessionRequest = null;
1094 }
1095
1096 /**@}*/
1097
1098 }