Debian Codegraph @

tests/phpunit/unit/includes/mail/EmailUserTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Unit\Mail;
4
5 use Generator;
6 use MediaWiki\Block\AbstractBlock;
7 use MediaWiki\Config\ServiceOptions;
8 use MediaWiki\Language\RawMessage;
9 use MediaWiki\Mail\EmailUser;
10 use MediaWiki\Mail\IEmailer;
11 use MediaWiki\MainConfigNames;
12 use MediaWiki\Permissions\Authority;
13 use MediaWiki\Permissions\PermissionStatus;
14 use MediaWiki\User\CentralId\CentralIdLookup;
15 use MediaWiki\User\Options\UserOptionsLookup;
16 use MediaWiki\User\User;
17 use MediaWiki\User\UserFactory;
18 use MediaWiki\User\UserIdentity;
19 use MediaWikiUnitTestCase;
20 use StatusValue;
21 use Wikimedia\Message\IMessageFormatterFactory;
22 use Wikimedia\Message\ITextFormatter;
23
24 /**
25 * @group Mail
26 * @covers \MediaWiki\Mail\EmailUser
27 */
28 class EmailUserTest extends MediaWikiUnitTestCase {
29 private function getEmailUser(
30 Authority $sender,
31 ?UserOptionsLookup $userOptionsLookup = null,
32 ?CentralIdLookup $centralIdLookup = null,
33 ?UserFactory $userFactory = null,
34 array $configOverrides = [],
35 array $hooks = [],
36 ?IEmailer $emailer = null
37 ): EmailUser {
38 $options = new ServiceOptions(
39 EmailUser::CONSTRUCTOR_OPTIONS,
40 $configOverrides + [
41 MainConfigNames::EnableEmail => true,
42 MainConfigNames::EnableUserEmail => true,
43 MainConfigNames::EnableSpecialMute => true,
44 MainConfigNames::PasswordSender => '[email protected]',
45 MainConfigNames::UserEmailUseReplyTo => true,
46 ]
47 );
48
49 return new EmailUser(
50 $options,
51 $this->createHookContainer( $hooks ),
52 $userOptionsLookup ?? $this->createMock( UserOptionsLookup::class ),
53 $centralIdLookup ?? $this->createMock( CentralIdLookup::class ),
54 $userFactory ?? $this->createMock( UserFactory::class ),
55 $emailer ?? $this->createMock( IEmailer::class ),
56 $this->createMock( IMessageFormatterFactory::class ),
57 $this->createMock( ITextFormatter::class ),
58 $sender
59 );
60 }
61
62 /**
63 * @dataProvider provideValidateTarget
64 */
65 public function testValidateTarget(
66 User $target,
67 User $sender,
68 StatusValue $expected,
69 ?UserOptionsLookup $userOptionsLookup = null,
70 ?CentralIdLookup $centralIdLookup = null
71 ) {
72 $userFactory = $this->createMock( UserFactory::class );
73 $userFactory->method( 'newFromAuthority' )->willReturn( $sender );
74 $userFactory->method( 'newFromUserIdentity' )->willReturn( $target );
75 $emailUser = $this->getEmailUser( $sender, $userOptionsLookup, $centralIdLookup, $userFactory );
76 $this->assertEquals( $expected, $emailUser->validateTarget( $target ) );
77 }
78
79 public function provideValidateTarget(): Generator {
80 $noopUserMock = $this->createMock( User::class );
81 $noopUserMock->method( 'getUser' )->willReturnSelf();
82 $validTarget = $this->getValidTarget();
83
84 $anonTarget = $this->createMock( User::class );
85 $anonTarget->expects( $this->atLeastOnce() )->method( 'getId' )->willReturn( 0 );
86 $anonTarget->method( 'getUser' )->willReturnSelf();
87 yield 'Target has user ID 0' => [ $anonTarget, $noopUserMock, StatusValue::newFatal( 'emailnotarget' ) ];
88
89 $emailNotConfirmedTarget = $this->createMock( User::class );
90 $emailNotConfirmedTarget->method( 'getId' )->willReturn( 1 );
91 $emailNotConfirmedTarget->expects( $this->atLeastOnce() )->method( 'isEmailConfirmed' )->willReturn( false );
92 $emailNotConfirmedTarget->method( 'getUser' )->willReturnSelf();
93 yield 'Target does not have confirmed email' => [
94 $emailNotConfirmedTarget,
95 $noopUserMock,
96 StatusValue::newFatal( 'noemailtext' )
97 ];
98
99 $cannotReceiveEmailsTarget = $this->createMock( User::class );
100 $cannotReceiveEmailsTarget->method( 'getId' )->willReturn( 1 );
101 $cannotReceiveEmailsTarget->method( 'isEmailConfirmed' )->willReturn( true );
102 $cannotReceiveEmailsTarget->expects( $this->atLeastOnce() )->method( 'canReceiveEmail' )->willReturn( false );
103 $cannotReceiveEmailsTarget->method( 'getUser' )->willReturnSelf();
104 yield 'Target cannot receive emails' => [
105 $cannotReceiveEmailsTarget,
106 $noopUserMock,
107 StatusValue::newFatal( 'nowikiemailtext' )
108 ];
109
110 $newbieSender = $this->createMock( User::class );
111 $newbieSender->expects( $this->atLeastOnce() )->method( 'isNewbie' )->willReturn( true );
112 $noNewbieEmailsOptionsLookup = $this->createMock( UserOptionsLookup::class );
113 $noNewbieEmailsOptionsLookup->expects( $this->atLeastOnce() )
114 ->method( 'getOption' )
115 ->with( $validTarget, 'email-allow-new-users' )
116 ->willReturn( false );
117 yield 'Target does not allow emails from newbie and sender is newbie' => [
118 $validTarget,
119 $newbieSender,
120 StatusValue::newFatal( 'nowikiemailtext' ),
121 $noNewbieEmailsOptionsLookup
122 ];
123
124 $senderCentralID = 42;
125 $muteListOptionsLookup = $this->createMock( UserOptionsLookup::class );
126 $muteListOptionsLookup->expects( $this->atLeast( 2 ) )
127 ->method( 'getOption' )
128 ->willReturnCallback(
129 function ( UserIdentity $user, string $option ) use ( $validTarget, $senderCentralID ) {
130 $this->assertSame( $validTarget->getUser(), $user );
131 return $option === 'email-blacklist' ? (string)$senderCentralID : null;
132 }
133 );
134 $centralIdLookup = $this->createMock( CentralIdLookup::class );
135 $centralIdLookup->expects( $this->atLeastOnce() )
136 ->method( 'centralIdFromLocalUser' )
137 ->with( $noopUserMock )
138 ->willReturn( $senderCentralID );
139 yield 'Target muted the sender' => [
140 $validTarget,
141 $noopUserMock,
142 StatusValue::newFatal( 'nowikiemailtext' ),
143 $muteListOptionsLookup,
144 $centralIdLookup
145 ];
146
147 yield 'Valid' => [ $validTarget, $noopUserMock, StatusValue::newGood() ];
148 }
149
150 /**
151 * @dataProvider provideCanSend
152 * @dataProvider provideAuthorizeSend
153 */
154 public function testAuthorizeSend(
155 User $performerUser,
156 StatusValue $expected,
157 array $configOverrides = [],
158 array $hooks = [],
159 bool $expectDeprecation = false
160 ) {
161 $userFactory = $this->createMock( UserFactory::class );
162 $userFactory->method( 'newFromAuthority' )->willReturn( $performerUser );
163 if ( $expectDeprecation ) {
164 $this->expectDeprecationAndContinue( '/Use of EmailUserPermissionsErrors hook/' );
165 }
166 $emailUser = $this->getEmailUser( $performerUser, null, null, $userFactory, $configOverrides, $hooks );
167 $this->assertEquals( $expected, $emailUser->authorizeSend() );
168 }
169
170 /**
171 * @dataProvider provideCanSend
172 */
173 public function testCanSend(
174 User $performerUser,
175 StatusValue $expected,
176 array $configOverrides = [],
177 array $hooks = [],
178 bool $expectDeprecation = false
179 ) {
180 $userFactory = $this->createMock( UserFactory::class );
181 $userFactory->method( 'newFromAuthority' )->willReturn( $performerUser );
182 if ( $expectDeprecation ) {
183 $this->expectDeprecationAndContinue( '/Use of EmailUserPermissionsErrors hook/' );
184 }
185 $emailUser = $this->getEmailUser( $performerUser, null, null, $userFactory, $configOverrides, $hooks );
186 $this->assertEquals( $expected, $emailUser->canSend( 'some-token' ) );
187 }
188
189 private function newMockUser( $methods = [] ) {
190 $methods['isEmailConfirmed'] = $methods['isEmailConfirmed'] ?? true;
191 $methods['isAllowed'] = $methods['isAllowed'] ?? true;
192 $methods['isDefinitelyAllowed'] = $methods['isDefinitelyAllowed'] ?? $methods['isAllowed'];
193 $methods['authorizeAction'] = $methods['authorizeAction'] ?? $methods['isDefinitelyAllowed'];
194
195 $user = $this->createMock( User::class );
196
197 foreach ( $methods as $name => $value ) {
198 if ( is_callable( $value ) ) {
199 $user->method( $name )->willReturnCallback( $value );
200 } else {
201 $user->method( $name )->willReturn( $value );
202 }
203 }
204
205 return $user;
206 }
207
208 public function provideCanSend(): Generator {
209 $validSender = $this->newMockUser();
210
211 yield 'Emails disabled' => [
212 $validSender,
213 StatusValue::newFatal( 'usermaildisabled' ),
214 [ MainConfigNames::EnableEmail => false ]
215 ];
216
217 yield 'User emails disabled' => [
218 $validSender,
219 StatusValue::newFatal( 'usermaildisabled' ),
220 [ MainConfigNames::EnableUserEmail => false ]
221 ];
222
223 $noEmailSender = $this->newMockUser( [ 'isEmailConfirmed' => false ] );
224 yield 'Sender does not have an email' => [
225 $noEmailSender,
226 StatusValue::newFatal( 'mailnologin' )
227 ];
228
229 $notAllowedValidSender = $this->newMockUser( [
230 'isAllowed' => false,
231 'isDefinitelyAllowed' => static function ( $user, StatusValue $status ) {
232 $status->fatal( 'badaccess' );
233 return false;
234 }
235 ] );
236
237 yield 'Sender is not allowed to send emails' => [
238 $notAllowedValidSender,
239 PermissionStatus::newFatal( 'badaccess' )
240 ];
241
242 $block = $this->createMock( AbstractBlock::class );
243 $block->expects( $this->atLeastOnce() )
244 ->method( 'appliesToRight' )
245 ->with( 'sendemail' )
246 ->willReturn( true );
247
248 $blockedSender = $this->newMockUser( [
249 'getBlock' => $block,
250 'isDefinitelyAllowed' => static function ( $action, PermissionStatus $status )
251 use ( $block ) {
252 if ( $action === 'sendemail' ) {
253 $status->setBlock( $block );
254 return false;
255 }
256 return true;
257 },
258 ] );
259
260 $blockedPermission = PermissionStatus::newEmpty();
261 $blockedPermission->setBlock( $block );
262
263 yield 'Sender is blocked from emailing users' => [
264 $blockedSender,
265 $blockedPermission
266 ];
267
268 $userCanSendEmailError = [ 'first-hook-error', 'first-hook-error-text', [] ];
269 $userCanSendEmailHooks = [
270 'UserCanSendEmail' => static function ( $user, &$err ) use ( $userCanSendEmailError ) {
271 $err = $userCanSendEmailError;
272 }
273 ];
274 $expectedStatusFirstHook = StatusValue::newFatal( $userCanSendEmailError[1], ...$userCanSendEmailError[2] );
275 $expectedStatusFirstHook->value = $userCanSendEmailError[0];
276 yield 'UserCanSendEmail hook error' => [
277 $validSender,
278 $expectedStatusFirstHook,
279 [],
280 $userCanSendEmailHooks
281 ];
282
283 $emailUserPermissionsErrorsError = [ 'second-hook-error', 'second-hook-error-text', [] ];
284 $emailUserPermissionsErrorsHooks = [
285 'EmailUserPermissionsErrors' =>
286 static function ( $user, $token, &$err ) use ( $emailUserPermissionsErrorsError ) {
287 $err = $emailUserPermissionsErrorsError;
288 }
289 ];
290 $expectedStatusSecondHook = StatusValue::newFatal(
291 $emailUserPermissionsErrorsError[1],
292 ...$emailUserPermissionsErrorsError[2]
293 );
294 $expectedStatusSecondHook->value = $emailUserPermissionsErrorsError[0];
295 yield 'EmailUserPermissionsErrors hook error' => [
296 $validSender,
297 $expectedStatusSecondHook,
298 [],
299 $emailUserPermissionsErrorsHooks,
300 true
301 ];
302
303 yield 'Successful' => [ $validSender, StatusValue::newGood() ];
304 }
305
306 public function provideAuthorizeSend(): Generator {
307 $ratelimitedSender = $this->newMockUser( [
308 'pingLimiter' => true,
309 'isDefinitelyAllowed' => static function ( $action, PermissionStatus $status ) {
310 if ( $action === 'sendemail' ) {
311 $status->setRateLimitExceeded();
312 return false;
313 }
314 return true;
315 }
316 ] );
317
318 $rateLimitStatus = PermissionStatus::newEmpty();
319 $rateLimitStatus->setRateLimitExceeded();
320
321 yield 'Sender is rate-limited' => [
322 $ratelimitedSender,
323 $rateLimitStatus
324 ];
325
326 $validSender = $this->newMockUser();
327
328 $emailUserAuthorizeSendError = 'my-hook-error';
329 $emailUserAuthorizeSendHooks = [
330 'EmailUserAuthorizeSend' =>
331 static function ( $user, StatusValue $status ) use ( $emailUserAuthorizeSendError ) {
332 $status->fatal( $emailUserAuthorizeSendError );
333 return false;
334 }
335 ];
336
337 yield 'EmailUserAuthorizeSend hook error' => [
338 $validSender,
339 PermissionStatus::newFatal( $emailUserAuthorizeSendError ),
340 [],
341 $emailUserAuthorizeSendHooks
342 ];
343 }
344
345 /**
346 * @dataProvider provideSubmit
347 */
348 public function testSubmit(
349 User $target,
350 Authority $sender,
351 StatusValue $expected,
352 array $hooks = [],
353 ?IEmailer $emailer = null
354 ) {
355 $userFactory = $this->createMock( UserFactory::class );
356 $userFactory->method( 'newFromUserIdentity' )
357 ->with( $target )
358 ->willReturn( $target );
359 $emailUser = $this->getEmailUser( $sender, null, null, $userFactory, [], $hooks, $emailer );
360 $res = $emailUser->sendEmailUnsafe(
361 $target,
362 'subject',
363 'text',
364 false,
365 'qqx'
366 );
367 $this->assertEquals( $expected, $res );
368 }
369
370 public function provideSubmit(): Generator {
371 $validSender = $this->createMock( Authority::class );
372 $validTarget = $this->getValidTarget();
373
374 $invalidTarget = $this->createMock( User::class );
375 $invalidTarget->method( 'getId' )->willReturn( 0 );
376 $invalidTarget->method( 'getUser' )->willReturnSelf();
377 yield 'Invalid target' => [ $invalidTarget, $validSender, StatusValue::newFatal( 'emailnotarget' ) ];
378
379 $hookStatusError = StatusValue::newFatal( 'some-hook-error' );
380 $emailUserHookUsingStatusHooks = [
381 'EmailUser' => static function ( $a, $b, $c, $d, &$err ) use ( $hookStatusError ) {
382 $err = $hookStatusError;
383 return false;
384 }
385 ];
386 yield 'EmailUserHook error as a Status' => [
387 $validTarget,
388 $validSender,
389 $hookStatusError,
390 $emailUserHookUsingStatusHooks
391 ];
392
393 $emailUserHookUsingBooleanFalseHooks = [
394 'EmailUser' => static function ( $a, $b, $c, $d, &$err ) {
395 $err = false;
396 return false;
397 }
398 ];
399 yield 'EmailUserHook error as boolean false' => [
400 $validTarget,
401 $validSender,
402 StatusValue::newFatal( 'hookaborted' ),
403 $emailUserHookUsingBooleanFalseHooks
404 ];
405
406 $emailUserHookUsingBooleanTrueHooks = [
407 'EmailUser' => static function ( $a, $b, $c, $d, &$err ) {
408 $err = true;
409 return false;
410 }
411 ];
412 yield 'EmailUserHook error as boolean true' => [
413 $validTarget,
414 $validSender,
415 StatusValue::newGood(),
416 $emailUserHookUsingBooleanTrueHooks
417 ];
418
419 $hookError = 'a-hook-error';
420 $emailUserHookUsingArrayHooks = [
421 'EmailUser' => static function ( $a, $b, $c, $d, &$err ) use ( $hookError ) {
422 $err = [ $hookError ];
423 return false;
424 }
425 ];
426 yield 'EmailUserHook error as array' => [
427 $validTarget,
428 $validSender,
429 StatusValue::newFatal( $hookError ),
430 $emailUserHookUsingArrayHooks
431 ];
432
433 $hookErrorMsg = new RawMessage( 'Some hook error' );
434 $emailUserHookUsingMessageHooks = [
435 'EmailUser' => static function ( $a, $b, $c, $d, &$err ) use ( $hookErrorMsg ) {
436 $err = $hookErrorMsg;
437 return false;
438 }
439 ];
440 yield 'EmailUserHook error as MessageSpecifier' => [
441 $validTarget,
442 $validSender,
443 StatusValue::newFatal( $hookErrorMsg ),
444 $emailUserHookUsingMessageHooks
445 ];
446
447 $emailUserSendEmailHookError = 'some-pretty-hook-error';
448 $emailUserHookUsingStatusHooks = [
449 'EmailUserSendEmail' => static function ( $a, $b, $c, $d, $e, $f, StatusValue $status )
450 use ( $emailUserSendEmailHookError )
451 {
452 $status->fatal( $emailUserSendEmailHookError );
453 return false;
454 }
455 ];
456 yield 'EmailUserSendEmail error as a Status' => [
457 $validTarget,
458 $validSender,
459 StatusValue::newFatal( $emailUserSendEmailHookError ),
460 $emailUserHookUsingStatusHooks
461 ];
462
463 $emailerErrorStatus = StatusValue::newFatal( 'emailer-error' );
464 $errorEmailer = $this->createMock( IEmailer::class );
465 $errorEmailer->expects( $this->atLeastOnce() )->method( 'send' )->willReturn( $emailerErrorStatus );
466 yield 'Error in the Emailer' => [
467 $validTarget,
468 $validSender,
469 $emailerErrorStatus,
470 [],
471 $errorEmailer
472 ];
473
474 $emailerSuccessStatus = StatusValue::newGood( 42 );
475 $successEmailer = $this->createMock( IEmailer::class );
476 $successEmailer->expects( $this->atLeastOnce() )->method( 'send' )->willReturn( $emailerSuccessStatus );
477 yield 'Successful' => [
478 $validTarget,
479 $validSender,
480 $emailerSuccessStatus,
481 [],
482 $successEmailer
483 ];
484 }
485
486 private function getValidTarget(): User {
487 $validTarget = $this->createMock( User::class );
488 $validTarget->method( 'getId' )->willReturn( 1 );
489 $validTarget->method( 'isEmailConfirmed' )->willReturn( true );
490 $validTarget->method( 'canReceiveEmail' )->willReturn( true );
491 $validTarget->method( 'getUser' )->willReturnSelf();
492 return $validTarget;
493 }
494 }