/includes/session/BotPasswordSessionProvider.php

https://github.com/archlinux/archwiki · PHP · 193 lines · 120 code · 21 blank · 52 comment · 14 complexity · 81f04318b9cb2fea7ae9cb21444a254d MD5 · raw file

  1. <?php
  2. /**
  3. * Session provider for bot passwords
  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 BotPassword;
  25. use User;
  26. use WebRequest;
  27. /**
  28. * Session provider for bot passwords
  29. * @since 1.27
  30. */
  31. class BotPasswordSessionProvider extends ImmutableSessionProviderWithCookie {
  32. /**
  33. * @param array $params Keys include:
  34. * - priority: (required) Set the priority
  35. * - sessionCookieName: Session cookie name. Default is '_BPsession'.
  36. * - sessionCookieOptions: Options to pass to WebResponse::setCookie().
  37. */
  38. public function __construct( array $params = [] ) {
  39. if ( !isset( $params['sessionCookieName'] ) ) {
  40. $params['sessionCookieName'] = '_BPsession';
  41. }
  42. parent::__construct( $params );
  43. if ( !isset( $params['priority'] ) ) {
  44. throw new \InvalidArgumentException( __METHOD__ . ': priority must be specified' );
  45. }
  46. if ( $params['priority'] < SessionInfo::MIN_PRIORITY ||
  47. $params['priority'] > SessionInfo::MAX_PRIORITY
  48. ) {
  49. throw new \InvalidArgumentException( __METHOD__ . ': Invalid priority' );
  50. }
  51. $this->priority = $params['priority'];
  52. }
  53. public function provideSessionInfo( WebRequest $request ) {
  54. // Only relevant for the API
  55. if ( !defined( 'MW_API' ) ) {
  56. return null;
  57. }
  58. // Enabled?
  59. if ( !$this->config->get( 'EnableBotPasswords' ) ) {
  60. return null;
  61. }
  62. // Have a session ID?
  63. $id = $this->getSessionIdFromCookie( $request );
  64. if ( $id === null ) {
  65. return null;
  66. }
  67. return new SessionInfo( $this->priority, [
  68. 'provider' => $this,
  69. 'id' => $id,
  70. 'persisted' => true
  71. ] );
  72. }
  73. public function newSessionInfo( $id = null ) {
  74. // We don't activate by default
  75. return null;
  76. }
  77. /**
  78. * Create a new session for a request
  79. * @param User $user
  80. * @param BotPassword $bp
  81. * @param WebRequest $request
  82. * @return Session
  83. */
  84. public function newSessionForRequest( User $user, BotPassword $bp, WebRequest $request ) {
  85. $id = $this->getSessionIdFromCookie( $request );
  86. $info = new SessionInfo( SessionInfo::MAX_PRIORITY, [
  87. 'provider' => $this,
  88. 'id' => $id,
  89. 'userInfo' => UserInfo::newFromUser( $user, true ),
  90. 'persisted' => $id !== null,
  91. 'metadata' => [
  92. 'centralId' => $bp->getUserCentralId(),
  93. 'appId' => $bp->getAppId(),
  94. 'token' => $bp->getToken(),
  95. 'rights' => \MWGrants::getGrantRights( $bp->getGrants() ),
  96. ],
  97. ] );
  98. $session = $this->getManager()->getSessionFromInfo( $info, $request );
  99. $session->persist();
  100. return $session;
  101. }
  102. /**
  103. * @inheritDoc
  104. * @phan-param array &$metadata
  105. */
  106. public function refreshSessionInfo( SessionInfo $info, WebRequest $request, &$metadata ) {
  107. $missingKeys = array_diff(
  108. [ 'centralId', 'appId', 'token' ],
  109. array_keys( $metadata )
  110. );
  111. if ( $missingKeys ) {
  112. $this->logger->info( 'Session "{session}": Missing metadata: {missing}', [
  113. 'session' => $info->__toString(),
  114. 'missing' => implode( ', ', $missingKeys ),
  115. ] );
  116. return false;
  117. }
  118. $bp = BotPassword::newFromCentralId( $metadata['centralId'], $metadata['appId'] );
  119. if ( !$bp ) {
  120. $this->logger->info(
  121. 'Session "{session}": No BotPassword for {centralId} {appId}',
  122. [
  123. 'session' => $info->__toString(),
  124. 'centralId' => $metadata['centralId'],
  125. 'appId' => $metadata['appId'],
  126. ] );
  127. return false;
  128. }
  129. if ( !hash_equals( $metadata['token'], $bp->getToken() ) ) {
  130. $this->logger->info( 'Session "{session}": BotPassword token check failed', [
  131. 'session' => $info->__toString(),
  132. 'centralId' => $metadata['centralId'],
  133. 'appId' => $metadata['appId'],
  134. ] );
  135. return false;
  136. }
  137. $status = $bp->getRestrictions()->check( $request );
  138. if ( !$status->isOK() ) {
  139. $this->logger->info(
  140. 'Session "{session}": Restrictions check failed',
  141. [
  142. 'session' => $info->__toString(),
  143. 'restrictions' => $status->getValue(),
  144. 'centralId' => $metadata['centralId'],
  145. 'appId' => $metadata['appId'],
  146. ] );
  147. return false;
  148. }
  149. // Update saved rights
  150. $metadata['rights'] = \MWGrants::getGrantRights( $bp->getGrants() );
  151. return true;
  152. }
  153. /**
  154. * @codeCoverageIgnore
  155. * @inheritDoc
  156. */
  157. public function preventSessionsForUser( $username ) {
  158. BotPassword::removeAllPasswordsForUser( $username );
  159. }
  160. public function getAllowedUserRights( SessionBackend $backend ) {
  161. if ( $backend->getProvider() !== $this ) {
  162. throw new \InvalidArgumentException( 'Backend\'s provider isn\'t $this' );
  163. }
  164. $data = $backend->getProviderMetadata();
  165. if ( $data && isset( $data['rights'] ) && is_array( $data['rights'] ) ) {
  166. return $data['rights'];
  167. }
  168. // Should never happen
  169. $this->logger->debug( __METHOD__ . ': No provider metadata, returning no rights allowed' );
  170. return [];
  171. }
  172. }