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