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