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