SessionManager.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. namespace MediaWiki\Session;
  24. use MediaWiki\MediaWikiServices;
  25. use MWException;
  26. use Psr\Log\LoggerInterface;
  27. use BagOStuff;
  28. use CachedBagOStuff;
  29. use Config;
  30. use FauxRequest;
  31. use User;
  32. use WebRequest;
  33. use Wikimedia\ObjectFactory;
  34. /**
  35. * This serves as the entry point to the MediaWiki session handling system.
  36. *
  37. * Most methods here are for internal use by session handling code. Other callers
  38. * should only use getGlobalSession and the methods of SessionManagerInterface;
  39. * the rest of the functionality is exposed via MediaWiki\Session\Session methods.
  40. *
  41. * To provide custom session handling, implement a MediaWiki\Session\SessionProvider.
  42. *
  43. * @ingroup Session
  44. * @since 1.27
  45. * @see https://www.mediawiki.org/wiki/Manual:SessionManager_and_AuthManager
  46. */
  47. final class SessionManager implements SessionManagerInterface {
  48. /** @var SessionManager|null */
  49. private static $instance = null;
  50. /** @var Session|null */
  51. private static $globalSession = null;
  52. /** @var WebRequest|null */
  53. private static $globalSessionRequest = null;
  54. /** @var LoggerInterface */
  55. private $logger;
  56. /** @var Config */
  57. private $config;
  58. /** @var CachedBagOStuff|null */
  59. private $store;
  60. /** @var SessionProvider[] */
  61. private $sessionProviders = null;
  62. /** @var string[] */
  63. private $varyCookies = null;
  64. /** @var array */
  65. private $varyHeaders = null;
  66. /** @var SessionBackend[] */
  67. private $allSessionBackends = [];
  68. /** @var SessionId[] */
  69. private $allSessionIds = [];
  70. /** @var string[] */
  71. private $preventUsers = [];
  72. /**
  73. * Get the global SessionManager
  74. * @return self
  75. */
  76. public static function singleton() {
  77. if ( self::$instance === null ) {
  78. self::$instance = new self();
  79. }
  80. return self::$instance;
  81. }
  82. /**
  83. * Get the "global" session
  84. *
  85. * If PHP's session_id() has been set, returns that session. Otherwise
  86. * returns the session for RequestContext::getMain()->getRequest().
  87. *
  88. * @return Session
  89. */
  90. public static function getGlobalSession() {
  91. if ( !PHPSessionHandler::isEnabled() ) {
  92. $id = '';
  93. } else {
  94. $id = session_id();
  95. }
  96. $request = \RequestContext::getMain()->getRequest();
  97. if (
  98. !self::$globalSession // No global session is set up yet
  99. || self::$globalSessionRequest !== $request // The global WebRequest changed
  100. || $id !== '' && self::$globalSession->getId() !== $id // Someone messed with session_id()
  101. ) {
  102. self::$globalSessionRequest = $request;
  103. if ( $id === '' ) {
  104. // session_id() wasn't used, so fetch the Session from the WebRequest.
  105. // We use $request->getSession() instead of $singleton->getSessionForRequest()
  106. // because doing the latter would require a public
  107. // "$request->getSessionId()" method that would confuse end
  108. // users by returning SessionId|null where they'd expect it to
  109. // be short for $request->getSession()->getId(), and would
  110. // wind up being a duplicate of the code in
  111. // $request->getSession() anyway.
  112. self::$globalSession = $request->getSession();
  113. } else {
  114. // Someone used session_id(), so we need to follow suit.
  115. // Note this overwrites whatever session might already be
  116. // associated with $request with the one for $id.
  117. self::$globalSession = self::singleton()->getSessionById( $id, true, $request )
  118. ?: $request->getSession();
  119. }
  120. }
  121. return self::$globalSession;
  122. }
  123. /**
  124. * @param array $options
  125. * - config: Config to fetch configuration from. Defaults to the default 'main' config.
  126. * - logger: LoggerInterface to use for logging. Defaults to the 'session' channel.
  127. * - store: BagOStuff to store session data in.
  128. */
  129. public function __construct( $options = [] ) {
  130. if ( isset( $options['config'] ) ) {
  131. $this->config = $options['config'];
  132. if ( !$this->config instanceof Config ) {
  133. throw new \InvalidArgumentException(
  134. '$options[\'config\'] must be an instance of Config'
  135. );
  136. }
  137. } else {
  138. $this->config = MediaWikiServices::getInstance()->getMainConfig();
  139. }
  140. if ( isset( $options['logger'] ) ) {
  141. if ( !$options['logger'] instanceof LoggerInterface ) {
  142. throw new \InvalidArgumentException(
  143. '$options[\'logger\'] must be an instance of LoggerInterface'
  144. );
  145. }
  146. $this->setLogger( $options['logger'] );
  147. } else {
  148. $this->setLogger( \MediaWiki\Logger\LoggerFactory::getInstance( 'session' ) );
  149. }
  150. if ( isset( $options['store'] ) ) {
  151. if ( !$options['store'] instanceof BagOStuff ) {
  152. throw new \InvalidArgumentException(
  153. '$options[\'store\'] must be an instance of BagOStuff'
  154. );
  155. }
  156. $store = $options['store'];
  157. } else {
  158. $store = \ObjectCache::getInstance( $this->config->get( 'SessionCacheType' ) );
  159. }
  160. $this->logger->debug( 'SessionManager using store ' . get_class( $store ) );
  161. $this->store = $store instanceof CachedBagOStuff ? $store : new CachedBagOStuff( $store );
  162. register_shutdown_function( [ $this, 'shutdown' ] );
  163. }
  164. public function setLogger( LoggerInterface $logger ) {
  165. $this->logger = $logger;
  166. }
  167. public function getSessionForRequest( WebRequest $request ) {
  168. $info = $this->getSessionInfoForRequest( $request );
  169. if ( !$info ) {
  170. $session = $this->getEmptySession( $request );
  171. } else {
  172. $session = $this->getSessionFromInfo( $info, $request );
  173. }
  174. return $session;
  175. }
  176. public function getSessionById( $id, $create = false, WebRequest $request = null ) {
  177. if ( !self::validateSessionId( $id ) ) {
  178. throw new \InvalidArgumentException( 'Invalid session ID' );
  179. }
  180. if ( !$request ) {
  181. $request = new FauxRequest;
  182. }
  183. $session = null;
  184. $info = new SessionInfo( SessionInfo::MIN_PRIORITY, [ 'id' => $id, 'idIsSafe' => true ] );
  185. // If we already have the backend loaded, use it directly
  186. if ( isset( $this->allSessionBackends[$id] ) ) {
  187. return $this->getSessionFromInfo( $info, $request );
  188. }
  189. // Test if the session is in storage, and if so try to load it.
  190. $key = $this->store->makeKey( 'MWSession', $id );
  191. if ( is_array( $this->store->get( $key ) ) ) {
  192. $create = false; // If loading fails, don't bother creating because it probably will fail too.
  193. if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
  194. $session = $this->getSessionFromInfo( $info, $request );
  195. }
  196. }
  197. if ( $create && $session === null ) {
  198. $ex = null;
  199. try {
  200. $session = $this->getEmptySessionInternal( $request, $id );
  201. } catch ( \Exception $ex ) {
  202. $this->logger->error( 'Failed to create empty session: {exception}',
  203. [
  204. 'method' => __METHOD__,
  205. 'exception' => $ex,
  206. ] );
  207. $session = null;
  208. }
  209. }
  210. return $session;
  211. }
  212. public function getEmptySession( WebRequest $request = null ) {
  213. return $this->getEmptySessionInternal( $request );
  214. }
  215. /**
  216. * @see SessionManagerInterface::getEmptySession
  217. * @param WebRequest|null $request
  218. * @param string|null $id ID to force on the new session
  219. * @return Session
  220. */
  221. private function getEmptySessionInternal( WebRequest $request = null, $id = null ) {
  222. if ( $id !== null ) {
  223. if ( !self::validateSessionId( $id ) ) {
  224. throw new \InvalidArgumentException( 'Invalid session ID' );
  225. }
  226. $key = $this->store->makeKey( 'MWSession', $id );
  227. if ( is_array( $this->store->get( $key ) ) ) {
  228. throw new \InvalidArgumentException( 'Session ID already exists' );
  229. }
  230. }
  231. if ( !$request ) {
  232. $request = new FauxRequest;
  233. }
  234. $infos = [];
  235. foreach ( $this->getProviders() as $provider ) {
  236. $info = $provider->newSessionInfo( $id );
  237. if ( !$info ) {
  238. continue;
  239. }
  240. if ( $info->getProvider() !== $provider ) {
  241. throw new \UnexpectedValueException(
  242. "$provider returned an empty session info for a different provider: $info"
  243. );
  244. }
  245. if ( $id !== null && $info->getId() !== $id ) {
  246. throw new \UnexpectedValueException(
  247. "$provider returned empty session info with a wrong id: " .
  248. $info->getId() . ' != ' . $id
  249. );
  250. }
  251. if ( !$info->isIdSafe() ) {
  252. throw new \UnexpectedValueException(
  253. "$provider returned empty session info with id flagged unsafe"
  254. );
  255. }
  256. $compare = $infos ? SessionInfo::compare( $infos[0], $info ) : -1;
  257. if ( $compare > 0 ) {
  258. continue;
  259. }
  260. if ( $compare === 0 ) {
  261. $infos[] = $info;
  262. } else {
  263. $infos = [ $info ];
  264. }
  265. }
  266. // Make sure there's exactly one
  267. if ( count( $infos ) > 1 ) {
  268. throw new \UnexpectedValueException(
  269. 'Multiple empty sessions tied for top priority: ' . implode( ', ', $infos )
  270. );
  271. } elseif ( count( $infos ) < 1 ) {
  272. throw new \UnexpectedValueException( 'No provider could provide an empty session!' );
  273. }
  274. return $this->getSessionFromInfo( $infos[0], $request );
  275. }
  276. public function invalidateSessionsForUser( User $user ) {
  277. $user->setToken();
  278. $user->saveSettings();
  279. foreach ( $this->getProviders() as $provider ) {
  280. $provider->invalidateSessionsForUser( $user );
  281. }
  282. }
  283. public function getVaryHeaders() {
  284. // @codeCoverageIgnoreStart
  285. // @phan-suppress-next-line PhanUndeclaredConstant
  286. if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
  287. return [];
  288. }
  289. // @codeCoverageIgnoreEnd
  290. if ( $this->varyHeaders === null ) {
  291. $headers = [];
  292. foreach ( $this->getProviders() as $provider ) {
  293. foreach ( $provider->getVaryHeaders() as $header => $options ) {
  294. # Note that the $options value returned has been deprecated
  295. # and is ignored.
  296. $headers[$header] = null;
  297. }
  298. }
  299. $this->varyHeaders = $headers;
  300. }
  301. return $this->varyHeaders;
  302. }
  303. public function getVaryCookies() {
  304. // @codeCoverageIgnoreStart
  305. // @phan-suppress-next-line PhanUndeclaredConstant
  306. if ( defined( 'MW_NO_SESSION' ) && MW_NO_SESSION !== 'warn' ) {
  307. return [];
  308. }
  309. // @codeCoverageIgnoreEnd
  310. if ( $this->varyCookies === null ) {
  311. $cookies = [];
  312. foreach ( $this->getProviders() as $provider ) {
  313. $cookies = array_merge( $cookies, $provider->getVaryCookies() );
  314. }
  315. $this->varyCookies = array_values( array_unique( $cookies ) );
  316. }
  317. return $this->varyCookies;
  318. }
  319. /**
  320. * Validate a session ID
  321. * @param string $id
  322. * @return bool
  323. */
  324. public static function validateSessionId( $id ) {
  325. return is_string( $id ) && preg_match( '/^[a-zA-Z0-9_-]{32,}$/', $id );
  326. }
  327. /**
  328. * @name Internal methods
  329. * @{
  330. */
  331. /**
  332. * Prevent future sessions for the user
  333. *
  334. * The intention is that the named account will never again be usable for
  335. * normal login (i.e. there is no way to undo the prevention of access).
  336. *
  337. * @private For use from \User::newSystemUser only
  338. * @param string $username
  339. */
  340. public function preventSessionsForUser( $username ) {
  341. $this->preventUsers[$username] = true;
  342. // Instruct the session providers to kill any other sessions too.
  343. foreach ( $this->getProviders() as $provider ) {
  344. $provider->preventSessionsForUser( $username );
  345. }
  346. }
  347. /**
  348. * Test if a user is prevented
  349. * @private For use from SessionBackend only
  350. * @param string $username
  351. * @return bool
  352. */
  353. public function isUserSessionPrevented( $username ) {
  354. return !empty( $this->preventUsers[$username] );
  355. }
  356. /**
  357. * Get the available SessionProviders
  358. * @return SessionProvider[]
  359. */
  360. protected function getProviders() {
  361. if ( $this->sessionProviders === null ) {
  362. $this->sessionProviders = [];
  363. foreach ( $this->config->get( 'SessionProviders' ) as $spec ) {
  364. $provider = ObjectFactory::getObjectFromSpec( $spec );
  365. $provider->setLogger( $this->logger );
  366. $provider->setConfig( $this->config );
  367. $provider->setManager( $this );
  368. if ( isset( $this->sessionProviders[(string)$provider] ) ) {
  369. // @phan-suppress-next-line PhanTypeSuspiciousStringExpression
  370. throw new \UnexpectedValueException( "Duplicate provider name \"$provider\"" );
  371. }
  372. $this->sessionProviders[(string)$provider] = $provider;
  373. }
  374. }
  375. return $this->sessionProviders;
  376. }
  377. /**
  378. * Get a session provider by name
  379. *
  380. * Generally, this will only be used by internal implementation of some
  381. * special session-providing mechanism. General purpose code, if it needs
  382. * to access a SessionProvider at all, will use Session::getProvider().
  383. *
  384. * @param string $name
  385. * @return SessionProvider|null
  386. */
  387. public function getProvider( $name ) {
  388. $providers = $this->getProviders();
  389. return $providers[$name] ?? null;
  390. }
  391. /**
  392. * Save all active sessions on shutdown
  393. * @private For internal use with register_shutdown_function()
  394. */
  395. public function shutdown() {
  396. if ( $this->allSessionBackends ) {
  397. $this->logger->debug( 'Saving all sessions on shutdown' );
  398. if ( session_id() !== '' ) {
  399. // @codeCoverageIgnoreStart
  400. session_write_close();
  401. }
  402. // @codeCoverageIgnoreEnd
  403. foreach ( $this->allSessionBackends as $backend ) {
  404. $backend->shutdown();
  405. }
  406. }
  407. }
  408. /**
  409. * Fetch the SessionInfo(s) for a request
  410. * @param WebRequest $request
  411. * @return SessionInfo|null
  412. */
  413. private function getSessionInfoForRequest( WebRequest $request ) {
  414. // Call all providers to fetch "the" session
  415. $infos = [];
  416. foreach ( $this->getProviders() as $provider ) {
  417. $info = $provider->provideSessionInfo( $request );
  418. if ( !$info ) {
  419. continue;
  420. }
  421. if ( $info->getProvider() !== $provider ) {
  422. throw new \UnexpectedValueException(
  423. "$provider returned session info for a different provider: $info"
  424. );
  425. }
  426. $infos[] = $info;
  427. }
  428. // Sort the SessionInfos. Then find the first one that can be
  429. // successfully loaded, and then all the ones after it with the same
  430. // priority.
  431. usort( $infos, 'MediaWiki\\Session\\SessionInfo::compare' );
  432. $retInfos = [];
  433. while ( $infos ) {
  434. $info = array_pop( $infos );
  435. if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
  436. $retInfos[] = $info;
  437. while ( $infos ) {
  438. $info = array_pop( $infos );
  439. if ( SessionInfo::compare( $retInfos[0], $info ) ) {
  440. // We hit a lower priority, stop checking.
  441. break;
  442. }
  443. if ( $this->loadSessionInfoFromStore( $info, $request ) ) {
  444. // This is going to error out below, but we want to
  445. // provide a complete list.
  446. $retInfos[] = $info;
  447. } else {
  448. // Session load failed, so unpersist it from this request
  449. $info->getProvider()->unpersistSession( $request );
  450. }
  451. }
  452. } else {
  453. // Session load failed, so unpersist it from this request
  454. $info->getProvider()->unpersistSession( $request );
  455. }
  456. }
  457. if ( count( $retInfos ) > 1 ) {
  458. throw new SessionOverflowException(
  459. $retInfos,
  460. 'Multiple sessions for this request tied for top priority: ' . implode( ', ', $retInfos )
  461. );
  462. }
  463. return $retInfos ? $retInfos[0] : null;
  464. }
  465. /**
  466. * Load and verify the session info against the store
  467. *
  468. * @param SessionInfo &$info Will likely be replaced with an updated SessionInfo instance
  469. * @param WebRequest $request
  470. * @return bool Whether the session info matches the stored data (if any)
  471. */
  472. private function loadSessionInfoFromStore( SessionInfo &$info, WebRequest $request ) {
  473. $key = $this->store->makeKey( 'MWSession', $info->getId() );
  474. $blob = $this->store->get( $key );
  475. // If we got data from the store and the SessionInfo says to force use,
  476. // "fail" means to delete the data from the store and retry. Otherwise,
  477. // "fail" is just return false.
  478. if ( $info->forceUse() && $blob !== false ) {
  479. $failHandler = function () use ( $key, &$info, $request ) {
  480. $this->store->delete( $key );
  481. return $this->loadSessionInfoFromStore( $info, $request );
  482. };
  483. } else {
  484. $failHandler = function () {
  485. return false;
  486. };
  487. }
  488. $newParams = [];
  489. if ( $blob !== false ) {
  490. // Sanity check: blob must be an array, if it's saved at all
  491. if ( !is_array( $blob ) ) {
  492. $this->logger->warning( 'Session "{session}": Bad data', [
  493. 'session' => $info,
  494. ] );
  495. $this->store->delete( $key );
  496. return $failHandler();
  497. }
  498. // Sanity check: blob has data and metadata arrays
  499. if ( !isset( $blob['data'] ) || !is_array( $blob['data'] ) ||
  500. !isset( $blob['metadata'] ) || !is_array( $blob['metadata'] )
  501. ) {
  502. $this->logger->warning( 'Session "{session}": Bad data structure', [
  503. 'session' => $info,
  504. ] );
  505. $this->store->delete( $key );
  506. return $failHandler();
  507. }
  508. $data = $blob['data'];
  509. $metadata = $blob['metadata'];
  510. // Sanity check: metadata must be an array and must contain certain
  511. // keys, if it's saved at all
  512. if ( !array_key_exists( 'userId', $metadata ) ||
  513. !array_key_exists( 'userName', $metadata ) ||
  514. !array_key_exists( 'userToken', $metadata ) ||
  515. !array_key_exists( 'provider', $metadata )
  516. ) {
  517. $this->logger->warning( 'Session "{session}": Bad metadata', [
  518. 'session' => $info,
  519. ] );
  520. $this->store->delete( $key );
  521. return $failHandler();
  522. }
  523. // First, load the provider from metadata, or validate it against the metadata.
  524. $provider = $info->getProvider();
  525. if ( $provider === null ) {
  526. $newParams['provider'] = $provider = $this->getProvider( $metadata['provider'] );
  527. if ( !$provider ) {
  528. $this->logger->warning(
  529. 'Session "{session}": Unknown provider ' . $metadata['provider'],
  530. [
  531. 'session' => $info,
  532. ]
  533. );
  534. $this->store->delete( $key );
  535. return $failHandler();
  536. }
  537. } elseif ( $metadata['provider'] !== (string)$provider ) {
  538. $this->logger->warning( 'Session "{session}": Wrong provider ' .
  539. $metadata['provider'] . ' !== ' . $provider,
  540. [
  541. 'session' => $info,
  542. ] );
  543. return $failHandler();
  544. }
  545. // Load provider metadata from metadata, or validate it against the metadata
  546. $providerMetadata = $info->getProviderMetadata();
  547. if ( isset( $metadata['providerMetadata'] ) ) {
  548. if ( $providerMetadata === null ) {
  549. $newParams['metadata'] = $metadata['providerMetadata'];
  550. } else {
  551. try {
  552. $newProviderMetadata = $provider->mergeMetadata(
  553. $metadata['providerMetadata'], $providerMetadata
  554. );
  555. if ( $newProviderMetadata !== $providerMetadata ) {
  556. $newParams['metadata'] = $newProviderMetadata;
  557. }
  558. } catch ( MetadataMergeException $ex ) {
  559. $this->logger->warning(
  560. 'Session "{session}": Metadata merge failed: {exception}',
  561. [
  562. 'session' => $info,
  563. 'exception' => $ex,
  564. ] + $ex->getContext()
  565. );
  566. return $failHandler();
  567. }
  568. }
  569. }
  570. // Next, load the user from metadata, or validate it against the metadata.
  571. $userInfo = $info->getUserInfo();
  572. if ( !$userInfo ) {
  573. // For loading, id is preferred to name.
  574. try {
  575. if ( $metadata['userId'] ) {
  576. $userInfo = UserInfo::newFromId( $metadata['userId'] );
  577. } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
  578. $userInfo = UserInfo::newFromName( $metadata['userName'] );
  579. } else {
  580. $userInfo = UserInfo::newAnonymous();
  581. }
  582. } catch ( \InvalidArgumentException $ex ) {
  583. $this->logger->error( 'Session "{session}": {exception}', [
  584. 'session' => $info,
  585. 'exception' => $ex,
  586. ] );
  587. return $failHandler();
  588. }
  589. $newParams['userInfo'] = $userInfo;
  590. } else {
  591. // User validation passes if user ID matches, or if there
  592. // is no saved ID and the names match.
  593. if ( $metadata['userId'] ) {
  594. if ( $metadata['userId'] !== $userInfo->getId() ) {
  595. $this->logger->warning(
  596. 'Session "{session}": User ID mismatch, {uid_a} !== {uid_b}',
  597. [
  598. 'session' => $info,
  599. 'uid_a' => $metadata['userId'],
  600. 'uid_b' => $userInfo->getId(),
  601. ] );
  602. return $failHandler();
  603. }
  604. // If the user was renamed, probably best to fail here.
  605. if ( $metadata['userName'] !== null &&
  606. $userInfo->getName() !== $metadata['userName']
  607. ) {
  608. $this->logger->warning(
  609. 'Session "{session}": User ID matched but name didn\'t (rename?), {uname_a} !== {uname_b}',
  610. [
  611. 'session' => $info,
  612. 'uname_a' => $metadata['userName'],
  613. 'uname_b' => $userInfo->getName(),
  614. ] );
  615. return $failHandler();
  616. }
  617. } elseif ( $metadata['userName'] !== null ) { // Shouldn't happen, but just in case
  618. if ( $metadata['userName'] !== $userInfo->getName() ) {
  619. $this->logger->warning(
  620. 'Session "{session}": User name mismatch, {uname_a} !== {uname_b}',
  621. [
  622. 'session' => $info,
  623. 'uname_a' => $metadata['userName'],
  624. 'uname_b' => $userInfo->getName(),
  625. ] );
  626. return $failHandler();
  627. }
  628. } elseif ( !$userInfo->isAnon() ) {
  629. // Metadata specifies an anonymous user, but the passed-in
  630. // user isn't anonymous.
  631. $this->logger->warning(
  632. 'Session "{session}": Metadata has an anonymous user, but a non-anon user was provided',
  633. [
  634. 'session' => $info,
  635. ] );
  636. return $failHandler();
  637. }
  638. }
  639. // And if we have a token in the metadata, it must match the loaded/provided user.
  640. if ( $metadata['userToken'] !== null &&
  641. $userInfo->getToken() !== $metadata['userToken']
  642. ) {
  643. $this->logger->warning( 'Session "{session}": User token mismatch', [
  644. 'session' => $info,
  645. ] );
  646. return $failHandler();
  647. }
  648. if ( !$userInfo->isVerified() ) {
  649. $newParams['userInfo'] = $userInfo->verified();
  650. }
  651. if ( !empty( $metadata['remember'] ) && !$info->wasRemembered() ) {
  652. $newParams['remembered'] = true;
  653. }
  654. if ( !empty( $metadata['forceHTTPS'] ) && !$info->forceHTTPS() ) {
  655. $newParams['forceHTTPS'] = true;
  656. }
  657. if ( !empty( $metadata['persisted'] ) && !$info->wasPersisted() ) {
  658. $newParams['persisted'] = true;
  659. }
  660. if ( !$info->isIdSafe() ) {
  661. $newParams['idIsSafe'] = true;
  662. }
  663. } else {
  664. // No metadata, so we can't load the provider if one wasn't given.
  665. if ( $info->getProvider() === null ) {
  666. $this->logger->warning(
  667. 'Session "{session}": Null provider and no metadata',
  668. [
  669. 'session' => $info,
  670. ] );
  671. return $failHandler();
  672. }
  673. // If no user was provided and no metadata, it must be anon.
  674. if ( !$info->getUserInfo() ) {
  675. if ( $info->getProvider()->canChangeUser() ) {
  676. $newParams['userInfo'] = UserInfo::newAnonymous();
  677. } else {
  678. $this->logger->info(
  679. 'Session "{session}": No user provided and provider cannot set user',
  680. [
  681. 'session' => $info,
  682. ] );
  683. return $failHandler();
  684. }
  685. } elseif ( !$info->getUserInfo()->isVerified() ) {
  686. // probably just a session timeout
  687. $this->logger->info(
  688. 'Session "{session}": Unverified user provided and no metadata to auth it',
  689. [
  690. 'session' => $info,
  691. ] );
  692. return $failHandler();
  693. }
  694. $data = false;
  695. $metadata = false;
  696. if ( !$info->getProvider()->persistsSessionId() && !$info->isIdSafe() ) {
  697. // The ID doesn't come from the user, so it should be safe
  698. // (and if not, nothing we can do about it anyway)
  699. $newParams['idIsSafe'] = true;
  700. }
  701. }
  702. // Construct the replacement SessionInfo, if necessary
  703. if ( $newParams ) {
  704. $newParams['copyFrom'] = $info;
  705. $info = new SessionInfo( $info->getPriority(), $newParams );
  706. }
  707. // Allow the provider to check the loaded SessionInfo
  708. $providerMetadata = $info->getProviderMetadata();
  709. if ( !$info->getProvider()->refreshSessionInfo( $info, $request, $providerMetadata ) ) {
  710. return $failHandler();
  711. }
  712. if ( $providerMetadata !== $info->getProviderMetadata() ) {
  713. $info = new SessionInfo( $info->getPriority(), [
  714. 'metadata' => $providerMetadata,
  715. 'copyFrom' => $info,
  716. ] );
  717. }
  718. // Give hooks a chance to abort. Combined with the SessionMetadata
  719. // hook, this can allow for tying a session to an IP address or the
  720. // like.
  721. $reason = 'Hook aborted';
  722. if ( !\Hooks::run(
  723. 'SessionCheckInfo',
  724. [ &$reason, $info, $request, $metadata, $data ]
  725. ) ) {
  726. $this->logger->warning( 'Session "{session}": ' . $reason, [
  727. 'session' => $info,
  728. ] );
  729. return $failHandler();
  730. }
  731. return true;
  732. }
  733. /**
  734. * Create a Session corresponding to the passed SessionInfo
  735. * @private For use by a SessionProvider that needs to specially create its
  736. * own Session. Most session providers won't need this.
  737. * @param SessionInfo $info
  738. * @param WebRequest $request
  739. * @return Session
  740. */
  741. public function getSessionFromInfo( SessionInfo $info, WebRequest $request ) {
  742. // @codeCoverageIgnoreStart
  743. if ( defined( 'MW_NO_SESSION' ) ) {
  744. // @phan-suppress-next-line PhanUndeclaredConstant
  745. if ( MW_NO_SESSION === 'warn' ) {
  746. // Undocumented safety case for converting existing entry points
  747. $this->logger->error( 'Sessions are supposed to be disabled for this entry point', [
  748. 'exception' => new \BadMethodCallException( 'Sessions are disabled for this entry point' ),
  749. ] );
  750. } else {
  751. throw new \BadMethodCallException( 'Sessions are disabled for this entry point' );
  752. }
  753. }
  754. // @codeCoverageIgnoreEnd
  755. $id = $info->getId();
  756. if ( !isset( $this->allSessionBackends[$id] ) ) {
  757. if ( !isset( $this->allSessionIds[$id] ) ) {
  758. $this->allSessionIds[$id] = new SessionId( $id );
  759. }
  760. $backend = new SessionBackend(
  761. $this->allSessionIds[$id],
  762. $info,
  763. $this->store,
  764. $this->logger,
  765. $this->config->get( 'ObjectCacheSessionExpiry' )
  766. );
  767. $this->allSessionBackends[$id] = $backend;
  768. $delay = $backend->delaySave();
  769. } else {
  770. $backend = $this->allSessionBackends[$id];
  771. $delay = $backend->delaySave();
  772. if ( $info->wasPersisted() ) {
  773. $backend->persist();
  774. }
  775. if ( $info->wasRemembered() ) {
  776. $backend->setRememberUser( true );
  777. }
  778. }
  779. $request->setSessionId( $backend->getSessionId() );
  780. $session = $backend->getSession( $request );
  781. if ( !$info->isIdSafe() ) {
  782. $session->resetId();
  783. }
  784. \Wikimedia\ScopedCallback::consume( $delay );
  785. return $session;
  786. }
  787. /**
  788. * Deregister a SessionBackend
  789. * @private For use from \MediaWiki\Session\SessionBackend only
  790. * @param SessionBackend $backend
  791. */
  792. public function deregisterSessionBackend( SessionBackend $backend ) {
  793. $id = $backend->getId();
  794. if ( !isset( $this->allSessionBackends[$id] ) || !isset( $this->allSessionIds[$id] ) ||
  795. $this->allSessionBackends[$id] !== $backend ||
  796. $this->allSessionIds[$id] !== $backend->getSessionId()
  797. ) {
  798. throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
  799. }
  800. unset( $this->allSessionBackends[$id] );
  801. // Explicitly do not unset $this->allSessionIds[$id]
  802. }
  803. /**
  804. * Change a SessionBackend's ID
  805. * @private For use from \MediaWiki\Session\SessionBackend only
  806. * @param SessionBackend $backend
  807. */
  808. public function changeBackendId( SessionBackend $backend ) {
  809. $sessionId = $backend->getSessionId();
  810. $oldId = (string)$sessionId;
  811. if ( !isset( $this->allSessionBackends[$oldId] ) || !isset( $this->allSessionIds[$oldId] ) ||
  812. $this->allSessionBackends[$oldId] !== $backend ||
  813. $this->allSessionIds[$oldId] !== $sessionId
  814. ) {
  815. throw new \InvalidArgumentException( 'Backend was not registered with this SessionManager' );
  816. }
  817. $newId = $this->generateSessionId();
  818. unset( $this->allSessionBackends[$oldId], $this->allSessionIds[$oldId] );
  819. $sessionId->setId( $newId );
  820. $this->allSessionBackends[$newId] = $backend;
  821. $this->allSessionIds[$newId] = $sessionId;
  822. }
  823. /**
  824. * Generate a new random session ID
  825. * @return string
  826. */
  827. public function generateSessionId() {
  828. do {
  829. $id = \Wikimedia\base_convert( \MWCryptRand::generateHex( 40 ), 16, 32, 32 );
  830. $key = $this->store->makeKey( 'MWSession', $id );
  831. } while ( isset( $this->allSessionIds[$id] ) || is_array( $this->store->get( $key ) ) );
  832. return $id;
  833. }
  834. /**
  835. * Call setters on a PHPSessionHandler
  836. * @private Use PhpSessionHandler::install()
  837. * @param PHPSessionHandler $handler
  838. */
  839. public function setupPHPSessionHandler( PHPSessionHandler $handler ) {
  840. $handler->setManager( $this, $this->store, $this->logger );
  841. }
  842. /**
  843. * Reset the internal caching for unit testing
  844. * @protected Unit tests only
  845. */
  846. public static function resetCache() {
  847. if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
  848. // @codeCoverageIgnoreStart
  849. throw new MWException( __METHOD__ . ' may only be called from unit tests!' );
  850. // @codeCoverageIgnoreEnd
  851. }
  852. self::$globalSession = null;
  853. self::$globalSessionRequest = null;
  854. }
  855. /** @} */
  856. }