Optimize email sending on password reset
[lhc/web/wiklou.git] / includes / user / PasswordReset.php
1 <?php
2 /**
3 * User password reset helper for MediaWiki.
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 */
22
23 use MediaWiki\Auth\AuthManager;
24 use MediaWiki\Auth\TemporaryPasswordAuthenticationRequest;
25 use MediaWiki\Config\ServiceOptions;
26 use MediaWiki\Logger\LoggerFactory;
27 use MediaWiki\MediaWikiServices;
28 use MediaWiki\Permissions\PermissionManager;
29 use Psr\Log\LoggerAwareInterface;
30 use Psr\Log\LoggerAwareTrait;
31 use Psr\Log\LoggerInterface;
32 use Wikimedia\Rdbms\ILoadBalancer;
33
34 /**
35 * Helper class for the password reset functionality shared by the web UI and the API.
36 *
37 * Requires the TemporaryPasswordPrimaryAuthenticationProvider and the
38 * EmailNotificationSecondaryAuthenticationProvider (or something providing equivalent
39 * functionality) to be enabled.
40 */
41 class PasswordReset implements LoggerAwareInterface {
42 use LoggerAwareTrait;
43
44 /** @var ServiceOptions|Config */
45 protected $config;
46
47 /** @var AuthManager */
48 protected $authManager;
49
50 /** @var PermissionManager */
51 protected $permissionManager;
52
53 /** @var ILoadBalancer */
54 protected $loadBalancer;
55
56 /**
57 * In-process cache for isAllowed lookups, by username.
58 * Contains a StatusValue object
59 * @var MapCacheLRU
60 */
61 private $permissionCache;
62
63 public const CONSTRUCTOR_OPTIONS = [
64 'AllowRequiringEmailForResets',
65 'EnableEmail',
66 'PasswordResetRoutes',
67 ];
68
69 /**
70 * This class is managed by MediaWikiServices, don't instantiate directly.
71 *
72 * @param ServiceOptions|Config $config
73 * @param AuthManager $authManager
74 * @param PermissionManager $permissionManager
75 * @param ILoadBalancer|null $loadBalancer
76 * @param LoggerInterface|null $logger
77 */
78 public function __construct(
79 $config,
80 AuthManager $authManager,
81 PermissionManager $permissionManager,
82 ILoadBalancer $loadBalancer = null,
83 LoggerInterface $logger = null
84 ) {
85 $this->config = $config;
86 $this->authManager = $authManager;
87 $this->permissionManager = $permissionManager;
88
89 if ( !$loadBalancer ) {
90 wfDeprecated( 'Not passing LoadBalancer to ' . __METHOD__, '1.34' );
91 $loadBalancer = MediaWikiServices::getInstance()->getDBLoadBalancer();
92 }
93 $this->loadBalancer = $loadBalancer;
94
95 if ( !$logger ) {
96 wfDeprecated( 'Not passing LoggerInterface to ' . __METHOD__, '1.34' );
97 $logger = LoggerFactory::getInstance( 'authentication' );
98 }
99 $this->logger = $logger;
100
101 $this->permissionCache = new MapCacheLRU( 1 );
102 }
103
104 /**
105 * Check if a given user has permission to use this functionality.
106 * @param User $user
107 * @since 1.29 Second argument for displayPassword removed.
108 * @return StatusValue
109 */
110 public function isAllowed( User $user ) {
111 $status = $this->permissionCache->get( $user->getName() );
112 if ( !$status ) {
113 $resetRoutes = $this->config->get( 'PasswordResetRoutes' );
114 $status = StatusValue::newGood();
115
116 if ( !is_array( $resetRoutes ) || !in_array( true, $resetRoutes, true ) ) {
117 // Maybe password resets are disabled, or there are no allowable routes
118 $status = StatusValue::newFatal( 'passwordreset-disabled' );
119 } elseif (
120 ( $providerStatus = $this->authManager->allowsAuthenticationDataChange(
121 new TemporaryPasswordAuthenticationRequest(), false ) )
122 && !$providerStatus->isGood()
123 ) {
124 // Maybe the external auth plugin won't allow local password changes
125 $status = StatusValue::newFatal( 'resetpass_forbidden-reason',
126 $providerStatus->getMessage() );
127 } elseif ( !$this->config->get( 'EnableEmail' ) ) {
128 // Maybe email features have been disabled
129 $status = StatusValue::newFatal( 'passwordreset-emaildisabled' );
130 } elseif ( !$this->permissionManager->userHasRight( $user, 'editmyprivateinfo' ) ) {
131 // Maybe not all users have permission to change private data
132 $status = StatusValue::newFatal( 'badaccess' );
133 } elseif ( $this->isBlocked( $user ) ) {
134 // Maybe the user is blocked (check this here rather than relying on the parent
135 // method as we have a more specific error message to use here and we want to
136 // ignore some types of blocks)
137 $status = StatusValue::newFatal( 'blocked-mailpassword' );
138 }
139
140 $this->permissionCache->set( $user->getName(), $status );
141 }
142
143 return $status;
144 }
145
146 /**
147 * Do a password reset. Authorization is the caller's responsibility.
148 *
149 * Process the form. At this point we know that the user passes all the criteria in
150 * userCanExecute(), and if the data array contains 'Username', etc, then Username
151 * resets are allowed.
152 *
153 * @since 1.29 Fourth argument for displayPassword removed.
154 * @param User $performingUser The user that does the password reset
155 * @param string|null $username The user whose password is reset
156 * @param string|null $email Alternative way to specify the user
157 * @return StatusValue
158 * @throws LogicException When the user is not allowed to perform the action
159 * @throws MWException On unexpected DB errors
160 */
161 public function execute(
162 User $performingUser, $username = null, $email = null
163 ) {
164 if ( !$this->isAllowed( $performingUser )->isGood() ) {
165 throw new LogicException( 'User ' . $performingUser->getName()
166 . ' is not allowed to reset passwords' );
167 }
168
169 $username = $username ?? '';
170 $email = $email ?? '';
171
172 $resetRoutes = $this->config->get( 'PasswordResetRoutes' )
173 + [ 'username' => false, 'email' => false ];
174 if ( $resetRoutes['username'] && $username ) {
175 $method = 'username';
176 $users = [ $this->lookupUser( $username ) ];
177 } elseif ( $resetRoutes['email'] && $email ) {
178 if ( !Sanitizer::validateEmail( $email ) ) {
179 return StatusValue::newFatal( 'passwordreset-invalidemail' );
180 }
181 $method = 'email';
182 $users = $this->getUsersByEmail( $email );
183 $username = null;
184 } else {
185 // The user didn't supply any data
186 return StatusValue::newFatal( 'passwordreset-nodata' );
187 }
188
189 // Check for hooks (captcha etc), and allow them to modify the users list
190 $error = [];
191 $data = [
192 'Username' => $username,
193 // Email gets set to null for backward compatibility
194 'Email' => $method === 'email' ? $email : null,
195 ];
196 if ( !Hooks::run( 'SpecialPasswordResetOnSubmit', [ &$users, $data, &$error ] ) ) {
197 return StatusValue::newFatal( Message::newFromSpecifier( $error ) );
198 }
199
200 $firstUser = $users[0] ?? null;
201 $requireEmail = $this->config->get( 'AllowRequiringEmailForResets' )
202 && $method === 'username'
203 && $firstUser
204 && $firstUser->getBoolOption( 'requireemail' );
205 if ( $requireEmail ) {
206 if ( $email === '' ) {
207 return StatusValue::newFatal( 'passwordreset-username-email-required' );
208 }
209
210 if ( !Sanitizer::validateEmail( $email ) ) {
211 return StatusValue::newFatal( 'passwordreset-invalidemail' );
212 }
213 }
214
215 // Check against the rate limiter
216 if ( $performingUser->pingLimiter( 'mailpassword' ) ) {
217 return StatusValue::newFatal( 'actionthrottledtext' );
218 }
219
220 if ( !$users ) {
221 if ( $method === 'email' ) {
222 // Don't reveal whether or not an email address is in use
223 return StatusValue::newGood( [] );
224 } else {
225 return StatusValue::newFatal( 'noname' );
226 }
227 }
228
229 if ( !$firstUser instanceof User || !$firstUser->getId() ) {
230 // Don't parse username as wikitext (T67501)
231 return StatusValue::newFatal( wfMessage( 'nosuchuser', wfEscapeWikiText( $username ) ) );
232 }
233
234 // All the users will have the same email address
235 if ( !$firstUser->getEmail() ) {
236 // This won't be reachable from the email route, so safe to expose the username
237 return StatusValue::newFatal( wfMessage( 'noemail',
238 wfEscapeWikiText( $firstUser->getName() ) ) );
239 }
240
241 if ( $requireEmail && $firstUser->getEmail() !== $email ) {
242 // Pretend everything's fine to avoid disclosure
243 return StatusValue::newGood();
244 }
245
246 // We need to have a valid IP address for the hook, but per T20347, we should
247 // send the user's name if they're logged in.
248 $ip = $performingUser->getRequest()->getIP();
249 if ( !$ip ) {
250 return StatusValue::newFatal( 'badipaddress' );
251 }
252
253 Hooks::run( 'User::mailPasswordInternal', [ &$performingUser, &$ip, &$firstUser ] );
254
255 $result = StatusValue::newGood();
256 $reqs = [];
257 foreach ( $users as $user ) {
258 $req = TemporaryPasswordAuthenticationRequest::newRandom();
259 $req->username = $user->getName();
260 $req->mailpassword = true;
261 $req->caller = $performingUser->getName();
262 $status = $this->authManager->allowsAuthenticationDataChange( $req, true );
263 if ( $status->isGood() && $status->getValue() !== 'ignored' ) {
264 $reqs[] = $req;
265 } elseif ( $result->isGood() ) {
266 // only record the first error, to avoid exposing the number of users having the
267 // same email address
268 if ( $status->getValue() === 'ignored' ) {
269 $status = StatusValue::newFatal( 'passwordreset-ignored' );
270 }
271 $result->merge( $status );
272 }
273 }
274
275 $logContext = [
276 'requestingIp' => $ip,
277 'requestingUser' => $performingUser->getName(),
278 'targetUsername' => $username,
279 'targetEmail' => $email,
280 ];
281
282 if ( !$result->isGood() ) {
283 $this->logger->info(
284 "{requestingUser} attempted password reset of {actualUser} but failed",
285 $logContext + [ 'errors' => $result->getErrors() ]
286 );
287 return $result;
288 }
289
290 DeferredUpdates::addUpdate(
291 new SendPasswordResetEmailUpdate( $this->authManager, $reqs, $logContext ),
292 DeferredUpdates::POSTSEND
293 );
294
295 return StatusValue::newGood();
296 }
297
298 /**
299 * Check whether the user is blocked.
300 * Ignores certain types of system blocks that are only meant to force users to log in.
301 * @param User $user
302 * @return bool
303 * @since 1.30
304 */
305 protected function isBlocked( User $user ) {
306 $block = $user->getBlock() ?: $user->getGlobalBlock();
307 if ( !$block ) {
308 return false;
309 }
310 return $block->appliesToPasswordReset();
311 }
312
313 /**
314 * @param string $email
315 * @return User[]
316 * @throws MWException On unexpected database errors
317 */
318 protected function getUsersByEmail( $email ) {
319 $userQuery = User::getQueryInfo();
320 $res = $this->loadBalancer->getConnectionRef( DB_REPLICA )->select(
321 $userQuery['tables'],
322 $userQuery['fields'],
323 [ 'user_email' => $email ],
324 __METHOD__,
325 [],
326 $userQuery['joins']
327 );
328
329 if ( !$res ) {
330 // Some sort of database error, probably unreachable
331 throw new MWException( 'Unknown database error in ' . __METHOD__ );
332 }
333
334 $users = [];
335 foreach ( $res as $row ) {
336 $users[] = User::newFromRow( $row );
337 }
338 return $users;
339 }
340
341 /**
342 * User object creation helper for testability
343 * @codeCoverageIgnore
344 *
345 * @param string $username
346 * @return User|false
347 */
348 protected function lookupUser( $username ) {
349 return User::newFromName( $username );
350 }
351 }