Debian Codegraph @

tests/phpunit/includes/auth/AuthManagerTest.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Tests\Auth;
4
5 use Closure;
6 use DatabaseLogEntry;
7 use DomainException;
8 use DummySessionProvider;
9 use DynamicPropertyTestHelper;
10 use Exception;
11 use InvalidArgumentException;
12 use LogicException;
13 use MediaWiki\Auth\AbstractPreAuthenticationProvider;
14 use MediaWiki\Auth\AbstractPrimaryAuthenticationProvider;
15 use MediaWiki\Auth\AbstractSecondaryAuthenticationProvider;
16 use MediaWiki\Auth\AuthenticationProvider;
17 use MediaWiki\Auth\AuthenticationRequest;
18 use MediaWiki\Auth\AuthenticationResponse;
19 use MediaWiki\Auth\AuthManager;
20 use MediaWiki\Auth\ConfirmLinkSecondaryAuthenticationProvider;
21 use MediaWiki\Auth\CreatedAccountAuthenticationRequest;
22 use MediaWiki\Auth\CreateFromLoginAuthenticationRequest;
23 use MediaWiki\Auth\CreationReasonAuthenticationRequest;
24 use MediaWiki\Auth\Hook\AuthManagerLoginAuthenticateAuditHook;
25 use MediaWiki\Auth\Hook\AuthManagerVerifyAuthenticationHook;
26 use MediaWiki\Auth\Hook\LocalUserCreatedHook;
27 use MediaWiki\Auth\Hook\SecuritySensitiveOperationStatusHook;
28 use MediaWiki\Auth\Hook\UserLoggedInHook;
29 use MediaWiki\Auth\PasswordAuthenticationRequest;
30 use MediaWiki\Auth\PrimaryAuthenticationProvider;
31 use MediaWiki\Auth\RememberMeAuthenticationRequest;
32 use MediaWiki\Auth\TemporaryPasswordAuthenticationRequest;
33 use MediaWiki\Auth\UserDataAuthenticationRequest;
34 use MediaWiki\Auth\UsernameAuthenticationRequest;
35 use MediaWiki\Block\BlockManager;
36 use MediaWiki\Block\DatabaseBlock;
37 use MediaWiki\Block\Restriction\PageRestriction;
38 use MediaWiki\Block\SystemBlock;
39 use MediaWiki\Config\Config;
40 use MediaWiki\Config\HashConfig;
41 use MediaWiki\Config\ServiceOptions;
42 use MediaWiki\Context\RequestContext;
43 use MediaWiki\HookContainer\HookContainer;
44 use MediaWiki\HookContainer\StaticHookRegistry;
45 use MediaWiki\Language\Language;
46 use MediaWiki\Languages\LanguageConverterFactory;
47 use MediaWiki\Logger\LoggerFactory;
48 use MediaWiki\MainConfigNames;
49 use MediaWiki\MediaWikiServices;
50 use MediaWiki\Message\Message;
51 use MediaWiki\Request\FauxRequest;
52 use MediaWiki\Request\WebRequest;
53 use MediaWiki\Session\SessionInfo;
54 use MediaWiki\Session\SessionManager;
55 use MediaWiki\Session\UserInfo;
56 use MediaWiki\Status\Status;
57 use MediaWiki\Tests\Session\TestUtils;
58 use MediaWiki\User\BotPasswordStore;
59 use MediaWiki\User\Options\UserOptionsManager;
60 use MediaWiki\User\User;
61 use MediaWiki\User\UserFactory;
62 use MediaWiki\User\UserIdentityLookup;
63 use MediaWiki\User\UserNameUtils;
64 use MediaWiki\Watchlist\WatchlistManager;
65 use MediaWikiIntegrationTestCase;
66 use ObjectCacheFactory;
67 use PHPUnit\Framework\Assert;
68 use PHPUnit\Framework\MockObject\Builder\InvocationMocker;
69 use PHPUnit\Framework\MockObject\MockObject;
70 use PHPUnit\Framework\MockObject\Rule\InvocationOrder;
71 use Psr\Container\ContainerInterface;
72 use Psr\Log\LoggerInterface;
73 use Psr\Log\LogLevel;
74 use Psr\Log\NullLogger;
75 use ReflectionClass;
76 use RuntimeException;
77 use StatusValue;
78 use TestLogger;
79 use TestUser;
80 use UnexpectedValueException;
81 use Wikimedia\Message\MessageSpecifier;
82 use Wikimedia\ObjectCache\HashBagOStuff;
83 use Wikimedia\ObjectFactory\ObjectFactory;
84 use Wikimedia\Rdbms\ILoadBalancer;
85 use Wikimedia\Rdbms\ReadOnlyMode;
86 use Wikimedia\ScopedCallback;
87 use Wikimedia\TestingAccessWrapper;
88
89 /**
90 * @group AuthManager
91 * @group Database
92 * @covers \MediaWiki\Auth\AuthManager
93 */
94 class AuthManagerTest extends MediaWikiIntegrationTestCase {
95 /** @var WebRequest */
96 protected $request;
97 /** @var Config */
98 protected $config;
99 /** @var ObjectFactory */
100 protected $objectFactory;
101 /** @var ReadOnlyMode */
102 protected $readOnlyMode;
103
104 /** @var HookContainer */
105 private $hookContainer;
106
107 /** @var UserNameUtils */
108 protected $userNameUtils;
109
110 /** @var LoggerInterface */
111 protected $logger;
112
113 /** @var AbstractPreAuthenticationProvider&MockObject[] */
114 protected $preauthMocks = [];
115 /** @var AbstractPrimaryAuthenticationProvider&MockObject[] */
116 protected $primaryauthMocks = [];
117 /** @var AbstractSecondaryAuthenticationProvider&MockObject[] */
118 protected $secondaryauthMocks = [];
119
120 /** @var AuthManager */
121 protected $manager;
122 /** @var TestingAccessWrapper|AuthManager */
123 protected $managerPriv;
124
125 /** @var BlockManager */
126 private $blockManager;
127
128 /** @var WatchlistManager */
129 private $watchlistManager;
130
131 /** @var ILoadBalancer */
132 private $loadBalancer;
133
134 /** @var Language */
135 private $contentLanguage;
136
137 /** @var LanguageConverterFactory */
138 private $languageConverterFactory;
139
140 /** @var BotPasswordStore */
141 private $botPasswordStore;
142
143 /** @var UserFactory */
144 private $userFactory;
145
146 /** @var UserIdentityLookup */
147 private $userIdentityLookup;
148
149 /** @var UserOptionsManager */
150 private $userOptionsManager;
151
152 /** @var ObjectCacheFactory */
153 private $objectCacheFactory;
154
155 /**
156 * Registers a mock hook.
157 * Note this should be called after initializeManager( true ) as that removes mock hooks.
158 * @param string $hook
159 * @param string $hookInterface
160 * @param InvocationOrder $expect From $this->once(), $this->never(), etc.
161 * @return InvocationMocker $mock->expects( $expect )->method( ... ).
162 */
163 protected function hook( $hook, $hookInterface, $expect ) {
164 $mock = $this->getMockBuilder( $hookInterface )
165 ->onlyMethods( [ "on$hook" ] )
166 ->getMock();
167 $this->hookContainer->register( $hook, $mock );
168 return $mock->expects( $expect )->method( "on$hook" );
169 }
170
171 /**
172 * Unsets a hook
173 * @param string $hook
174 */
175 protected function unhook( $hook ) {
176 $this->hookContainer->clear( $hook );
177 }
178
179 /**
180 * Ensure a value is a clean Message object
181 *
182 * @param string|Message $key
183 * @param array $params
184 *
185 * @return Message
186 */
187 protected function message( $key, $params = [] ) {
188 if ( $key === null ) {
189 return null;
190 }
191 if ( $key instanceof MessageSpecifier ) {
192 $params = $key->getParams();
193 $key = $key->getKey();
194 }
195 return new Message( $key, $params,
196 MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'en' ) );
197 }
198
199 /**
200 * Test two AuthenticationResponses for equality. We don't want to use regular assertEquals
201 * because that recursively compares members, which leads to false negatives if e.g. Language
202 * caches are reset.
203 *
204 * @param AuthenticationResponse $expected
205 * @param AuthenticationResponse $actual
206 * @param string $msg
207 */
208 private function assertResponseEquals(
209 AuthenticationResponse $expected, AuthenticationResponse $actual, $msg = ''
210 ) {
211 foreach ( ( new ReflectionClass( $expected ) )->getProperties() as $prop ) {
212 $name = $prop->getName();
213 $usedMsg = ltrim( "$msg ($name)" );
214 if ( $name === 'message' && $expected->message ) {
215 $this->assertSame( $expected->message->__serialize(), $actual->message->__serialize(),
216 $usedMsg );
217 } else {
218 $this->assertEquals( $expected->$name, $actual->$name, $usedMsg );
219 }
220 }
221 }
222
223 /**
224 * Initialize the AuthManagerConfig variable in $this->config
225 *
226 * Uses data from the various 'mocks' fields.
227 */
228 protected function initializeConfig() {
229 $config = [
230 'preauth' => [
231 ],
232 'primaryauth' => [
233 ],
234 'secondaryauth' => [
235 ],
236 ];
237
238 foreach ( [ 'preauth', 'primaryauth', 'secondaryauth' ] as $type ) {
239 $key = $type . 'Mocks';
240 foreach ( $this->$key as $mock ) {
241 $config[$type][$mock->getUniqueId()] = [ 'factory' => static function () use ( $mock ) {
242 return $mock;
243 } ];
244 }
245 }
246
247 $this->config->set( MainConfigNames::AuthManagerConfig, $config );
248 $this->config->set( MainConfigNames::LanguageCode, 'en' );
249 $this->config->set( MainConfigNames::NewUserLog, false );
250 $this->config->set( MainConfigNames::RememberMe, RememberMeAuthenticationRequest::CHOOSE_REMEMBER );
251 }
252
253 /**
254 * Initialize $this->manager
255 * @param bool $regen Force a call to $this->initializeConfig()
256 */
257 protected function initializeManager( $regen = false ) {
258 // TODO clean this up, don't need to re fetch the services each time
259 if ( $regen || !$this->config ) {
260 $this->config = new HashConfig();
261 }
262 if ( $regen || !$this->request ) {
263 $this->request = new FauxRequest();
264 }
265 if ( $regen || !$this->objectFactory ) {
266 $services = $this->createNoOpAbstractMock( ContainerInterface::class );
267 $this->objectFactory = new ObjectFactory( $services );
268 }
269 if ( $regen || !$this->readOnlyMode ) {
270 $this->readOnlyMode = $this->getServiceContainer()->getReadOnlyMode();
271 }
272 if ( $regen || !$this->blockManager ) {
273 // Override BlockManager::checkHost. Formerly testAuthorizeCreateAccount_DNSBlacklist
274 // required *.localhost to resolve as 127.0.0.1, but that is system-dependent.
275 $this->blockManager = new class(
276 new ServiceOptions(
277 BlockManager::CONSTRUCTOR_OPTIONS,
278 $this->getServiceContainer()->getMainConfig()
279 ),
280 $this->getServiceContainer()->getUserFactory(),
281 $this->getServiceContainer()->getUserIdentityUtils(),
282 LoggerFactory::getInstance( 'BlockManager' ),
283 $this->getServiceContainer()->getHookContainer(),
284 $this->getServiceContainer()->getDatabaseBlockStore(),
285 $this->getServiceContainer()->getProxyLookup()
286 ) extends BlockManager {
287 protected function checkHost( $hostname ) {
288 return '127.0.0.1';
289 }
290 };
291 }
292 if ( $regen || !$this->watchlistManager ) {
293 $this->watchlistManager = $this->getServiceContainer()->getWatchlistManager();
294 }
295 if ( $regen || !$this->hookContainer ) {
296 // Set up a HookContainer we control
297 $this->hookContainer = new HookContainer(
298 new StaticHookRegistry( [], [], [] ),
299 $this->objectFactory
300 );
301 }
302 if ( $regen || !$this->userNameUtils ) {
303 $this->userNameUtils = $this->getServiceContainer()->getUserNameUtils();
304 }
305 if ( $regen || !$this->loadBalancer ) {
306 $this->loadBalancer = $this->getServiceContainer()->getDBLoadBalancer();
307 }
308 if ( $regen || !$this->contentLanguage ) {
309 $this->contentLanguage = $this->getServiceContainer()->getContentLanguage();
310 }
311 if ( $regen || !$this->languageConverterFactory ) {
312 $this->languageConverterFactory = $this->getServiceContainer()->getLanguageConverterFactory();
313 }
314 if ( $regen || !$this->botPasswordStore ) {
315 $this->botPasswordStore = $this->getServiceContainer()->getBotPasswordStore();
316 }
317 if ( $regen || !$this->userFactory ) {
318 $this->userFactory = $this->getServiceContainer()->getUserFactory();
319 }
320 if ( $regen || !$this->userIdentityLookup ) {
321 $this->userIdentityLookup = $this->getServiceContainer()->getUserIdentityLookup();
322 }
323 if ( $regen || !$this->userOptionsManager ) {
324 $this->userOptionsManager = $this->getServiceContainer()->getUserOptionsManager();
325 }
326 if ( $regen || !$this->objectCacheFactory ) {
327 $this->objectCacheFactory = $this->getServiceContainer()->getObjectCacheFactory();
328 }
329 if ( !$this->logger ) {
330 $this->logger = new TestLogger();
331 }
332
333 if ( $regen || !$this->config->has( MainConfigNames::AuthManagerConfig ) ) {
334 $this->initializeConfig();
335 }
336 $this->manager = new AuthManager(
337 $this->request,
338 $this->config,
339 $this->objectFactory,
340 $this->hookContainer,
341 $this->readOnlyMode,
342 $this->userNameUtils,
343 $this->blockManager,
344 $this->watchlistManager,
345 $this->loadBalancer,
346 $this->contentLanguage,
347 $this->languageConverterFactory,
348 $this->botPasswordStore,
349 $this->userFactory,
350 $this->userIdentityLookup,
351 $this->userOptionsManager
352 );
353 $this->manager->setLogger( $this->logger );
354 $this->managerPriv = TestingAccessWrapper::newFromObject( $this->manager );
355 }
356
357 /**
358 * Setup SessionManager with a mock session provider
359 * @param bool|null $canChangeUser If non-null, canChangeUser will be mocked to return this
360 * @param array $methods Additional methods to mock
361 * @return array (MediaWiki\Session\SessionProvider, ScopedCallback)
362 */
363 protected function getMockSessionProvider( $canChangeUser = null, array $methods = [] ) {
364 if ( !$this->config ) {
365 $this->config = new HashConfig();
366 $this->initializeConfig();
367 }
368 $this->config->set( MainConfigNames::ObjectCacheSessionExpiry, 100 );
369
370 $methods[] = '__toString';
371 $methods[] = 'describe';
372 if ( $canChangeUser !== null ) {
373 $methods[] = 'canChangeUser';
374 }
375 $provider = $this->getMockBuilder( DummySessionProvider::class )
376 ->onlyMethods( $methods )
377 ->getMock();
378 $provider->method( '__toString' )
379 ->willReturn( 'MockSessionProvider' );
380 $provider->method( 'describe' )
381 ->willReturn( 'MockSessionProvider sessions' );
382 if ( $canChangeUser !== null ) {
383 $provider->method( 'canChangeUser' )
384 ->willReturn( $canChangeUser );
385 }
386 $this->config->set( MainConfigNames::SessionProviders, [
387 [ 'factory' => static function () use ( $provider ) {
388 return $provider;
389 } ],
390 ] );
391
392 $manager = new SessionManager( [
393 'config' => $this->config,
394 'logger' => new NullLogger(),
395 'store' => new HashBagOStuff(),
396 ] );
397 TestingAccessWrapper::newFromObject( $manager )->getProvider( (string)$provider );
398
399 $reset = TestUtils::setSessionManagerSingleton( $manager );
400
401 if ( $this->request ) {
402 $manager->getSessionForRequest( $this->request );
403 }
404
405 return [ $provider, $reset ];
406 }
407
408 public function testCanAuthenticateNow() {
409 $this->initializeManager();
410
411 [ $provider, $reset ] = $this->getMockSessionProvider( false );
412 $this->assertFalse( $this->manager->canAuthenticateNow() );
413 ScopedCallback::consume( $reset );
414
415 [ $provider, $reset ] = $this->getMockSessionProvider( true );
416 $this->assertTrue( $this->manager->canAuthenticateNow() );
417 ScopedCallback::consume( $reset );
418 }
419
420 public function testNormalizeUsername() {
421 $mocks = [
422 $this->createMock( AbstractPrimaryAuthenticationProvider::class ),
423 $this->createMock( AbstractPrimaryAuthenticationProvider::class ),
424 $this->createMock( AbstractPrimaryAuthenticationProvider::class ),
425 $this->createMock( AbstractPrimaryAuthenticationProvider::class ),
426 ];
427 foreach ( $mocks as $key => $mock ) {
428 $mock->method( 'getUniqueId' )->willReturn( $key );
429 }
430 $mocks[0]->expects( $this->once() )->method( 'providerNormalizeUsername' )
431 ->with( $this->identicalTo( 'XYZ' ) )
432 ->willReturn( 'Foo' );
433 $mocks[1]->expects( $this->once() )->method( 'providerNormalizeUsername' )
434 ->with( $this->identicalTo( 'XYZ' ) )
435 ->willReturn( 'Foo' );
436 $mocks[2]->expects( $this->once() )->method( 'providerNormalizeUsername' )
437 ->with( $this->identicalTo( 'XYZ' ) )
438 ->willReturn( null );
439 $mocks[3]->expects( $this->once() )->method( 'providerNormalizeUsername' )
440 ->with( $this->identicalTo( 'XYZ' ) )
441 ->willReturn( 'Bar!' );
442
443 $this->primaryauthMocks = $mocks;
444
445 $this->initializeManager();
446
447 $this->assertSame( [ 'Foo', 'Bar!' ], $this->manager->normalizeUsername( 'XYZ' ) );
448 }
449
450 /**
451 * @dataProvider provideSecuritySensitiveOperationStatus
452 * @param bool $mutableSession
453 */
454 public function testSecuritySensitiveOperationStatus( $mutableSession ) {
455 $this->logger = new NullLogger();
456 $user = $this->getTestSysop()->getUser();
457 $provideUser = null;
458 $reauth = $mutableSession ? AuthManager::SEC_REAUTH : AuthManager::SEC_FAIL;
459
460 [ $provider, $reset ] = $this->getMockSessionProvider(
461 $mutableSession, [ 'provideSessionInfo' ]
462 );
463 $provider->method( 'provideSessionInfo' )
464 ->willReturnCallback( static function () use ( $provider, &$provideUser ) {
465 return new SessionInfo( SessionInfo::MIN_PRIORITY, [
466 'provider' => $provider,
467 'id' => DummySessionProvider::ID,
468 'persisted' => true,
469 'userInfo' => UserInfo::newFromUser( $provideUser, true )
470 ] );
471 } );
472 $this->initializeManager();
473
474 $this->config->set( MainConfigNames::ReauthenticateTime, [] );
475 $this->config->set( MainConfigNames::AllowSecuritySensitiveOperationIfCannotReauthenticate, [] );
476 $provideUser = new User;
477 $session = $provider->getManager()->getSessionForRequest( $this->request );
478 $this->assertSame( 0, $session->getUser()->getId() );
479
480 // Anonymous user => reauth
481 $session->set( 'AuthManager:lastAuthId', 0 );
482 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
483 $this->assertSame( $reauth, $this->manager->securitySensitiveOperationStatus( 'foo' ) );
484
485 $provideUser = $user;
486 $session = $provider->getManager()->getSessionForRequest( $this->request );
487 $this->assertSame( $user->getId(), $session->getUser()->getId() );
488
489 // Error for no default (only gets thrown for non-anonymous user)
490 $session->set( 'AuthManager:lastAuthId', $user->getId() + 1 );
491 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
492 try {
493 $this->manager->securitySensitiveOperationStatus( 'foo' );
494 $this->fail( 'Expected exception not thrown' );
495 } catch ( UnexpectedValueException $ex ) {
496 $this->assertSame(
497 $mutableSession
498 ? '$wgReauthenticateTime lacks a default'
499 : '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default',
500 $ex->getMessage()
501 );
502 }
503
504 if ( $mutableSession ) {
505 $this->config->set( MainConfigNames::ReauthenticateTime, [
506 'test' => 100,
507 'test2' => -1,
508 'default' => 10,
509 ] );
510
511 // Mismatched user ID
512 $session->set( 'AuthManager:lastAuthId', $user->getId() + 1 );
513 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
514 $this->assertSame(
515 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'foo' )
516 );
517 $this->assertSame(
518 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'test' )
519 );
520 $this->assertSame(
521 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'test2' )
522 );
523
524 // Missing time
525 $session->set( 'AuthManager:lastAuthId', $user->getId() );
526 $session->set( 'AuthManager:lastAuthTimestamp', null );
527 $this->assertSame(
528 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'foo' )
529 );
530 $this->assertSame(
531 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'test' )
532 );
533 $this->assertSame(
534 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'test2' )
535 );
536
537 // Recent enough to pass
538 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
539 $this->assertSame(
540 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'foo' )
541 );
542
543 // Not recent enough to pass
544 $session->set( 'AuthManager:lastAuthTimestamp', time() - 20 );
545 $this->assertSame(
546 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'foo' )
547 );
548 // But recent enough for the 'test' operation
549 $this->assertSame(
550 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'test' )
551 );
552 } else {
553 $this->config->set( MainConfigNames::AllowSecuritySensitiveOperationIfCannotReauthenticate, [
554 'test' => false,
555 'default' => true,
556 ] );
557
558 $this->assertEquals(
559 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'foo' )
560 );
561
562 $this->assertEquals(
563 AuthManager::SEC_FAIL, $this->manager->securitySensitiveOperationStatus( 'test' )
564 );
565 }
566
567 // Test hook, all three possible values
568 foreach ( [
569 AuthManager::SEC_OK => AuthManager::SEC_OK,
570 AuthManager::SEC_REAUTH => $reauth,
571 AuthManager::SEC_FAIL => AuthManager::SEC_FAIL,
572 ] as $hook => $expect ) {
573 $this->hook( 'SecuritySensitiveOperationStatus',
574 SecuritySensitiveOperationStatusHook::class,
575 $this->exactly( 2 )
576 )
577 ->with(
578 /* $status */ $this->anything(),
579 /* $operation */ $this->anything(),
580 /* $session */ $this->callback( static function ( $s ) use ( $session ) {
581 return $s->getId() === $session->getId();
582 } ),
583 /* $timeSinceAuth*/ $mutableSession
584 ? $this->equalToWithDelta( 500, 2 )
585 : -1
586 )
587 ->willReturnCallback( static function ( &$v ) use ( $hook ) {
588 $v = $hook;
589 return true;
590 } );
591 $session->set( 'AuthManager:lastAuthTimestamp', time() - 500 );
592 $this->assertEquals(
593 $expect, $this->manager->securitySensitiveOperationStatus( 'test' ), "hook $hook"
594 );
595 $this->assertEquals(
596 $expect, $this->manager->securitySensitiveOperationStatus( 'test2' ), "hook $hook"
597 );
598 $this->unhook( 'SecuritySensitiveOperationStatus' );
599 }
600
601 ScopedCallback::consume( $reset );
602 }
603
604 public static function provideSecuritySensitiveOperationStatus() {
605 return [
606 [ true ],
607 [ false ],
608 ];
609 }
610
611 /**
612 * @dataProvider provideUserCanAuthenticate
613 * @param bool $primary1Can
614 * @param bool $primary2Can
615 * @param bool $expect
616 */
617 public function testUserCanAuthenticate( $primary1Can, $primary2Can, $expect ) {
618 $userName = 'TestUserCanAuthenticate';
619 $mock1 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
620 $mock1->method( 'getUniqueId' )
621 ->willReturn( 'primary1' );
622 $mock1->method( 'testUserCanAuthenticate' )
623 ->with( $userName )
624 ->willReturn( $primary1Can );
625 $mock2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
626 $mock2->method( 'getUniqueId' )
627 ->willReturn( 'primary2' );
628 $mock2->method( 'testUserCanAuthenticate' )
629 ->with( $userName )
630 ->willReturn( $primary2Can );
631 $this->primaryauthMocks = [ $mock1, $mock2 ];
632
633 $this->initializeManager( true );
634 $this->assertSame( $expect, $this->manager->userCanAuthenticate( $userName ) );
635 }
636
637 public static function provideUserCanAuthenticate() {
638 return [
639 [ false, false, false ],
640 [ true, false, true ],
641 [ false, true, true ],
642 [ true, true, true ],
643 ];
644 }
645
646 public function testRevokeAccessForUser() {
647 $userName = 'TestRevokeAccessForUser';
648 $this->initializeManager();
649
650 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
651 $mock->method( 'getUniqueId' )
652 ->willReturn( 'primary' );
653 $mock->expects( $this->once() )->method( 'providerRevokeAccessForUser' )
654 ->with( $userName );
655 $this->primaryauthMocks = [ $mock ];
656
657 $this->initializeManager( true );
658 $this->logger->setCollect( true );
659
660 $this->manager->revokeAccessForUser( $userName );
661
662 $this->assertSame( [
663 [ LogLevel::INFO, 'Revoking access for {user}' ],
664 ], $this->logger->getBuffer() );
665 }
666
667 public function testProviderCreation() {
668 $mocks = [
669 'pre' => $this->createMock( AbstractPreAuthenticationProvider::class ),
670 'primary' => $this->createMock( AbstractPrimaryAuthenticationProvider::class ),
671 'secondary' => $this->createMock( AbstractSecondaryAuthenticationProvider::class ),
672 ];
673 foreach ( $mocks as $key => $mock ) {
674 $mock->method( 'getUniqueId' )->willReturn( $key );
675 $mock->expects( $this->once() )->method( 'init' );
676 }
677 $this->preauthMocks = [ $mocks['pre'] ];
678 $this->primaryauthMocks = [ $mocks['primary'] ];
679 $this->secondaryauthMocks = [ $mocks['secondary'] ];
680
681 // Normal operation
682 $this->initializeManager();
683 $this->assertSame(
684 $mocks['primary'],
685 $this->managerPriv->getAuthenticationProvider( 'primary' )
686 );
687 $this->assertSame(
688 $mocks['secondary'],
689 $this->managerPriv->getAuthenticationProvider( 'secondary' )
690 );
691 $this->assertSame(
692 $mocks['pre'],
693 $this->managerPriv->getAuthenticationProvider( 'pre' )
694 );
695 $this->assertSame(
696 [ 'pre' => $mocks['pre'] ],
697 $this->managerPriv->getPreAuthenticationProviders()
698 );
699 $this->assertSame(
700 [ 'primary' => $mocks['primary'] ],
701 $this->managerPriv->getPrimaryAuthenticationProviders()
702 );
703 $this->assertSame(
704 [ 'secondary' => $mocks['secondary'] ],
705 $this->managerPriv->getSecondaryAuthenticationProviders()
706 );
707
708 // Duplicate IDs
709 $mock1 = $this->createMock( AbstractPreAuthenticationProvider::class );
710 $mock2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
711 $mock1->method( 'getUniqueId' )->willReturn( 'X' );
712 $mock2->method( 'getUniqueId' )->willReturn( 'X' );
713 $this->preauthMocks = [ $mock1 ];
714 $this->primaryauthMocks = [ $mock2 ];
715 $this->secondaryauthMocks = [];
716 $this->initializeManager( true );
717 try {
718 $this->managerPriv->getAuthenticationProvider( 'Y' );
719 $this->fail( 'Expected exception not thrown' );
720 } catch ( RuntimeException $ex ) {
721 $class1 = get_class( $mock1 );
722 $class2 = get_class( $mock2 );
723 $this->assertSame(
724 "Duplicate specifications for id X (classes $class2 and $class1)", $ex->getMessage()
725 );
726 }
727
728 // Wrong classes
729 $mock = $this->getMockForAbstractClass( AuthenticationProvider::class );
730 $mock->method( 'getUniqueId' )->willReturn( 'X' );
731 $class = get_class( $mock );
732 $this->preauthMocks = [ $mock ];
733 $this->primaryauthMocks = [];
734 $this->secondaryauthMocks = [];
735 $this->initializeManager( true );
736 try {
737 $this->managerPriv->getPreAuthenticationProviders();
738 $this->fail( 'Expected exception not thrown' );
739 } catch ( RuntimeException $ex ) {
740 $this->assertSame(
741 "Expected instance of MediaWiki\\Auth\\PreAuthenticationProvider, got $class",
742 $ex->getMessage()
743 );
744 }
745 $this->preauthMocks = [];
746 $this->primaryauthMocks = [ $mock ];
747 $this->secondaryauthMocks = [];
748 $this->initializeManager( true );
749 try {
750 $this->managerPriv->getPrimaryAuthenticationProviders();
751 $this->fail( 'Expected exception not thrown' );
752 } catch ( RuntimeException $ex ) {
753 $this->assertSame(
754 "Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got $class",
755 $ex->getMessage()
756 );
757 }
758 $this->preauthMocks = [];
759 $this->primaryauthMocks = [];
760 $this->secondaryauthMocks = [ $mock ];
761 $this->initializeManager( true );
762 try {
763 $this->managerPriv->getSecondaryAuthenticationProviders();
764 $this->fail( 'Expected exception not thrown' );
765 } catch ( RuntimeException $ex ) {
766 $this->assertSame(
767 "Expected instance of MediaWiki\\Auth\\SecondaryAuthenticationProvider, got $class",
768 $ex->getMessage()
769 );
770 }
771
772 // Sorting
773 $mock1 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
774 $mock2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
775 $mock3 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
776 $mock1->method( 'getUniqueId' )->willReturn( 'A' );
777 $mock2->method( 'getUniqueId' )->willReturn( 'B' );
778 $mock3->method( 'getUniqueId' )->willReturn( 'C' );
779 $this->preauthMocks = [];
780 $this->primaryauthMocks = [ $mock1, $mock2, $mock3 ];
781 $this->secondaryauthMocks = [];
782 $this->initializeConfig();
783 $config = $this->config->get( MainConfigNames::AuthManagerConfig );
784
785 $this->initializeManager( false );
786 $this->assertSame(
787 [ 'A' => $mock1, 'B' => $mock2, 'C' => $mock3 ],
788 $this->managerPriv->getPrimaryAuthenticationProviders()
789 );
790
791 $config['primaryauth']['A']['sort'] = 100;
792 $config['primaryauth']['C']['sort'] = -1;
793 $this->config->set( MainConfigNames::AuthManagerConfig, $config );
794 $this->initializeManager( false );
795 $this->assertSame(
796 [ 'C' => $mock3, 'B' => $mock2, 'A' => $mock1 ],
797 $this->managerPriv->getPrimaryAuthenticationProviders()
798 );
799
800 // filtering
801 $mockPreAuth1 = $this->createMock( AbstractPreAuthenticationProvider::class );
802 $mockPreAuth2 = $this->createMock( AbstractPreAuthenticationProvider::class );
803 $mockPrimary1 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
804 $mockPrimary2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
805 $mockSecondary1 = $this->createMock( AbstractSecondaryAuthenticationProvider::class );
806 $mockSecondary2 = $this->createMock( AbstractSecondaryAuthenticationProvider::class );
807 $mockPreAuth1->method( 'getUniqueId' )->willReturn( 'pre1' );
808 $mockPreAuth2->method( 'getUniqueId' )->willReturn( 'pre2' );
809 $mockPrimary1->method( 'getUniqueId' )->willReturn( 'primary1' );
810 $mockPrimary2->method( 'getUniqueId' )->willReturn( 'primary2' );
811 $mockSecondary1->method( 'getUniqueId' )->willReturn( 'secondary1' );
812 $mockSecondary2->method( 'getUniqueId' )->willReturn( 'secondary2' );
813 $this->preauthMocks = [ $mockPreAuth1, $mockPreAuth2 ];
814 $this->primaryauthMocks = [ $mockPrimary1, $mockPrimary2 ];
815 $this->secondaryauthMocks = [ $mockSecondary1, $mockSecondary2 ];
816 $this->initializeConfig();
817 $this->initializeManager( true );
818 $this->hookContainer->register( 'AuthManagerFilterProviders', static function ( &$providers ) {
819 unset( $providers['preauth']['pre1'] );
820 $providers['primaryauth']['primary2'] = false;
821 $providers['secondaryauth'] = [ 'secondary2' => true ];
822 } );
823 $this->assertSame( [ 'pre2' => $mockPreAuth2 ], $this->managerPriv->getPreAuthenticationProviders() );
824 $this->assertSame( [ 'primary1' => $mockPrimary1 ], $this->managerPriv->getPrimaryAuthenticationProviders() );
825 $this->assertSame( [ 'secondary2' => $mockSecondary2 ], $this->managerPriv->getSecondaryAuthenticationProviders() );
826 }
827
828 /**
829 * @dataProvider provideSetDefaultUserOptions
830 */
831 public function testSetDefaultUserOptions(
832 $contLang, $useContextLang, $expectedLang, $expectedVariant
833 ) {
834 $this->setContentLang( $contLang );
835 $this->initializeManager( true );
836 $context = RequestContext::getMain();
837 $reset = new ScopedCallback( [ $context, 'setLanguage' ], [ $context->getLanguage() ] );
838 $context->setLanguage( 'de' );
839
840 $user = User::newFromName( self::usernameForCreation() );
841 $user->addToDatabase();
842 $oldToken = $user->getToken();
843 $this->managerPriv->setDefaultUserOptions( $user, $useContextLang );
844 $user->saveSettings();
845 $this->assertNotEquals( $oldToken, $user->getToken() );
846 $this->assertSame(
847 $expectedLang,
848 $this->userOptionsManager->getOption( $user, 'language' )
849 );
850 $this->assertSame(
851 $expectedVariant,
852 $this->userOptionsManager->getOption( $user, 'variant' )
853 );
854 }
855
856 public static function provideSetDefaultUserOptions() {
857 return [
858 [ 'zh', false, 'zh', 'zh' ],
859 [ 'zh', true, 'de', 'zh' ],
860 [ 'fr', true, 'de', 'fr' ],
861 ];
862 }
863
864 public function testForcePrimaryAuthenticationProviders() {
865 $mockA = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
866 $mockB = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
867 $mockB2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
868 $mockA->method( 'getUniqueId' )->willReturn( 'A' );
869 $mockB->method( 'getUniqueId' )->willReturn( 'B' );
870 $mockB2->method( 'getUniqueId' )->willReturn( 'B' );
871 $this->primaryauthMocks = [ $mockA ];
872
873 $this->logger = new TestLogger( true );
874
875 // Test without first initializing the configured providers
876 $this->initializeManager();
877 $this->expectDeprecationAndContinue( '/AuthManager::forcePrimaryAuthenticationProviders/' );
878 $this->manager->forcePrimaryAuthenticationProviders( [ $mockB ], 'testing' );
879 $this->assertSame(
880 [ 'B' => $mockB ], $this->managerPriv->getPrimaryAuthenticationProviders()
881 );
882 $this->assertSame( null, $this->managerPriv->getAuthenticationProvider( 'A' ) );
883 $this->assertSame( $mockB, $this->managerPriv->getAuthenticationProvider( 'B' ) );
884 $this->assertSame( [
885 [ LogLevel::WARNING, 'Overriding AuthManager primary authn because testing' ],
886 ], $this->logger->getBuffer() );
887 $this->logger->clearBuffer();
888
889 // Test with first initializing the configured providers
890 $this->initializeManager();
891 $this->assertSame( $mockA, $this->managerPriv->getAuthenticationProvider( 'A' ) );
892 $this->assertSame( null, $this->managerPriv->getAuthenticationProvider( 'B' ) );
893 $this->request->getSession()->setSecret( AuthManager::AUTHN_STATE, 'test' );
894 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE, 'test' );
895 $this->expectDeprecationAndContinue( '/AuthManager::forcePrimaryAuthenticationProviders/' );
896 $this->manager->forcePrimaryAuthenticationProviders( [ $mockB ], 'testing' );
897 $this->assertSame(
898 [ 'B' => $mockB ], $this->managerPriv->getPrimaryAuthenticationProviders()
899 );
900 $this->assertSame( null, $this->managerPriv->getAuthenticationProvider( 'A' ) );
901 $this->assertSame( $mockB, $this->managerPriv->getAuthenticationProvider( 'B' ) );
902 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::AUTHN_STATE ) );
903 $this->assertNull(
904 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
905 );
906 $this->assertSame( [
907 [ LogLevel::WARNING, 'Overriding AuthManager primary authn because testing' ],
908 [
909 LogLevel::WARNING,
910 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
911 ],
912 ], $this->logger->getBuffer() );
913 $this->logger->clearBuffer();
914
915 // Test duplicate IDs
916 $this->initializeManager();
917 try {
918 $this->expectDeprecationAndContinue( '/AuthManager::forcePrimaryAuthenticationProviders/' );
919 $this->manager->forcePrimaryAuthenticationProviders( [ $mockB, $mockB2 ], 'testing' );
920 $this->fail( 'Expected exception not thrown' );
921 } catch ( RuntimeException $ex ) {
922 $class1 = get_class( $mockB );
923 $class2 = get_class( $mockB2 );
924 $this->assertSame(
925 "Duplicate specifications for id B (classes $class2 and $class1)", $ex->getMessage()
926 );
927 }
928
929 // Wrong classes
930 $mock = $this->getMockForAbstractClass( AuthenticationProvider::class );
931 $mock->method( 'getUniqueId' )->willReturn( 'X' );
932 $class = get_class( $mock );
933 try {
934 $this->manager->forcePrimaryAuthenticationProviders( [ $mock ], 'testing' );
935 $this->fail( 'Expected exception not thrown' );
936 } catch ( RuntimeException $ex ) {
937 $this->assertSame(
938 "Expected instance of MediaWiki\\Auth\\AbstractPrimaryAuthenticationProvider, got $class",
939 $ex->getMessage()
940 );
941 }
942 }
943
944 public function testBeginAuthentication() {
945 $this->initializeManager();
946
947 // Immutable session
948 [ $provider, $reset ] = $this->getMockSessionProvider( false );
949 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->never() );
950 $this->request->getSession()->setSecret( AuthManager::AUTHN_STATE, 'test' );
951 try {
952 $this->manager->beginAuthentication( [], 'http://localhost/' );
953 $this->fail( 'Expected exception not thrown' );
954 } catch ( LogicException $ex ) {
955 $this->assertSame( 'Authentication is not possible now', $ex->getMessage() );
956 }
957 $this->unhook( 'UserLoggedIn' );
958 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::AUTHN_STATE ) );
959 ScopedCallback::consume( $reset );
960 $this->initializeManager( true );
961
962 // CreatedAccountAuthenticationRequest
963 $user = $this->getTestSysop()->getUser();
964 $reqs = [
965 new CreatedAccountAuthenticationRequest( $user->getId(), $user->getName() )
966 ];
967 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->never() );
968 try {
969 $this->manager->beginAuthentication( $reqs, 'http://localhost/' );
970 $this->fail( 'Expected exception not thrown' );
971 } catch ( LogicException $ex ) {
972 $this->assertSame(
973 'CreatedAccountAuthenticationRequests are only valid on the same AuthManager ' .
974 'that created the account',
975 $ex->getMessage()
976 );
977 }
978 $this->unhook( 'UserLoggedIn' );
979
980 $this->request->getSession()->clear();
981 $this->request->getSession()->setSecret( AuthManager::AUTHN_STATE, 'test' );
982 $this->managerPriv->createdAccountAuthenticationRequests = [ $reqs[0] ];
983 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->once() )
984 ->with( $this->callback( static function ( $u ) use ( $user ) {
985 return $user->getId() === $u->getId() && $user->getName() === $u->getName();
986 } ) );
987 $this->hook( 'AuthManagerLoginAuthenticateAudit',
988 AuthManagerLoginAuthenticateAuditHook::class, $this->once() );
989 $this->logger->setCollect( true );
990 $ret = $this->manager->beginAuthentication( $reqs, 'http://localhost/' );
991 $this->logger->setCollect( false );
992 $this->unhook( 'UserLoggedIn' );
993 $this->unhook( 'AuthManagerLoginAuthenticateAudit' );
994 $this->assertSame( AuthenticationResponse::PASS, $ret->status );
995 $this->assertSame( $user->getName(), $ret->username );
996 $this->assertSame( $user->getId(), $this->request->getSessionData( 'AuthManager:lastAuthId' ) );
997 // FIXME: Avoid relying on implicit amounts of time elapsing.
998 $this->assertEqualsWithDelta(
999 time(),
1000 $this->request->getSessionData( 'AuthManager:lastAuthTimestamp' ),
1001 1,
1002 'timestamp ±1'
1003 );
1004 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::AUTHN_STATE ) );
1005 $this->assertSame( $user->getId(), $this->request->getSession()->getUser()->getId() );
1006 $this->assertSame( [
1007 [ LogLevel::INFO, 'Logging in {user} after account creation' ],
1008 ], $this->logger->getBuffer() );
1009 }
1010
1011 public function testCreateFromLogin() {
1012 $user = $this->getTestSysop()->getUser();
1013 $req1 = $this->createMock( AuthenticationRequest::class );
1014 $req1->method( 'getUniqueId' )->willReturn( __METHOD__ . 1 );
1015 $req2 = $this->createMock( AuthenticationRequest::class );
1016 $req2->method( 'getUniqueId' )->willReturn( __METHOD__ . 2 );
1017 $req3 = $this->createMock( AuthenticationRequest::class );
1018 $req3->method( 'getUniqueId' )->willReturn( __METHOD__ . 3 );
1019 $userReq = new UsernameAuthenticationRequest;
1020 $userReq->username = 'UTDummy';
1021
1022 $req1->returnToUrl = 'http://localhost/';
1023 $req2->returnToUrl = 'http://localhost/';
1024 $req3->returnToUrl = 'http://localhost/';
1025 $req3->username = 'UTDummy';
1026 $userReq->returnToUrl = 'http://localhost/';
1027
1028 // Passing one into beginAuthentication(), and an immediate FAIL
1029 $primary = $this->getMockForAbstractClass( AbstractPrimaryAuthenticationProvider::class );
1030 $this->primaryauthMocks = [ $primary ];
1031 $this->initializeManager( true );
1032 $res = AuthenticationResponse::newFail( wfMessage( 'foo' ) );
1033 $res->createRequest = $req1;
1034 $primary->method( 'beginPrimaryAuthentication' )
1035 ->willReturn( $res );
1036 $createReq = new CreateFromLoginAuthenticationRequest(
1037 null, [ $req2->getUniqueId() => $req2 ]
1038 );
1039 $this->logger->setCollect( true );
1040 $ret = $this->manager->beginAuthentication( [ $createReq ], 'http://localhost/' );
1041 $this->logger->setCollect( false );
1042 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1043 $this->assertInstanceOf( CreateFromLoginAuthenticationRequest::class, $ret->createRequest );
1044 $this->assertSame( $req1, $ret->createRequest->createRequest );
1045 $this->assertEquals( [ $req2->getUniqueId() => $req2 ], $ret->createRequest->maybeLink );
1046
1047 // UI, then FAIL in beginAuthentication()
1048 $primary = $this->getMockBuilder( AbstractPrimaryAuthenticationProvider::class )
1049 ->onlyMethods( [ 'continuePrimaryAuthentication' ] )
1050 ->getMockForAbstractClass();
1051 $this->primaryauthMocks = [ $primary ];
1052 $this->initializeManager( true );
1053 $primary->method( 'beginPrimaryAuthentication' )
1054 ->willReturn( AuthenticationResponse::newUI( [ $req1 ], wfMessage( 'foo' ) ) );
1055 $res = AuthenticationResponse::newFail( wfMessage( 'foo' ) );
1056 $res->createRequest = $req2;
1057 $primary->method( 'continuePrimaryAuthentication' )
1058 ->willReturn( $res );
1059 $this->logger->setCollect( true );
1060 $ret = $this->manager->beginAuthentication( [], 'http://localhost/' );
1061 $this->assertSame( AuthenticationResponse::UI, $ret->status );
1062 $ret = $this->manager->continueAuthentication( [] );
1063 $this->logger->setCollect( false );
1064 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1065 $this->assertInstanceOf( CreateFromLoginAuthenticationRequest::class, $ret->createRequest );
1066 $this->assertSame( $req2, $ret->createRequest->createRequest );
1067 $this->assertEquals( [], $ret->createRequest->maybeLink );
1068
1069 // Pass into beginAccountCreation(), see that maybeLink and createRequest get copied
1070 $primary = $this->getMockForAbstractClass( AbstractPrimaryAuthenticationProvider::class );
1071 $this->primaryauthMocks = [ $primary ];
1072 $this->initializeManager( true );
1073 $createReq = new CreateFromLoginAuthenticationRequest( $req3, [ $req2 ] );
1074 $createReq->returnToUrl = 'http://localhost/';
1075 $createReq->username = 'UTDummy';
1076 $res = AuthenticationResponse::newUI( [ $req1 ], wfMessage( 'foo' ) );
1077 $primary->method( 'beginPrimaryAccountCreation' )
1078 ->with( $this->anything(), $this->anything(), [ $userReq, $createReq, $req3 ] )
1079 ->willReturn( $res );
1080 $primary->method( 'accountCreationType' )
1081 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
1082 $this->logger->setCollect( true );
1083 $ret = $this->manager->beginAccountCreation(
1084 $user, [ $userReq, $createReq ], 'http://localhost/'
1085 );
1086 $this->logger->setCollect( false );
1087 $this->assertSame( AuthenticationResponse::UI, $ret->status );
1088 $state = $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE );
1089 $this->assertNotNull( $state );
1090 $this->assertEquals( [ $userReq, $createReq, $req3 ], $state['reqs'] );
1091 $this->assertEquals( [ $req2 ], $state['maybeLink'] );
1092 }
1093
1094 /**
1095 * @dataProvider provideAuthentication
1096 * @param StatusValue $preResponse
1097 * @param array<AuthenticationResponse|Exception> $primaryResponses
1098 * @param array<AuthenticationResponse|Exception> $secondaryResponses
1099 * @param array<AuthenticationResponse|Exception> $managerResponses
1100 * @param bool $link Whether the primary authentication provider is a "link" provider
1101 */
1102 public function testAuthentication(
1103 StatusValue $preResponse, array $primaryResponses, array $secondaryResponses,
1104 array $managerResponses, $link = false
1105 ) {
1106 $this->initializeManager();
1107 $user = $this->getTestSysop()->getUser();
1108 $id = $user->getId();
1109 $name = $user->getName();
1110 // Hack: replace placeholder usernames with that of the test user. A better solution would be to instantiate
1111 // all responses here, only providing constructor arguments (like the status) from the data provider.
1112 $responseArrays = [ $primaryResponses, $secondaryResponses, $managerResponses ];
1113 foreach ( $responseArrays as $respArray ) {
1114 foreach ( $respArray as $resp ) {
1115 if ( $resp instanceof AuthenticationResponse && $resp->username === 'PLACEHOLDER' ) {
1116 $resp->username = $name;
1117 }
1118 }
1119 }
1120
1121 // Set up lots of mocks...
1122 $req = new RememberMeAuthenticationRequest;
1123 $req->rememberMe = (bool)rand( 0, 1 );
1124 $mocks = [];
1125 foreach ( [ 'pre', 'primary', 'secondary' ] as $key ) {
1126 $class = ucfirst( $key ) . 'AuthenticationProvider';
1127 $mocks[$key] = $this->getMockBuilder( "MediaWiki\\Auth\\Abstract$class" )
1128 ->setMockClassName( "MockAbstract$class" )
1129 ->getMock();
1130 $mocks[$key]->method( 'getUniqueId' )
1131 ->willReturn( $key );
1132 $mocks[$key . '2'] = $this->createMock( "MediaWiki\\Auth\\Abstract$class" );
1133 $mocks[$key . '2']->method( 'getUniqueId' )
1134 ->willReturn( $key . '2' );
1135 $mocks[$key . '3'] = $this->createMock( "MediaWiki\\Auth\\Abstract$class" );
1136 $mocks[$key . '3']->method( 'getUniqueId' )
1137 ->willReturn( $key . '3' );
1138 }
1139 foreach ( $mocks as $mock ) {
1140 $mock->method( 'getAuthenticationRequests' )
1141 ->willReturn( [] );
1142 }
1143
1144 $mocks['pre']->expects( $this->once() )->method( 'testForAuthentication' )
1145 ->willReturnCallback( function ( $reqs ) use ( $req, $preResponse ) {
1146 $this->assertContains( $req, $reqs );
1147 return $preResponse;
1148 } );
1149
1150 $ct = count( $primaryResponses );
1151 $callback = $this->returnCallback( function ( $reqs ) use ( $req, &$primaryResponses ) {
1152 $this->assertContains( $req, $reqs );
1153 return array_shift( $primaryResponses );
1154 } );
1155 $mocks['primary']->expects( $this->exactly( min( 1, $ct ) ) )
1156 ->method( 'beginPrimaryAuthentication' )
1157 ->will( $callback );
1158 $mocks['primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
1159 ->method( 'continuePrimaryAuthentication' )
1160 ->will( $callback );
1161 if ( $link ) {
1162 $mocks['primary']->method( 'accountCreationType' )
1163 ->willReturn( PrimaryAuthenticationProvider::TYPE_LINK );
1164 }
1165
1166 $ct = count( $secondaryResponses );
1167 $callback = $this->returnCallback( function ( $user, $reqs ) use ( $id, $name, $req, &$secondaryResponses ) {
1168 $this->assertSame( $id, $user->getId() );
1169 $this->assertSame( $name, $user->getName() );
1170 $this->assertContains( $req, $reqs );
1171 return array_shift( $secondaryResponses );
1172 } );
1173 $mocks['secondary']->expects( $this->exactly( min( 1, $ct ) ) )
1174 ->method( 'beginSecondaryAuthentication' )
1175 ->will( $callback );
1176 $mocks['secondary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
1177 ->method( 'continueSecondaryAuthentication' )
1178 ->will( $callback );
1179
1180 $abstain = AuthenticationResponse::newAbstain();
1181 $mocks['pre2']->expects( $this->atMost( 1 ) )->method( 'testForAuthentication' )
1182 ->willReturn( StatusValue::newGood() );
1183 $mocks['primary2']->expects( $this->atMost( 1 ) )->method( 'beginPrimaryAuthentication' )
1184 ->willReturn( $abstain );
1185 $mocks['primary2']->expects( $this->never() )->method( 'continuePrimaryAuthentication' );
1186 $mocks['secondary2']->expects( $this->atMost( 1 ) )->method( 'beginSecondaryAuthentication' )
1187 ->willReturn( $abstain );
1188 $mocks['secondary2']->expects( $this->never() )->method( 'continueSecondaryAuthentication' );
1189 $mocks['secondary3']->expects( $this->atMost( 1 ) )->method( 'beginSecondaryAuthentication' )
1190 ->willReturn( $abstain );
1191 $mocks['secondary3']->expects( $this->never() )->method( 'continueSecondaryAuthentication' );
1192
1193 $this->preauthMocks = [ $mocks['pre'], $mocks['pre2'] ];
1194 $this->primaryauthMocks = [ $mocks['primary'], $mocks['primary2'] ];
1195 $this->secondaryauthMocks = [
1196 $mocks['secondary3'], $mocks['secondary'], $mocks['secondary2'],
1197 // So linking happens
1198 new ConfirmLinkSecondaryAuthenticationProvider,
1199 ];
1200 $this->initializeManager( true );
1201 $this->logger->setCollect( true );
1202
1203 $constraint = Assert::logicalOr(
1204 $this->equalTo( AuthenticationResponse::PASS ),
1205 $this->equalTo( AuthenticationResponse::FAIL )
1206 );
1207 $providers = array_filter(
1208 array_merge(
1209 $this->preauthMocks, $this->primaryauthMocks, $this->secondaryauthMocks
1210 ),
1211 static function ( $p ) {
1212 return is_callable( [ $p, 'expects' ] );
1213 }
1214 );
1215 foreach ( $providers as $p ) {
1216 DynamicPropertyTestHelper::setDynamicProperty( $p, 'postCalled', false );
1217 $p->expects( $this->atMost( 1 ) )->method( 'postAuthentication' )
1218 ->willReturnCallback( function ( $userArg, $response ) use ( $user, $constraint, $p ) {
1219 if ( $userArg !== null ) {
1220 $this->assertInstanceOf( User::class, $userArg );
1221 $this->assertSame( $user->getName(), $userArg->getName() );
1222 }
1223 $this->assertInstanceOf( AuthenticationResponse::class, $response );
1224 $this->assertThat( $response->status, $constraint );
1225 DynamicPropertyTestHelper::setDynamicProperty( $p, 'postCalled', $response->status );
1226 } );
1227 }
1228
1229 $session = $this->request->getSession();
1230 $session->setRememberUser( !$req->rememberMe );
1231
1232 foreach ( $managerResponses as $i => $response ) {
1233 $success = $response instanceof AuthenticationResponse &&
1234 $response->status === AuthenticationResponse::PASS;
1235 if ( $success ) {
1236 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->once() )
1237 ->with( $this->callback( static function ( $user ) use ( $id, $name ) {
1238 return $user->getId() === $id && $user->getName() === $name;
1239 } ) );
1240 } else {
1241 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->never() );
1242 }
1243 if ( $success || (
1244 $response instanceof AuthenticationResponse &&
1245 $response->status === AuthenticationResponse::FAIL &&
1246 $response->message->getKey() !== 'authmanager-authn-not-in-progress' &&
1247 $response->message->getKey() !== 'authmanager-authn-no-primary'
1248 )
1249 ) {
1250 $this->hook( 'AuthManagerLoginAuthenticateAudit',
1251 AuthManagerLoginAuthenticateAuditHook::class, $this->once() );
1252 } else {
1253 $this->hook( 'AuthManagerLoginAuthenticateAudit',
1254 AuthManagerLoginAuthenticateAuditHook::class, $this->never() );
1255 }
1256
1257 try {
1258 if ( !$i ) {
1259 $ret = $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1260 } else {
1261 $ret = $this->manager->continueAuthentication( [ $req ] );
1262 }
1263 if ( $response instanceof Exception ) {
1264 $this->fail( 'Expected exception not thrown', "Response $i" );
1265 }
1266 } catch ( Exception $ex ) {
1267 if ( !$response instanceof Exception ) {
1268 throw $ex;
1269 }
1270 $this->assertEquals( $response->getMessage(), $ex->getMessage(), "Response $i, exception" );
1271 $this->assertNull( $session->getSecret( AuthManager::AUTHN_STATE ),
1272 "Response $i, exception, session state" );
1273 $this->unhook( 'UserLoggedIn' );
1274 $this->unhook( 'AuthManagerLoginAuthenticateAudit' );
1275 return;
1276 }
1277
1278 $this->unhook( 'UserLoggedIn' );
1279 $this->unhook( 'AuthManagerLoginAuthenticateAudit' );
1280
1281 $this->assertSame( 'http://localhost/', $req->returnToUrl );
1282
1283 $ret->message = $this->message( $ret->message );
1284 $this->assertResponseEquals( $response, $ret, "Response $i, response" );
1285 if ( $success ) {
1286 $this->assertSame( $id, $session->getUser()->getId(),
1287 "Response $i, authn" );
1288 } else {
1289 $this->assertSame( 0, $session->getUser()->getId(),
1290 "Response $i, authn" );
1291 }
1292 if ( $success || $response->status === AuthenticationResponse::FAIL ) {
1293 $this->assertNull( $session->getSecret( AuthManager::AUTHN_STATE ),
1294 "Response $i, session state" );
1295 foreach ( $providers as $p ) {
1296 $this->assertSame( $response->status, DynamicPropertyTestHelper::getDynamicProperty( $p, 'postCalled' ),
1297 "Response $i, post-auth callback called" );
1298 }
1299 } else {
1300 $this->assertNotNull( $session->getSecret( AuthManager::AUTHN_STATE ),
1301 "Response $i, session state" );
1302 foreach ( $ret->neededRequests as $neededReq ) {
1303 $this->assertEquals( AuthManager::ACTION_LOGIN, $neededReq->action,
1304 "Response $i, neededRequest action" );
1305 }
1306 $this->assertEquals(
1307 $ret->neededRequests,
1308 $this->manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN_CONTINUE ),
1309 "Response $i, continuation check"
1310 );
1311 foreach ( $providers as $p ) {
1312 $this->assertFalse( DynamicPropertyTestHelper::getDynamicProperty( $p, 'postCalled' ), "Response $i, post-auth callback not called" );
1313 }
1314 }
1315
1316 $state = $session->getSecret( AuthManager::AUTHN_STATE );
1317 $maybeLink = $state['maybeLink'] ?? [];
1318 if ( $link && $response->status === AuthenticationResponse::RESTART ) {
1319 $this->assertEquals(
1320 $response->createRequest->maybeLink,
1321 $maybeLink,
1322 "Response $i, maybeLink"
1323 );
1324 } else {
1325 $this->assertEquals( [], $maybeLink, "Response $i, maybeLink" );
1326 }
1327 }
1328
1329 if ( $success ) {
1330 $this->assertSame( $req->rememberMe, $session->shouldRememberUser(),
1331 'rememberMe checkbox had effect' );
1332 } else {
1333 $this->assertNotSame( $req->rememberMe, $session->shouldRememberUser(),
1334 'rememberMe checkbox wasn\'t applied' );
1335 }
1336 }
1337
1338 public function provideAuthentication() {
1339 $rememberReq = new RememberMeAuthenticationRequest;
1340 $rememberReq->action = AuthManager::ACTION_LOGIN;
1341
1342 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1343 $restartResponse = AuthenticationResponse::newRestart(
1344 $this->message( 'authmanager-authn-no-local-user' )
1345 );
1346 $restartResponse->neededRequests = [ $rememberReq ];
1347
1348 $restartResponse2Pass = AuthenticationResponse::newPass( null );
1349 $restartResponse2Pass->linkRequest = $req;
1350 $restartResponse2 = AuthenticationResponse::newRestart(
1351 $this->message( 'authmanager-authn-no-local-user-link' )
1352 );
1353 $restartResponse2->createRequest = new CreateFromLoginAuthenticationRequest(
1354 null, [ $req->getUniqueId() => $req ]
1355 );
1356 $restartResponse2->createRequest->action = AuthManager::ACTION_LOGIN;
1357 $restartResponse2->neededRequests = [ $rememberReq, $restartResponse2->createRequest ];
1358
1359 // Hack: use a placeholder that will be replaced with the actual username in the test method.
1360 $userNamePlaceholder = 'PLACEHOLDER';
1361
1362 return [
1363 'Failure in pre-auth' => [
1364 StatusValue::newFatal( 'fail-from-pre' ),
1365 [],
1366 [],
1367 [
1368 AuthenticationResponse::newFail( $this->message( 'fail-from-pre' ) ),
1369 AuthenticationResponse::newFail(
1370 $this->message( 'authmanager-authn-not-in-progress' )
1371 ),
1372 ]
1373 ],
1374 'Failure in primary' => [
1375 StatusValue::newGood(),
1376 $tmp = [
1377 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
1378 ],
1379 [],
1380 $tmp
1381 ],
1382 'All primary abstain' => [
1383 StatusValue::newGood(),
1384 [
1385 AuthenticationResponse::newAbstain(),
1386 ],
1387 [],
1388 [
1389 AuthenticationResponse::newFail( $this->message( 'authmanager-authn-no-primary' ) )
1390 ]
1391 ],
1392 'Primary UI, then redirect, then fail' => [
1393 StatusValue::newGood(),
1394 $tmp = [
1395 AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1396 AuthenticationResponse::newRedirect( [ $req ], '/foo.html', [ 'foo' => 'bar' ] ),
1397 AuthenticationResponse::newFail( $this->message( 'fail-in-primary-continue' ) ),
1398 ],
1399 [],
1400 $tmp
1401 ],
1402 'Primary redirect, then abstain' => [
1403 StatusValue::newGood(),
1404 [
1405 $tmp = AuthenticationResponse::newRedirect(
1406 [ $req ], '/foo.html', [ 'foo' => 'bar' ]
1407 ),
1408 AuthenticationResponse::newAbstain(),
1409 ],
1410 [],
1411 [
1412 $tmp,
1413 new DomainException(
1414 'MockAbstractPrimaryAuthenticationProvider::continuePrimaryAuthentication() returned ABSTAIN'
1415 )
1416 ]
1417 ],
1418 'Primary UI, then pass with no local user' => [
1419 StatusValue::newGood(),
1420 [
1421 $tmp = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1422 AuthenticationResponse::newPass( null ),
1423 ],
1424 [],
1425 [
1426 $tmp,
1427 $restartResponse,
1428 ]
1429 ],
1430 'Primary UI, then pass with no local user (link type)' => [
1431 StatusValue::newGood(),
1432 [
1433 $tmp = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1434 $restartResponse2Pass,
1435 ],
1436 [],
1437 [
1438 $tmp,
1439 $restartResponse2,
1440 ],
1441 true
1442 ],
1443 'Primary pass with invalid username' => [
1444 StatusValue::newGood(),
1445 [
1446 AuthenticationResponse::newPass( '<>' ),
1447 ],
1448 [],
1449 [
1450 new DomainException(
1451 'MockAbstractPrimaryAuthenticationProvider returned an invalid username: <>'
1452 ),
1453 ]
1454 ],
1455 'Secondary fail' => [
1456 StatusValue::newGood(),
1457 [
1458 AuthenticationResponse::newPass( $userNamePlaceholder ),
1459 ],
1460 $tmp = [
1461 AuthenticationResponse::newFail( $this->message( 'fail-in-secondary' ) ),
1462 ],
1463 $tmp
1464 ],
1465 'Secondary UI, then abstain' => [
1466 StatusValue::newGood(),
1467 [
1468 AuthenticationResponse::newPass( $userNamePlaceholder ),
1469 ],
1470 [
1471 $tmp = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1472 AuthenticationResponse::newAbstain()
1473 ],
1474 [
1475 $tmp,
1476 AuthenticationResponse::newPass( $userNamePlaceholder ),
1477 ]
1478 ],
1479 'Secondary pass' => [
1480 StatusValue::newGood(),
1481 [
1482 AuthenticationResponse::newPass( $userNamePlaceholder ),
1483 ],
1484 [
1485 AuthenticationResponse::newPass()
1486 ],
1487 [
1488 AuthenticationResponse::newPass( $userNamePlaceholder ),
1489 ]
1490 ],
1491 ];
1492 }
1493
1494 public function testAuthentication_AuthManagerVerifyAuthentication() {
1495 $this->logger = new NullLogger();
1496 $this->initializeManager();
1497
1498 $primaryConfig = [
1499 'getUniqueId' => 'primary',
1500 'testUserForCreation' => StatusValue::newGood(),
1501 'getAuthenticationRequests' => [],
1502 'beginPrimaryAuthentication' => AuthenticationResponse::newPass( 'UTDummy' ),
1503 ];
1504 $secondaryConfig = [
1505 'getUniqueId' => 'secondary',
1506 'testUserForCreation' => StatusValue::newGood(),
1507 'getAuthenticationRequests' => [],
1508 'beginSecondaryAuthentication' => AuthenticationResponse::newAbstain(),
1509 ];
1510 $updateManager = function () use ( &$primaryConfig, &$secondaryConfig ) {
1511 $primaryMock = $this->createConfiguredMock( AbstractPrimaryAuthenticationProvider::class, $primaryConfig );
1512 foreach ( [ 'beginPrimaryAuthentication', 'continuePrimaryAuthentication' ] as $method ) {
1513 $primaryMock->expects(
1514 array_key_exists( $method, $primaryConfig ) ? $this->once() : $this->never()
1515 )->method( $method );
1516 }
1517 $secondaryMock = $this->createConfiguredMock( AbstractSecondaryAuthenticationProvider::class, $secondaryConfig );
1518 foreach ( [ 'beginSecondaryAuthentication', 'continueSecondaryAuthentication' ] as $method ) {
1519 $secondaryMock->expects(
1520 array_key_exists( $method, $secondaryConfig ) ? $this->once() : $this->never()
1521 )->method( $method );
1522 }
1523 $this->primaryauthMocks = [ $primaryMock ];
1524 $this->secondaryauthMocks = [ $secondaryMock ];
1525 $this->initializeManager( true );
1526 };
1527 $req = new RememberMeAuthenticationRequest();
1528 $req->rememberMe = true;
1529
1530 // Gets expected data
1531 $updateManager();
1532 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
1533 $hook->willReturnCallback( function ( $user, &$response, $authManager, $info ) {
1534 $this->assertSame( 'UTDummy', $user->getName() );
1535 $this->assertSame( AuthenticationResponse::PASS, $response->status );
1536 $this->assertSame( $this->manager, $authManager );
1537 $this->assertSame( AuthManager::ACTION_LOGIN, $info['action'] );
1538 $this->assertSame( 'primary', $info['primaryId'] );
1539 } );
1540 $response = $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1541 $this->assertEquals( AuthenticationResponse::newPass( 'UTDummy' ), $response );
1542 $this->assertNotNull( $this->manager->getRequest()->getSession()->getUser() );
1543 $this->assertSame( 'UTDummy', $this->manager->getRequest()->getSession()->getUser()->getName() );
1544
1545 // Will prevent login
1546 $updateManager();
1547 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
1548 $hook->willReturnCallback( static function ( $user, &$response, $authManager, $info ) {
1549 $response = AuthenticationResponse::newFail( wfMessage( 'hook-fail' ) );
1550 return false;
1551 } );
1552 $response = $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1553 $this->assertEquals( AuthenticationResponse::newFail( wfMessage( 'hook-fail' ) ), $response );
1554 $this->assertTrue( $this->manager->getRequest()->getSession()->getUser()->isAnon() );
1555
1556 // Will not allow invalid responses
1557 $updateManager();
1558 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
1559 $hook->willReturnCallback( static function ( $user, &$response, $authManager, $info ) {
1560 $response = 'invalid';
1561 return false;
1562 } );
1563 try {
1564 $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1565 $this->fail( 'Expected exception not thrown' );
1566 } catch ( LogicException $ex ) {
1567 $this->assertSame( '$response must be an AuthenticationResponse', $ex->getMessage() );
1568 }
1569
1570 $updateManager();
1571 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
1572 $hook->willReturnCallback( static function ( $user, &$response, $authManager, $info ) {
1573 $response = AuthenticationResponse::newPass( 'UTDummy' );
1574 } );
1575 try {
1576 $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1577 $this->fail( 'Expected exception not thrown' );
1578 } catch ( LogicException $ex ) {
1579 $this->assertSame( 'AuthManagerVerifyAuthenticationHook must not modify the response unless it returns false', $ex->getMessage() );
1580 }
1581
1582 $updateManager();
1583 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
1584 $hook->willReturnCallback( static function ( $user, &$response, $authManager, $info ) {
1585 return false;
1586 } );
1587 try {
1588 $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1589 $this->fail( 'Expected exception not thrown' );
1590 } catch ( LogicException $ex ) {
1591 $this->assertSame( 'AuthManagerVerifyAuthenticationHook must set the response to FAIL if it returns false', $ex->getMessage() );
1592 }
1593
1594 // Will prevent restart
1595 $primaryConfig['beginPrimaryAuthentication'] = AuthenticationResponse::newPass( null );
1596 unset( $secondaryConfig['beginSecondaryAuthentication'] );
1597 $updateManager();
1598 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
1599 $hook->willReturnCallback( function ( $user, &$response, $authManager, $info ) {
1600 $this->assertSame( AuthenticationResponse::RESTART, $response->status );
1601 $response = AuthenticationResponse::newFail( wfMessage( 'hook-fail' ) );
1602 return false;
1603 } );
1604 $response = $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1605 $this->assertEquals( AuthenticationResponse::newFail( wfMessage( 'hook-fail' ) ), $response );
1606 $this->assertTrue( $this->manager->getRequest()->getSession()->getUser()->isAnon() );
1607 $this->assertNull( $this->manager->getRequest()->getSession()->get( AuthManager::AUTHN_STATE ) );
1608 }
1609
1610 /**
1611 * @dataProvider provideUserExists
1612 * @param bool $primary1Exists
1613 * @param bool $primary2Exists
1614 * @param bool $expect
1615 */
1616 public function testUserExists( $primary1Exists, $primary2Exists, $expect ) {
1617 $userName = 'TestUserExists';
1618 $mock1 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1619 $mock1->method( 'getUniqueId' )
1620 ->willReturn( 'primary1' );
1621 $mock1->method( 'testUserExists' )
1622 ->with( $userName )
1623 ->willReturn( $primary1Exists );
1624 $mock2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1625 $mock2->method( 'getUniqueId' )
1626 ->willReturn( 'primary2' );
1627 $mock2->method( 'testUserExists' )
1628 ->with( $userName )
1629 ->willReturn( $primary2Exists );
1630 $this->primaryauthMocks = [ $mock1, $mock2 ];
1631
1632 $this->initializeManager( true );
1633 $this->assertSame( $expect, $this->manager->userExists( $userName ) );
1634 }
1635
1636 public static function provideUserExists() {
1637 return [
1638 [ false, false, false ],
1639 [ true, false, true ],
1640 [ false, true, true ],
1641 [ true, true, true ],
1642 ];
1643 }
1644
1645 /**
1646 * @dataProvider provideAllowsAuthenticationDataChange
1647 * @param StatusValue $primaryReturn
1648 * @param StatusValue $secondaryReturn
1649 * @param Status $expect
1650 */
1651 public function testAllowsAuthenticationDataChange( $primaryReturn, $secondaryReturn, $expect ) {
1652 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1653
1654 $mock1 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1655 $mock1->method( 'getUniqueId' )->willReturn( '1' );
1656 $mock1->method( 'providerAllowsAuthenticationDataChange' )
1657 ->with( $req )
1658 ->willReturn( $primaryReturn );
1659 $mock2 = $this->createMock( AbstractSecondaryAuthenticationProvider::class );
1660 $mock2->method( 'getUniqueId' )->willReturn( '2' );
1661 $mock2->method( 'providerAllowsAuthenticationDataChange' )
1662 ->with( $req )
1663 ->willReturn( $secondaryReturn );
1664
1665 $this->primaryauthMocks = [ $mock1 ];
1666 $this->secondaryauthMocks = [ $mock2 ];
1667 $this->initializeManager( true );
1668 $this->assertEquals( $expect, $this->manager->allowsAuthenticationDataChange( $req ) );
1669 }
1670
1671 public static function provideAllowsAuthenticationDataChange() {
1672 $ignored = Status::newGood( 'ignored' );
1673 $ignored->warning( 'authmanager-change-not-supported' );
1674
1675 $okFromPrimary = StatusValue::newGood();
1676 $okFromPrimary->warning( 'warning-from-primary' );
1677 $okFromSecondary = StatusValue::newGood();
1678 $okFromSecondary->warning( 'warning-from-secondary' );
1679
1680 $throttledMailPassword = StatusValue::newFatal( 'throttled-mailpassword' );
1681
1682 return [
1683 [
1684 StatusValue::newGood(),
1685 StatusValue::newGood(),
1686 Status::newGood(),
1687 ],
1688 [
1689 StatusValue::newGood(),
1690 StatusValue::newGood( 'ignore' ),
1691 Status::newGood(),
1692 ],
1693 [
1694 StatusValue::newGood( 'ignored' ),
1695 StatusValue::newGood(),
1696 Status::newGood(),
1697 ],
1698 [
1699 StatusValue::newGood( 'ignored' ),
1700 StatusValue::newGood( 'ignored' ),
1701 $ignored,
1702 ],
1703 [
1704 StatusValue::newFatal( 'fail from primary' ),
1705 StatusValue::newGood(),
1706 Status::newFatal( 'fail from primary' ),
1707 ],
1708 [
1709 $okFromPrimary,
1710 StatusValue::newGood(),
1711 Status::wrap( $okFromPrimary ),
1712 ],
1713 [
1714 StatusValue::newGood(),
1715 StatusValue::newFatal( 'fail from secondary' ),
1716 Status::newFatal( 'fail from secondary' ),
1717 ],
1718 [
1719 StatusValue::newGood(),
1720 $okFromSecondary,
1721 Status::wrap( $okFromSecondary ),
1722 ],
1723 [
1724 StatusValue::newGood(),
1725 $throttledMailPassword,
1726 Status::newGood( 'throttled-mailpassword' ),
1727 ]
1728 ];
1729 }
1730
1731 public function testChangeAuthenticationData() {
1732 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1733 $req->username = 'TestChangeAuthenticationData';
1734
1735 $mock1 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1736 $mock1->method( 'getUniqueId' )->willReturn( '1' );
1737 $mock1->expects( $this->once() )->method( 'providerChangeAuthenticationData' )
1738 ->with( $req );
1739 $mock2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1740 $mock2->method( 'getUniqueId' )->willReturn( '2' );
1741 $mock2->expects( $this->once() )->method( 'providerChangeAuthenticationData' )
1742 ->with( $req );
1743
1744 $this->primaryauthMocks = [ $mock1, $mock2 ];
1745 $this->initializeManager( true );
1746 $this->logger->setCollect( true );
1747 $this->manager->changeAuthenticationData( $req );
1748 $this->assertSame( [
1749 [ LogLevel::INFO, 'Changing authentication data for {user} class {what}' ],
1750 ], $this->logger->getBuffer() );
1751 }
1752
1753 public function testCanCreateAccounts() {
1754 $types = [
1755 PrimaryAuthenticationProvider::TYPE_CREATE => true,
1756 PrimaryAuthenticationProvider::TYPE_LINK => true,
1757 PrimaryAuthenticationProvider::TYPE_NONE => false,
1758 ];
1759
1760 foreach ( $types as $type => $can ) {
1761 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1762 $mock->method( 'getUniqueId' )->willReturn( $type );
1763 $mock->method( 'accountCreationType' )
1764 ->willReturn( $type );
1765 $this->primaryauthMocks = [ $mock ];
1766 $this->initializeManager( true );
1767 $this->assertSame( $can, $this->manager->canCreateAccounts(), $type );
1768 }
1769 }
1770
1771 /**
1772 * @covers \MediaWiki\Auth\AuthManager::probablyCanCreateAccount()
1773 */
1774 public function testProbablyCanCreateAccount() {
1775 $this->setGroupPermissions( '*', 'createaccount', true );
1776 $this->initializeManager( true );
1777 $this->assertEquals(
1778 StatusValue::newGood(),
1779 $this->manager->probablyCanCreateAccount( new User )
1780 );
1781 }
1782
1783 /**
1784 * @covers \MediaWiki\Auth\AuthManager::authorizeCreateAccount()
1785 */
1786 public function testAuthorizeCreateAccount_anon() {
1787 $this->setGroupPermissions( '*', 'createaccount', true );
1788 $this->initializeManager( true );
1789 $this->assertEquals(
1790 StatusValue::newGood(),
1791 $this->manager->authorizeCreateAccount( new User )
1792 );
1793 }
1794
1795 /**
1796 * @covers \MediaWiki\Auth\AuthManager::authorizeCreateAccount()
1797 */
1798 public function testAuthorizeCreateAccount_anonNotAllowed() {
1799 $this->setGroupPermissions( '*', 'createaccount', false );
1800 $this->initializeManager( true );
1801 $status = $this->manager->authorizeCreateAccount( new User );
1802 $this->assertStatusError( 'badaccess-groups', $status );
1803 }
1804
1805 /**
1806 * @covers \MediaWiki\Auth\AuthManager::authorizeCreateAccount()
1807 */
1808 public function testAuthorizeCreateAccount_readOnly() {
1809 $this->initializeManager( true );
1810 $readOnlyMode = $this->getServiceContainer()->getReadOnlyMode();
1811 $readOnlyMode->setReason( 'Because' );
1812 $this->assertEquals(
1813 StatusValue::newFatal( wfMessage( 'readonlytext', 'Because' ) ),
1814 $this->manager->authorizeCreateAccount( new User )
1815 );
1816 $readOnlyMode->setReason( false );
1817 }
1818
1819 /**
1820 * @covers \MediaWiki\Auth\AuthManager::authorizeCreateAccount()
1821 * @covers \MediaWiki\Permissions\PermissionManager::checkUserBlock()
1822 */
1823 public function testAuthorizeCreateAccount_blocked() {
1824 $this->initializeManager( true );
1825
1826 $user = User::newFromName( 'UTBlockee' );
1827 if ( $user->getId() == 0 ) {
1828 $user->addToDatabase();
1829 TestUser::setPasswordForUser( $user, 'UTBlockeePassword' );
1830 $user->saveSettings();
1831 }
1832 $blockStore = $this->getServiceContainer()->getDatabaseBlockStore();
1833 $blockOptions = [
1834 'address' => $user,
1835 'by' => $this->getTestSysop()->getUser(),
1836 'reason' => __METHOD__,
1837 'expiry' => time() + 100500,
1838 'createAccount' => true,
1839 ];
1840 $block = new DatabaseBlock( $blockOptions );
1841 $blockStore->insertBlock( $block );
1842 $this->resetServices();
1843 $this->initializeManager( true );
1844 $status = $this->manager->authorizeCreateAccount( $user );
1845 $this->assertStatusError( 'blockedtext', $status );
1846 }
1847
1848 /**
1849 * @covers \MediaWiki\Auth\AuthManager::authorizeCreateAccount()
1850 * @covers \MediaWiki\Permissions\PermissionManager::checkUserBlock()
1851 */
1852 public function testAuthorizeCreateAccount_ipBlocked() {
1853 $this->setGroupPermissions( '*', 'createaccount', true );
1854 $this->initializeManager( true );
1855 $blockStore = $this->getServiceContainer()->getDatabaseBlockStore();
1856 $blockOptions = [
1857 'address' => '127.0.0.0/24',
1858 'by' => $this->getTestSysop()->getUser(),
1859 'reason' => __METHOD__,
1860 'expiry' => time() + 100500,
1861 'createAccount' => true,
1862 'sitewide' => false,
1863 ];
1864 $block = new DatabaseBlock( $blockOptions );
1865 $blockStore->insertBlock( $block );
1866 $status = $this->manager->authorizeCreateAccount( new User );
1867 $this->assertStatusError( 'blockedtext-partial', $status );
1868 }
1869
1870 /**
1871 * @covers \MediaWiki\Auth\AuthManager::authorizeCreateAccount()
1872 */
1873 public function testAuthorizeCreateAccount_DNSBlacklist() {
1874 $this->overrideConfigValues( [
1875 MainConfigNames::EnableDnsBlacklist => true,
1876 MainConfigNames::DnsBlacklistUrls => [
1877 'localhost',
1878 ],
1879 MainConfigNames::ProxyWhitelist => [],
1880 ] );
1881 $this->initializeManager( true );
1882
1883 // For User::getBlockedStatus()
1884 $this->setService( 'BlockManager', $this->blockManager );
1885
1886 $status = $this->manager->authorizeCreateAccount( new User );
1887 $this->assertStatusError( 'sorbs_create_account_reason', $status );
1888
1889 $this->overrideConfigValue( MainConfigNames::ProxyWhitelist, [ '127.0.0.1' ] );
1890 $this->initializeManager( true );
1891 $this->setService( 'BlockManager', $this->blockManager );
1892 $status = $this->manager->authorizeCreateAccount( new User );
1893 $this->assertStatusGood( $status );
1894 }
1895
1896 /**
1897 * @covers \MediaWiki\Auth\AuthManager::authorizeCreateAccount()
1898 * @covers \MediaWiki\Permissions\PermissionManager::checkUserBlock()
1899 */
1900 public function testAuthorizeCreateAccount_ipIsBlockedByUserNot() {
1901 $this->initializeManager( true );
1902
1903 $user = User::newFromName( 'UTBlockee' );
1904 if ( $user->getId() == 0 ) {
1905 $user->addToDatabase();
1906 TestUser::setPasswordForUser( $user, 'UTBlockeePassword' );
1907 $user->saveSettings();
1908 }
1909 $blockStore = $this->getServiceContainer()->getDatabaseBlockStore();
1910 $blockOptions = [
1911 'address' => $user,
1912 'by' => $this->getTestSysop()->getUser(),
1913 'reason' => __METHOD__,
1914 'expiry' => time() + 100500,
1915 'createAccount' => false,
1916 ];
1917 $block = new DatabaseBlock( $blockOptions );
1918 $blockStore->insertBlock( $block );
1919
1920 $blockOptions = [
1921 'address' => '127.0.0.0/24',
1922 'by' => $this->getTestSysop()->getUser(),
1923 'reason' => __METHOD__,
1924 'expiry' => time() + 100500,
1925 'createAccount' => true,
1926 'sitewide' => false,
1927 ];
1928 $block = new DatabaseBlock( $blockOptions );
1929 $blockStore->insertBlock( $block );
1930
1931 $this->resetServices();
1932 $this->initializeManager( true );
1933 $status = $this->manager->authorizeCreateAccount( $user );
1934 $this->assertStatusError( 'blockedtext-partial', $status );
1935 }
1936
1937 /**
1938 * @param string $uniq
1939 * @return string
1940 */
1941 private static function usernameForCreation( $uniq = '' ) {
1942 $i = 0;
1943 do {
1944 $username = "UTAuthManagerTestAccountCreation" . $uniq . ++$i;
1945 } while ( User::newFromName( $username )->getId() !== 0 );
1946 return $username;
1947 }
1948
1949 public function testCanCreateAccount() {
1950 $username = self::usernameForCreation();
1951 $this->initializeManager();
1952
1953 $this->assertEquals(
1954 Status::newFatal( 'authmanager-create-disabled' ),
1955 $this->manager->canCreateAccount( $username )
1956 );
1957
1958 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1959 $mock->method( 'getUniqueId' )->willReturn( 'X' );
1960 $mock->method( 'accountCreationType' )
1961 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
1962 $mock->method( 'testUserExists' )->willReturn( true );
1963 $mock->method( 'testUserForCreation' )
1964 ->willReturn( StatusValue::newGood() );
1965 $this->primaryauthMocks = [ $mock ];
1966 $this->initializeManager( true );
1967
1968 $this->assertEquals(
1969 Status::newFatal( 'userexists' ),
1970 $this->manager->canCreateAccount( $username )
1971 );
1972
1973 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
1974 $mock->method( 'getUniqueId' )->willReturn( 'X' );
1975 $mock->method( 'accountCreationType' )
1976 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
1977 $mock->method( 'testUserExists' )->willReturn( false );
1978 $mock->method( 'testUserForCreation' )
1979 ->willReturn( StatusValue::newGood() );
1980 $this->primaryauthMocks = [ $mock ];
1981 $this->initializeManager( true );
1982
1983 $this->assertEquals(
1984 Status::newFatal( 'noname' ),
1985 $this->manager->canCreateAccount( $username . '<>' )
1986 );
1987
1988 $existingUserName = $this->getTestSysop()->getUserIdentity()->getName();
1989 $this->assertEquals(
1990 Status::newFatal( 'userexists' ),
1991 $this->manager->canCreateAccount( $existingUserName )
1992 );
1993
1994 $this->assertEquals(
1995 Status::newGood(),
1996 $this->manager->canCreateAccount( $username )
1997 );
1998
1999 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
2000 $mock->method( 'getUniqueId' )->willReturn( 'X' );
2001 $mock->method( 'accountCreationType' )
2002 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2003 $mock->method( 'testUserExists' )->willReturn( false );
2004 $mock->method( 'testUserForCreation' )
2005 ->willReturn( StatusValue::newFatal( 'fail' ) );
2006 $this->primaryauthMocks = [ $mock ];
2007 $this->initializeManager( true );
2008
2009 $this->assertEquals(
2010 Status::newFatal( 'fail' ),
2011 $this->manager->canCreateAccount( $username )
2012 );
2013 }
2014
2015 public function testBeginAccountCreation() {
2016 $creator = $this->getTestSysop()->getUser();
2017 $userReq = new UsernameAuthenticationRequest;
2018 $this->logger = new TestLogger( false, static function ( $message, $level ) {
2019 return $level === LogLevel::DEBUG ? null : $message;
2020 } );
2021 $this->initializeManager();
2022
2023 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE, 'test' );
2024 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2025 try {
2026 $this->manager->beginAccountCreation(
2027 $creator, [], 'http://localhost/'
2028 );
2029 $this->fail( 'Expected exception not thrown' );
2030 } catch ( LogicException $ex ) {
2031 $this->assertEquals( 'Account creation is not possible', $ex->getMessage() );
2032 }
2033 $this->unhook( 'LocalUserCreated' );
2034 $this->assertNull(
2035 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
2036 );
2037
2038 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
2039 $mock->method( 'getUniqueId' )->willReturn( 'X' );
2040 $mock->method( 'accountCreationType' )
2041 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2042 $mock->method( 'testUserExists' )->willReturn( true );
2043 $mock->method( 'testUserForCreation' )
2044 ->willReturn( StatusValue::newGood() );
2045 $this->primaryauthMocks = [ $mock ];
2046 $this->initializeManager( true );
2047
2048 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2049 $ret = $this->manager->beginAccountCreation( $creator, [], 'http://localhost/' );
2050 $this->unhook( 'LocalUserCreated' );
2051 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2052 $this->assertSame( 'noname', $ret->message->getKey() );
2053
2054 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2055 $userReq->username = self::usernameForCreation();
2056 $userReq2 = new UsernameAuthenticationRequest;
2057 $userReq2->username = $userReq->username . 'X';
2058 $ret = $this->manager->beginAccountCreation(
2059 $creator, [ $userReq, $userReq2 ], 'http://localhost/'
2060 );
2061 $this->unhook( 'LocalUserCreated' );
2062 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2063 $this->assertSame( 'noname', $ret->message->getKey() );
2064
2065 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2066 $readOnlyMode = $this->getServiceContainer()->getReadOnlyMode();
2067 $readOnlyMode->setReason( 'Because' );
2068 $userReq->username = self::usernameForCreation();
2069 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
2070 $this->unhook( 'LocalUserCreated' );
2071 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2072 $this->assertSame( 'readonlytext', $ret->message->getKey() );
2073 $this->assertSame( [ 'Because' ], $ret->message->getParams() );
2074 $readOnlyMode->setReason( false );
2075
2076 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2077 $userReq->username = self::usernameForCreation();
2078 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
2079 $this->unhook( 'LocalUserCreated' );
2080 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2081 $this->assertSame( 'userexists', $ret->message->getKey() );
2082
2083 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
2084 $mock->method( 'getUniqueId' )->willReturn( 'X' );
2085 $mock->method( 'accountCreationType' )
2086 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2087 $mock->method( 'testUserExists' )->willReturn( false );
2088 $mock->method( 'testUserForCreation' )
2089 ->willReturn( StatusValue::newFatal( 'fail' ) );
2090 $this->primaryauthMocks = [ $mock ];
2091 $this->initializeManager( true );
2092
2093 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2094 $userReq->username = self::usernameForCreation();
2095 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
2096 $this->unhook( 'LocalUserCreated' );
2097 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2098 $this->assertSame( 'fail', $ret->message->getKey() );
2099
2100 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
2101 $mock->method( 'getUniqueId' )->willReturn( 'X' );
2102 $mock->method( 'accountCreationType' )
2103 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2104 $mock->method( 'testUserExists' )->willReturn( false );
2105 $mock->method( 'testUserForCreation' )
2106 ->willReturn( StatusValue::newGood() );
2107 $this->primaryauthMocks = [ $mock ];
2108 $this->initializeManager( true );
2109
2110 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2111 $userReq->username = self::usernameForCreation() . '<>';
2112 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
2113 $this->unhook( 'LocalUserCreated' );
2114 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2115 $this->assertSame( 'noname', $ret->message->getKey() );
2116
2117 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2118 $userReq->username = $creator->getName();
2119 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
2120 $this->unhook( 'LocalUserCreated' );
2121 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2122 $this->assertSame( 'userexists', $ret->message->getKey() );
2123
2124 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
2125 $mock->method( 'getUniqueId' )->willReturn( 'X' );
2126 $mock->method( 'accountCreationType' )
2127 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2128 $mock->method( 'testUserExists' )->willReturn( false );
2129 $mock->method( 'testUserForCreation' )
2130 ->willReturn( StatusValue::newGood() );
2131 $mock->method( 'testForAccountCreation' )
2132 ->willReturn( StatusValue::newFatal( 'fail' ) );
2133 $this->primaryauthMocks = [ $mock ];
2134 $this->initializeManager( true );
2135
2136 $req = $this->getMockBuilder( UserDataAuthenticationRequest::class )
2137 ->onlyMethods( [ 'populateUser' ] )
2138 ->getMock();
2139 $req->method( 'populateUser' )
2140 ->willReturn( StatusValue::newFatal( 'populatefail' ) );
2141 $userReq->username = self::usernameForCreation();
2142 $ret = $this->manager->beginAccountCreation(
2143 $creator, [ $userReq, $req ], 'http://localhost/'
2144 );
2145 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2146 $this->assertSame( 'populatefail', $ret->message->getKey() );
2147
2148 $req = new UserDataAuthenticationRequest;
2149 $userReq->username = self::usernameForCreation();
2150
2151 $ret = $this->manager->beginAccountCreation(
2152 $creator, [ $userReq, $req ], 'http://localhost/'
2153 );
2154 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2155 $this->assertSame( 'fail', $ret->message->getKey() );
2156
2157 $this->manager->beginAccountCreation(
2158 User::newFromName( $userReq->username ), [ $userReq, $req ], 'http://localhost/'
2159 );
2160 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2161 $this->assertSame( 'fail', $ret->message->getKey() );
2162 }
2163
2164 public function testContinueAccountCreation() {
2165 $creator = $this->getTestSysop()->getUser();
2166 $username = self::usernameForCreation();
2167 $this->logger = new TestLogger( false, static function ( $message, $level ) {
2168 return $level === LogLevel::DEBUG ? null : $message;
2169 } );
2170 $this->initializeManager();
2171
2172 $session = [
2173 'userid' => 0,
2174 'username' => $username,
2175 'creatorid' => 0,
2176 'creatorname' => $username,
2177 'reqs' => [],
2178 'providerIds' => [ 'preauth' => [], 'primaryauth' => [], 'secondaryauth' => [] ],
2179 'primary' => null,
2180 'primaryResponse' => null,
2181 'secondary' => [],
2182 'ranPreTests' => true,
2183 ];
2184
2185 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2186 try {
2187 $this->manager->continueAccountCreation( [] );
2188 $this->fail( 'Expected exception not thrown' );
2189 } catch ( LogicException $ex ) {
2190 $this->assertEquals( 'Account creation is not possible', $ex->getMessage() );
2191 }
2192 $this->unhook( 'LocalUserCreated' );
2193
2194 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
2195 $mock->method( 'getUniqueId' )->willReturn( 'X' );
2196 $mock->method( 'accountCreationType' )
2197 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2198 $mock->method( 'testUserExists' )->willReturn( false );
2199 $mock->method( 'beginPrimaryAccountCreation' )
2200 ->willReturn( AuthenticationResponse::newFail( $this->message( 'fail' ) ) );
2201 $this->primaryauthMocks = [ $mock ];
2202 $session['providerIds']['primaryauth'][] = 'X';
2203 $this->initializeManager( true );
2204
2205 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE, null );
2206 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2207 $ret = $this->manager->continueAccountCreation( [] );
2208 $this->unhook( 'LocalUserCreated' );
2209 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2210 $this->assertSame( 'authmanager-create-not-in-progress', $ret->message->getKey() );
2211
2212 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE,
2213 [ 'username' => "$username<>" ] + $session );
2214 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2215 $ret = $this->manager->continueAccountCreation( [] );
2216 $this->unhook( 'LocalUserCreated' );
2217 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2218 $this->assertSame( 'noname', $ret->message->getKey() );
2219 $this->assertNull(
2220 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
2221 );
2222
2223 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE, $session );
2224 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2225 $cache = $this->objectCacheFactory->getLocalClusterInstance();
2226 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
2227 $ret = $this->manager->continueAccountCreation( [] );
2228 unset( $lock );
2229 $this->unhook( 'LocalUserCreated' );
2230 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2231 $this->assertSame( 'usernameinprogress', $ret->message->getKey() );
2232 // This error shouldn't remove the existing session, because the
2233 // raced-with process "owns" it.
2234 $this->assertSame(
2235 $session, $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
2236 );
2237
2238 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2239 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE,
2240 [ 'username' => $creator->getName() ] + $session );
2241 $readOnlyMode = $this->getServiceContainer()->getReadOnlyMode();
2242 $readOnlyMode->setReason( 'Because' );
2243 $ret = $this->manager->continueAccountCreation( [] );
2244 $this->unhook( 'LocalUserCreated' );
2245 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2246 $this->assertSame( 'readonlytext', $ret->message->getKey() );
2247 $this->assertSame( [ 'Because' ], $ret->message->getParams() );
2248 $readOnlyMode->setReason( false );
2249
2250 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE,
2251 [ 'username' => $creator->getName() ] + $session );
2252 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2253 $ret = $this->manager->continueAccountCreation( [] );
2254 $this->unhook( 'LocalUserCreated' );
2255 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2256 $this->assertSame( 'userexists', $ret->message->getKey() );
2257 $this->assertNull(
2258 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
2259 );
2260
2261 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE,
2262 [ 'userid' => $creator->getId() ] + $session );
2263 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2264 try {
2265 $ret = $this->manager->continueAccountCreation( [] );
2266 $this->fail( 'Expected exception not thrown' );
2267 } catch ( UnexpectedValueException $ex ) {
2268 $this->assertEquals( "User \"{$username}\" should exist now, but doesn't!", $ex->getMessage() );
2269 }
2270 $this->unhook( 'LocalUserCreated' );
2271 $this->assertNull(
2272 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
2273 );
2274
2275 $id = $creator->getId();
2276 $name = $creator->getName();
2277 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE,
2278 [ 'username' => $name, 'userid' => $id + 1 ] + $session );
2279 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2280 try {
2281 $ret = $this->manager->continueAccountCreation( [] );
2282 $this->fail( 'Expected exception not thrown' );
2283 } catch ( UnexpectedValueException $ex ) {
2284 $this->assertEquals(
2285 "User \"{$name}\" exists, but ID $id !== " . ( $id + 1 ) . '!', $ex->getMessage()
2286 );
2287 }
2288 $this->unhook( 'LocalUserCreated' );
2289 $this->assertNull(
2290 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
2291 );
2292
2293 $req = $this->getMockBuilder( UserDataAuthenticationRequest::class )
2294 ->onlyMethods( [ 'populateUser' ] )
2295 ->getMock();
2296 $req->method( 'populateUser' )
2297 ->willReturn( StatusValue::newFatal( 'populatefail' ) );
2298 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE,
2299 [ 'reqs' => [ $req ] ] + $session );
2300 $ret = $this->manager->continueAccountCreation( [] );
2301 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
2302 $this->assertSame( 'populatefail', $ret->message->getKey() );
2303 $this->assertNull(
2304 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE )
2305 );
2306 }
2307
2308 /**
2309 * @dataProvider provideAccountCreation
2310 * @param StatusValue $preTest
2311 * @param StatusValue $primaryTest
2312 * @param StatusValue $secondaryTest
2313 * @param array $primaryResponses
2314 * @param array $secondaryResponses
2315 * @param array $managerResponses
2316 */
2317 public function testAccountCreation(
2318 StatusValue $preTest, $primaryTest, $secondaryTest,
2319 array $primaryResponses, array $secondaryResponses, array $managerResponses
2320 ) {
2321 $creator = $this->getTestSysop()->getUser();
2322 $username = self::usernameForCreation();
2323
2324 $this->initializeManager();
2325
2326 // Set up lots of mocks...
2327 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
2328 $mocks = [];
2329 foreach ( [ 'pre', 'primary', 'secondary' ] as $key ) {
2330 $class = ucfirst( $key ) . 'AuthenticationProvider';
2331 $mocks[$key] = $this->getMockBuilder( "MediaWiki\\Auth\\Abstract$class" )
2332 ->setMockClassName( "MockAbstract$class" )
2333 ->getMock();
2334 $mocks[$key]->method( 'getUniqueId' )
2335 ->willReturn( $key );
2336 $mocks[$key]->method( 'testUserForCreation' )
2337 ->willReturn( StatusValue::newGood() );
2338 $mocks[$key]->method( 'testForAccountCreation' )
2339 ->willReturnCallback(
2340 function ( $user, $creatorIn, $reqs )
2341 use ( $username, $creator, $req, $key, $preTest, $primaryTest, $secondaryTest )
2342 {
2343 $this->assertSame( $username, $user->getName() );
2344 $this->assertSame( $creator->getId(), $creatorIn->getId() );
2345 $this->assertSame( $creator->getName(), $creatorIn->getName() );
2346 $foundReq = false;
2347 foreach ( $reqs as $r ) {
2348 $this->assertSame( $username, $r->username );
2349 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
2350 }
2351 $this->assertTrue( $foundReq, '$reqs contains $req' );
2352 if ( $key === 'pre' ) {
2353 return $preTest;
2354 }
2355 if ( $key === 'primary' ) {
2356 return $primaryTest;
2357 }
2358 return $secondaryTest;
2359 }
2360 );
2361
2362 for ( $i = 2; $i <= 3; $i++ ) {
2363 $mocks[$key . $i] = $this->createMock( "MediaWiki\\Auth\\Abstract$class" );
2364 $mocks[$key . $i]->method( 'getUniqueId' )
2365 ->willReturn( $key . $i );
2366 $mocks[$key . $i]->method( 'testUserForCreation' )
2367 ->willReturn( StatusValue::newGood() );
2368 $mocks[$key . $i]->expects( $this->atMost( 1 ) )->method( 'testForAccountCreation' )
2369 ->willReturn( StatusValue::newGood() );
2370 }
2371 }
2372
2373 $mocks['primary']->method( 'accountCreationType' )
2374 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2375 $mocks['primary']->method( 'testUserExists' )
2376 ->willReturn( false );
2377 $ct = count( $primaryResponses );
2378 $callback = $this->returnCallback( function ( $user, $creatorArg, $reqs ) use ( $creator, $username, $req, &$primaryResponses ) {
2379 $this->assertSame( $username, $user->getName() );
2380 $this->assertSame( $creator->getName(), $creatorArg->getName() );
2381 $foundReq = false;
2382 foreach ( $reqs as $r ) {
2383 $this->assertSame( $username, $r->username );
2384 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
2385 }
2386 $this->assertTrue( $foundReq, '$reqs contains $req' );
2387 return array_shift( $primaryResponses );
2388 } );
2389 $mocks['primary']->expects( $this->exactly( min( 1, $ct ) ) )
2390 ->method( 'beginPrimaryAccountCreation' )
2391 ->will( $callback );
2392 $mocks['primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
2393 ->method( 'continuePrimaryAccountCreation' )
2394 ->will( $callback );
2395
2396 $ct = count( $secondaryResponses );
2397 $callback = $this->returnCallback( function ( $user, $creatorArg, $reqs ) use ( $creator, $username, $req, &$secondaryResponses ) {
2398 $this->assertSame( $username, $user->getName() );
2399 $this->assertSame( $creator->getName(), $creatorArg->getName() );
2400 $foundReq = false;
2401 foreach ( $reqs as $r ) {
2402 $this->assertSame( $username, $r->username );
2403 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
2404 }
2405 $this->assertTrue( $foundReq, '$reqs contains $req' );
2406 return array_shift( $secondaryResponses );
2407 } );
2408 $mocks['secondary']->expects( $this->exactly( min( 1, $ct ) ) )
2409 ->method( 'beginSecondaryAccountCreation' )
2410 ->will( $callback );
2411 $mocks['secondary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
2412 ->method( 'continueSecondaryAccountCreation' )
2413 ->will( $callback );
2414
2415 $abstain = AuthenticationResponse::newAbstain();
2416 $mocks['primary2']->method( 'accountCreationType' )
2417 ->willReturn( PrimaryAuthenticationProvider::TYPE_LINK );
2418 $mocks['primary2']->method( 'testUserExists' )
2419 ->willReturn( false );
2420 $mocks['primary2']->expects( $this->atMost( 1 ) )->method( 'beginPrimaryAccountCreation' )
2421 ->willReturn( $abstain );
2422 $mocks['primary2']->expects( $this->never() )->method( 'continuePrimaryAccountCreation' );
2423 $mocks['primary3']->method( 'accountCreationType' )
2424 ->willReturn( PrimaryAuthenticationProvider::TYPE_NONE );
2425 $mocks['primary3']->method( 'testUserExists' )
2426 ->willReturn( false );
2427 $mocks['primary3']->expects( $this->never() )->method( 'beginPrimaryAccountCreation' );
2428 $mocks['primary3']->expects( $this->never() )->method( 'continuePrimaryAccountCreation' );
2429 $mocks['secondary2']->expects( $this->atMost( 1 ) )
2430 ->method( 'beginSecondaryAccountCreation' )
2431 ->willReturn( $abstain );
2432 $mocks['secondary2']->expects( $this->never() )->method( 'continueSecondaryAccountCreation' );
2433 $mocks['secondary3']->expects( $this->atMost( 1 ) )
2434 ->method( 'beginSecondaryAccountCreation' )
2435 ->willReturn( $abstain );
2436 $mocks['secondary3']->expects( $this->never() )->method( 'continueSecondaryAccountCreation' );
2437
2438 $this->preauthMocks = [ $mocks['pre'], $mocks['pre2'] ];
2439 $this->primaryauthMocks = [ $mocks['primary3'], $mocks['primary'], $mocks['primary2'] ];
2440 $this->secondaryauthMocks = [
2441 $mocks['secondary3'], $mocks['secondary'], $mocks['secondary2']
2442 ];
2443
2444 $this->logger = new TestLogger( true, static function ( $message, $level ) {
2445 return $level === LogLevel::DEBUG ? null : $message;
2446 } );
2447 $expectLog = [];
2448 $this->initializeManager( true );
2449
2450 $constraint = Assert::logicalOr(
2451 $this->equalTo( AuthenticationResponse::PASS ),
2452 $this->equalTo( AuthenticationResponse::FAIL )
2453 );
2454 $providers = array_merge(
2455 $this->preauthMocks, $this->primaryauthMocks, $this->secondaryauthMocks
2456 );
2457 foreach ( $providers as $p ) {
2458 DynamicPropertyTestHelper::setDynamicProperty( $p, 'postCalled', false );
2459 $p->expects( $this->atMost( 1 ) )->method( 'postAccountCreation' )
2460 ->willReturnCallback( function ( $user, $creatorArg, $response )
2461 use ( $creator, $constraint, $p, $username )
2462 {
2463 $this->assertInstanceOf( User::class, $user );
2464 $this->assertSame( $username, $user->getName() );
2465 $this->assertSame( $creator->getName(), $creatorArg->getName() );
2466 $this->assertInstanceOf( AuthenticationResponse::class, $response );
2467 $this->assertThat( $response->status, $constraint );
2468 DynamicPropertyTestHelper::setDynamicProperty( $p, 'postCalled', $response->status );
2469 } );
2470 }
2471
2472 // We're testing with $wgNewUserLog = false, so assert that it worked
2473 $dbw = $this->getDb();
2474 $maxLogId = $dbw->newSelectQueryBuilder()
2475 ->select( 'MAX(log_id)' )
2476 ->from( 'logging' )
2477 ->where( [ 'log_type' => 'newusers' ] )
2478 ->fetchField();
2479
2480 $first = true;
2481 $created = false;
2482 foreach ( $managerResponses as $i => $response ) {
2483 $success = $response instanceof AuthenticationResponse &&
2484 $response->status === AuthenticationResponse::PASS;
2485 if ( $i === 'created' ) {
2486 $created = true;
2487 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->once() )
2488 ->with(
2489 $this->callback( static function ( $user ) use ( $username ) {
2490 return $user->getName() === $username;
2491 } ),
2492 false
2493 );
2494 $expectLog[] = [ LogLevel::INFO, "Creating user {user} during account creation" ];
2495 } else {
2496 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2497 }
2498
2499 try {
2500 if ( $first ) {
2501 $userReq = new UsernameAuthenticationRequest;
2502 $userReq->username = $username;
2503 $ret = $this->manager->beginAccountCreation(
2504 $creator, [ $userReq, $req ], 'http://localhost/'
2505 );
2506 } else {
2507 $ret = $this->manager->continueAccountCreation( [ $req ] );
2508 }
2509 if ( $response instanceof Exception ) {
2510 $this->fail( 'Expected exception not thrown', "Response $i" );
2511 }
2512 } catch ( Exception $ex ) {
2513 if ( !$response instanceof Exception ) {
2514 throw $ex;
2515 }
2516 $this->assertEquals( $response->getMessage(), $ex->getMessage(), "Response $i, exception" );
2517 $this->assertNull(
2518 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE ),
2519 "Response $i, exception, session state"
2520 );
2521 $this->unhook( 'LocalUserCreated' );
2522 return;
2523 }
2524
2525 $this->unhook( 'LocalUserCreated' );
2526
2527 $this->assertSame( 'http://localhost/', $req->returnToUrl );
2528
2529 if ( $success ) {
2530 $this->assertNotNull( $ret->loginRequest, "Response $i, login marker" );
2531 $this->assertContains(
2532 $ret->loginRequest, $this->managerPriv->createdAccountAuthenticationRequests,
2533 "Response $i, login marker"
2534 );
2535
2536 $expectLog[] = [
2537 LogLevel::INFO,
2538 "MediaWiki\Auth\AuthManager::continueAccountCreation: Account creation succeeded for {user}"
2539 ];
2540
2541 // Set some fields in the expected $response that we couldn't
2542 // know in provideAccountCreation().
2543 $response->username = $username;
2544 $response->loginRequest = $ret->loginRequest;
2545 } else {
2546 $this->assertNull( $ret->loginRequest, "Response $i, login marker" );
2547 $this->assertSame( [], $this->managerPriv->createdAccountAuthenticationRequests,
2548 "Response $i, login marker" );
2549 }
2550 $ret->message = $this->message( $ret->message );
2551 $this->assertResponseEquals( $response, $ret, "Response $i, response" );
2552 if ( $success || $response->status === AuthenticationResponse::FAIL ) {
2553 $this->assertNull(
2554 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE ),
2555 "Response $i, session state"
2556 );
2557 foreach ( $providers as $p ) {
2558 $this->assertSame( $response->status, DynamicPropertyTestHelper::getDynamicProperty( $p, 'postCalled' ),
2559 "Response $i, post-auth callback called" );
2560 }
2561 } else {
2562 $this->assertNotNull(
2563 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_CREATION_STATE ),
2564 "Response $i, session state"
2565 );
2566 foreach ( $ret->neededRequests as $neededReq ) {
2567 $this->assertEquals( AuthManager::ACTION_CREATE, $neededReq->action,
2568 "Response $i, neededRequest action" );
2569 }
2570 $this->assertEquals(
2571 $ret->neededRequests,
2572 $this->manager->getAuthenticationRequests( AuthManager::ACTION_CREATE_CONTINUE ),
2573 "Response $i, continuation check"
2574 );
2575 foreach ( $providers as $p ) {
2576 $this->assertFalse( DynamicPropertyTestHelper::getDynamicProperty( $p, 'postCalled' ), "Response $i, post-auth callback not called" );
2577 }
2578 }
2579
2580 $userIdentity = $this->userIdentityLookup->getUserIdentityByName( $username );
2581 $this->assertSame( $created, $userIdentity && $userIdentity->isRegistered() );
2582
2583 $first = false;
2584 }
2585
2586 $this->assertSame( $expectLog, $this->logger->getBuffer() );
2587
2588 $this->assertSame(
2589 $maxLogId,
2590 $dbw->newSelectQueryBuilder()
2591 ->select( 'MAX(log_id)' )
2592 ->from( 'logging' )
2593 ->where( [ 'log_type' => 'newusers' ] )
2594 ->fetchField() );
2595 }
2596
2597 public function provideAccountCreation() {
2598 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
2599 $good = StatusValue::newGood();
2600
2601 return [
2602 'Pre-creation test fail in pre' => [
2603 StatusValue::newFatal( 'fail-from-pre' ), $good, $good,
2604 [],
2605 [],
2606 [
2607 AuthenticationResponse::newFail( $this->message( 'fail-from-pre' ) ),
2608 ]
2609 ],
2610 'Pre-creation test fail in primary' => [
2611 $good, StatusValue::newFatal( 'fail-from-primary' ), $good,
2612 [],
2613 [],
2614 [
2615 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
2616 ]
2617 ],
2618 'Pre-creation test fail in secondary' => [
2619 $good, $good, StatusValue::newFatal( 'fail-from-secondary' ),
2620 [],
2621 [],
2622 [
2623 AuthenticationResponse::newFail( $this->message( 'fail-from-secondary' ) ),
2624 ]
2625 ],
2626 'Failure in primary' => [
2627 $good, $good, $good,
2628 $tmp = [
2629 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
2630 ],
2631 [],
2632 $tmp
2633 ],
2634 'All primary abstain' => [
2635 $good, $good, $good,
2636 [
2637 AuthenticationResponse::newAbstain(),
2638 ],
2639 [],
2640 [
2641 AuthenticationResponse::newFail( $this->message( 'authmanager-create-no-primary' ) )
2642 ]
2643 ],
2644 'Primary UI, then redirect, then fail' => [
2645 $good, $good, $good,
2646 $tmp = [
2647 AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
2648 AuthenticationResponse::newRedirect( [ $req ], '/foo.html', [ 'foo' => 'bar' ] ),
2649 AuthenticationResponse::newFail( $this->message( 'fail-in-primary-continue' ) ),
2650 ],
2651 [],
2652 $tmp
2653 ],
2654 'Primary redirect, then abstain' => [
2655 $good, $good, $good,
2656 [
2657 $tmp = AuthenticationResponse::newRedirect(
2658 [ $req ], '/foo.html', [ 'foo' => 'bar' ]
2659 ),
2660 AuthenticationResponse::newAbstain(),
2661 ],
2662 [],
2663 [
2664 $tmp,
2665 new DomainException(
2666 'MockAbstractPrimaryAuthenticationProvider::continuePrimaryAccountCreation() returned ABSTAIN'
2667 )
2668 ]
2669 ],
2670 'Primary UI, then pass; secondary abstain' => [
2671 $good, $good, $good,
2672 [
2673 $tmp1 = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
2674 AuthenticationResponse::newPass(),
2675 ],
2676 [
2677 AuthenticationResponse::newAbstain(),
2678 ],
2679 [
2680 $tmp1,
2681 'created' => AuthenticationResponse::newPass( '' ),
2682 ]
2683 ],
2684 'Primary pass; secondary UI then pass' => [
2685 $good, $good, $good,
2686 [
2687 AuthenticationResponse::newPass( '' ),
2688 ],
2689 [
2690 $tmp1 = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
2691 AuthenticationResponse::newPass( '' ),
2692 ],
2693 [
2694 'created' => $tmp1,
2695 AuthenticationResponse::newPass( '' ),
2696 ]
2697 ],
2698 'Primary pass; secondary fail' => [
2699 $good, $good, $good,
2700 [
2701 AuthenticationResponse::newPass(),
2702 ],
2703 [
2704 AuthenticationResponse::newFail( $this->message( '...' ) ),
2705 ],
2706 [
2707 'created' => new DomainException(
2708 'MockAbstractSecondaryAuthenticationProvider::beginSecondaryAccountCreation() returned FAIL. ' .
2709 'Secondary providers are not allowed to fail account creation, ' .
2710 'that should have been done via testForAccountCreation().'
2711 )
2712 ]
2713 ],
2714 ];
2715 }
2716
2717 /**
2718 * @dataProvider provideAccountCreationLogging
2719 * @param bool $isAnon
2720 * @param string|null $logSubtype
2721 */
2722 public function testAccountCreationLogging( $isAnon, $logSubtype ) {
2723 $creator = $isAnon ? new User : $this->getTestSysop()->getUser();
2724 $username = self::usernameForCreation();
2725
2726 $this->initializeManager();
2727
2728 // Set up lots of mocks...
2729 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
2730 $mock->method( 'getUniqueId' )
2731 ->willReturn( 'primary' );
2732 $mock->method( 'testUserForCreation' )
2733 ->willReturn( StatusValue::newGood() );
2734 $mock->method( 'testForAccountCreation' )
2735 ->willReturn( StatusValue::newGood() );
2736 $mock->method( 'accountCreationType' )
2737 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2738 $mock->method( 'testUserExists' )
2739 ->willReturn( false );
2740 $mock->method( 'beginPrimaryAccountCreation' )
2741 ->willReturn( AuthenticationResponse::newPass( $username ) );
2742 $mock->method( 'finishAccountCreation' )
2743 ->willReturn( $logSubtype );
2744
2745 $this->primaryauthMocks = [ $mock ];
2746 $this->initializeManager( true );
2747 $this->logger->setCollect( true );
2748
2749 $this->config->set( MainConfigNames::NewUserLog, true );
2750
2751 $dbw = $this->getDb();
2752 $maxLogId = $dbw->newSelectQueryBuilder()
2753 ->select( 'MAX(log_id)' )
2754 ->from( 'logging' )
2755 ->where( [ 'log_type' => 'newusers' ] )
2756 ->fetchField();
2757
2758 $userReq = new UsernameAuthenticationRequest;
2759 $userReq->username = $username;
2760 $reasonReq = new CreationReasonAuthenticationRequest;
2761 $reasonReq->reason = $this->toString();
2762 $ret = $this->manager->beginAccountCreation(
2763 $creator, [ $userReq, $reasonReq ], 'http://localhost/'
2764 );
2765
2766 $this->assertSame( AuthenticationResponse::PASS, $ret->status );
2767
2768 $user = User::newFromName( $username );
2769 $this->assertNotEquals( 0, $user->getId() );
2770 $this->assertNotEquals( $creator->getId(), $user->getId() );
2771
2772 $queryBuilder = DatabaseLogEntry::newSelectQueryBuilder( $dbw )
2773 ->where( [ 'log_id > ' . (int)$maxLogId, 'log_type' => 'newusers' ] );
2774 $rows = iterator_to_array( $queryBuilder->caller( __METHOD__ )->fetchResultSet() );
2775 $this->assertCount( 1, $rows );
2776 $entry = DatabaseLogEntry::newFromRow( reset( $rows ) );
2777
2778 $this->assertSame( $logSubtype ?: ( $isAnon ? 'create' : 'create2' ), $entry->getSubtype() );
2779 $this->assertSame(
2780 $isAnon ? $user->getId() : $creator->getId(),
2781 $entry->getPerformerIdentity()->getId()
2782 );
2783 $this->assertSame(
2784 $isAnon ? $user->getName() : $creator->getName(),
2785 $entry->getPerformerIdentity()->getName()
2786 );
2787 $this->assertSame( $user->getUserPage()->getFullText(), $entry->getTarget()->getFullText() );
2788 $this->assertSame( [ '4::userid' => $user->getId() ], $entry->getParameters() );
2789 $this->assertSame( $this->toString(), $entry->getComment() );
2790 }
2791
2792 public static function provideAccountCreationLogging() {
2793 return [
2794 [ true, null ],
2795 [ true, 'foobar' ],
2796 [ false, null ],
2797 [ false, 'byemail' ],
2798 ];
2799 }
2800
2801 public function testAccountCreation_AuthManagerVerifyAuthentication() {
2802 $this->logger = new NullLogger();
2803 $this->initializeManager();
2804
2805 $primaryConfig = [
2806 'getUniqueId' => 'primary',
2807 'accountCreationType' => PrimaryAuthenticationProvider::TYPE_CREATE,
2808 'testUserForCreation' => StatusValue::newGood(),
2809 'testForAccountCreation' => StatusValue::newGood(),
2810 'getAuthenticationRequests' => [],
2811 'beginPrimaryAccountCreation' => AuthenticationResponse::newPass(),
2812 ];
2813 $secondaryConfig = [
2814 'getUniqueId' => 'secondary',
2815 'testUserForCreation' => StatusValue::newGood(),
2816 'testForAccountCreation' => StatusValue::newGood(),
2817 'getAuthenticationRequests' => [],
2818 'beginSecondaryAccountCreation' => AuthenticationResponse::newAbstain(),
2819 ];
2820 $updateManager = function () use ( &$primaryConfig, &$secondaryConfig ) {
2821 $primaryMock = $this->createConfiguredMock( AbstractPrimaryAuthenticationProvider::class, $primaryConfig );
2822 foreach ( [ 'beginPrimaryAccountCreation', 'continuePrimaryAccountCreation' ] as $method ) {
2823 $primaryMock->expects(
2824 array_key_exists( $method, $primaryConfig ) ? $this->once() : $this->never()
2825 )->method( $method );
2826 }
2827 $secondaryMock = $this->createConfiguredMock( AbstractSecondaryAuthenticationProvider::class, $secondaryConfig );
2828 foreach ( [ 'beginSecondaryAccountCreation', 'continueSecondaryAccountCreation' ] as $method ) {
2829 $secondaryMock->expects(
2830 array_key_exists( $method, $secondaryConfig ) ? $this->once() : $this->never()
2831 )->method( $method );
2832 }
2833 $this->primaryauthMocks = [ $primaryMock ];
2834 $this->secondaryauthMocks = [ $secondaryMock ];
2835 $this->initializeManager( true );
2836 };
2837 $req = new UsernameAuthenticationRequest();
2838 $req->username = 'UTDummy';
2839
2840 // Gets expected data
2841 $updateManager();
2842 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
2843 $hook->willReturnCallback( function ( $user, &$response, $authManager, $info ) {
2844 $this->assertSame( 'UTDummy', $user->getName() );
2845 $this->assertSame( AuthenticationResponse::PASS, $response->status );
2846 $this->assertSame( $this->manager, $authManager );
2847 $this->assertSame( AuthManager::ACTION_CREATE, $info['action'] );
2848 $this->assertSame( 'primary', $info['primaryId'] );
2849 } );
2850 $response = $this->manager->beginAccountCreation( new User(), [ $req ], 'http://localhost/' );
2851 // Simplify verifying $response, loginRequest would include the user ID
2852 $response->loginRequest = null;
2853 $this->assertEquals( AuthenticationResponse::newPass( 'UTDummy' ), $response );
2854 $this->assertNotNull( $this->manager->getRequest()->getSession()->getUser() );
2855 $this->assertTrue( $this->getServiceContainer()->getUserFactory()->newFromName( 'UTDummy' )->isRegistered() );
2856
2857 // Will prevent login
2858 unset( $secondaryConfig['beginSecondaryAccountCreation'] );
2859 $updateManager();
2860 $req = new UsernameAuthenticationRequest();
2861 $req->username = 'UTDummy2';
2862 $hook = $this->hook( 'AuthManagerVerifyAuthentication', AuthManagerVerifyAuthenticationHook::class, $this->once() );
2863 $hook->willReturnCallback( static function ( $user, &$response, $authManager, $info ) {
2864 $response = AuthenticationResponse::newFail( wfMessage( 'hook-fail' ) );
2865 return false;
2866 } );
2867 $response = $this->manager->beginAccountCreation( new User(), [ $req ], 'http://localhost/' );
2868 $this->assertEquals( AuthenticationResponse::newFail( wfMessage( 'hook-fail' ) ), $response );
2869 $this->assertFalse( $this->getServiceContainer()->getUserFactory()->newFromName( 'UTDummy2' )->isRegistered() );
2870
2871 // the LogicError paths are already tested under testAuthentication_AuthManagerVerifyAuthentication
2872 }
2873
2874 public function testAutoAccountCreation() {
2875 // PHPUnit seems to have a bug where it will call the ->with()
2876 // callbacks for our hooks again after the test is run (WTF?), which
2877 // breaks here because $username no longer matches $user by the end of
2878 // the testing.
2879 $workaroundPHPUnitBug = false;
2880
2881 $username = self::usernameForCreation();
2882 $expectedSource = AuthManager::AUTOCREATE_SOURCE_SESSION;
2883
2884 $this->setGroupPermissions( '*', 'createaccount', true );
2885 $this->setGroupPermissions( '*', 'autocreateaccount', false );
2886 $this->initializeManager( true );
2887
2888 // Set up lots of mocks...
2889 $mocks = [];
2890 foreach ( [ 'pre', 'primary', 'secondary' ] as $key ) {
2891 $class = ucfirst( $key ) . 'AuthenticationProvider';
2892 $mocks[$key] = $this->createMock( "MediaWiki\\Auth\\Abstract$class" );
2893 $mocks[$key]->method( 'getUniqueId' )
2894 ->willReturn( $key );
2895 }
2896
2897 $good = StatusValue::newGood();
2898 $ok = StatusValue::newFatal( 'ok' );
2899 $callback = $this->callback( static function ( $user ) use ( &$username, &$workaroundPHPUnitBug ) {
2900 return $workaroundPHPUnitBug || $user->getName() === $username;
2901 } );
2902 $callback2 = $this->callback(
2903 static function ( $source ) use ( &$expectedSource, &$workaroundPHPUnitBug ) {
2904 return $workaroundPHPUnitBug || $source === $expectedSource;
2905 }
2906 );
2907
2908 $mocks['pre']->expects( $this->exactly( 13 ) )->method( 'testUserForCreation' )
2909 ->with( $callback, $callback2 )
2910 ->willReturnOnConsecutiveCalls(
2911 $ok, $ok, $ok, // For testing permissions
2912 StatusValue::newFatal( 'fail-in-pre' ), $good, $good,
2913 $good, // backoff test
2914 $good, // addToDatabase fails test
2915 $good, // addToDatabase throws test
2916 $good, // addToDatabase exists test
2917 $good, $good, $good // success
2918 );
2919
2920 $mocks['primary']->method( 'accountCreationType' )
2921 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
2922 $mocks['primary']->method( 'testUserExists' )
2923 ->willReturn( true );
2924 $mocks['primary']->expects( $this->exactly( 9 ) )->method( 'testUserForCreation' )
2925 ->with( $callback, $callback2 )
2926 ->willReturnOnConsecutiveCalls(
2927 StatusValue::newFatal( 'fail-in-primary' ), $good,
2928 $good, // backoff test
2929 $good, // addToDatabase fails test
2930 $good, // addToDatabase throws test
2931 $good, // addToDatabase exists test
2932 $good, $good, $good
2933 );
2934 $mocks['primary']->expects( $this->exactly( 3 ) )->method( 'autoCreatedAccount' )
2935 ->with( $callback, $callback2 );
2936
2937 $mocks['secondary']->expects( $this->exactly( 8 ) )->method( 'testUserForCreation' )
2938 ->with( $callback, $callback2 )
2939 ->willReturnOnConsecutiveCalls(
2940 StatusValue::newFatal( 'fail-in-secondary' ),
2941 $good, // backoff test
2942 $good, // addToDatabase fails test
2943 $good, // addToDatabase throws test
2944 $good, // addToDatabase exists test
2945 $good, $good, $good
2946 );
2947 $mocks['secondary']->expects( $this->exactly( 3 ) )->method( 'autoCreatedAccount' )
2948 ->with( $callback, $callback2 );
2949
2950 $this->preauthMocks = [ $mocks['pre'] ];
2951 $this->primaryauthMocks = [ $mocks['primary'] ];
2952 $this->secondaryauthMocks = [ $mocks['secondary'] ];
2953 $this->initializeManager( true );
2954 $session = $this->request->getSession();
2955
2956 $logger = new TestLogger( true, static function ( $m ) {
2957 $m = str_replace( 'MediaWiki\\Auth\\AuthManager::autoCreateUser: ', '', $m );
2958 return $m;
2959 } );
2960 $this->logger = $logger;
2961 $this->manager->setLogger( $logger );
2962
2963 try {
2964 $userMock = $this->createMock( User::class );
2965 $this->manager->autoCreateUser( $userMock, 'InvalidSource', true, true );
2966 $this->fail( 'Expected exception not thrown' );
2967 } catch ( InvalidArgumentException $ex ) {
2968 $this->assertSame( 'Unknown auto-creation source: InvalidSource', $ex->getMessage() );
2969 }
2970
2971 // First, check an existing user
2972 $session->clear();
2973 $existingUser = $this->getTestSysop()->getUser();
2974 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2975 $ret = $this->manager->autoCreateUser( $existingUser, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
2976 $this->unhook( 'LocalUserCreated' );
2977 $expect = Status::newGood();
2978 $expect->warning( 'userexists' );
2979 $this->assertEquals( $expect, $ret );
2980 $this->assertNotEquals( 0, $existingUser->getId() );
2981 $this->assertEquals( $existingUser->getId(), $session->getUser()->getId() );
2982 $this->assertSame( [
2983 [ LogLevel::DEBUG, '{username} already exists locally' ],
2984 ], $logger->getBuffer() );
2985 $logger->clearBuffer();
2986
2987 $session->clear();
2988 $user = $this->getTestSysop()->getUser();
2989 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
2990 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, false, true );
2991 $this->unhook( 'LocalUserCreated' );
2992 $expect = Status::newGood();
2993 $expect->warning( 'userexists' );
2994 $this->assertEquals( $expect, $ret );
2995 $this->assertNotEquals( 0, $user->getId() );
2996 $this->assertSame( 0, $session->getUser()->getId() );
2997 $this->assertSame( [
2998 [ LogLevel::DEBUG, '{username} already exists locally' ],
2999 ], $logger->getBuffer() );
3000 $logger->clearBuffer();
3001
3002 // Wiki is read-only
3003 $session->clear();
3004 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3005 $readOnlyMode = $this->getServiceContainer()->getReadOnlyMode();
3006 $readOnlyMode->setReason( 'Because' );
3007 $user = User::newFromName( $username );
3008 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3009 $this->unhook( 'LocalUserCreated' );
3010 $this->assertEquals( Status::newFatal( wfMessage( 'readonlytext', 'Because' ) ), $ret );
3011 $this->assertSame( 0, $user->getId() );
3012 $this->assertNotEquals( $username, $user->getName() );
3013 $this->assertSame( 0, $session->getUser()->getId() );
3014 $this->assertSame( [
3015 [ LogLevel::DEBUG, 'denied because of read only mode: {reason}' ],
3016 ], $logger->getBuffer() );
3017 $logger->clearBuffer();
3018 $readOnlyMode->setReason( false );
3019
3020 // Session blacklisted
3021 $session->clear();
3022 $session->set( AuthManager::AUTOCREATE_BLOCKLIST, 'test' );
3023 $user = User::newFromName( $username );
3024 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3025 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3026 $this->unhook( 'LocalUserCreated' );
3027 $this->assertEquals( Status::newFatal( 'test' ), $ret );
3028 $this->assertSame( 0, $user->getId() );
3029 $this->assertNotEquals( $username, $user->getName() );
3030 $this->assertSame( 0, $session->getUser()->getId() );
3031 $this->assertSame( [
3032 [ LogLevel::DEBUG, 'blacklisted in session {sessionid}' ],
3033 ], $logger->getBuffer() );
3034 $logger->clearBuffer();
3035
3036 $session->clear();
3037 $session->set( AuthManager::AUTOCREATE_BLOCKLIST, StatusValue::newFatal( 'test2' ) );
3038 $user = User::newFromName( $username );
3039 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3040 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3041 $this->unhook( 'LocalUserCreated' );
3042 $this->assertEquals( Status::newFatal( 'test2' ), $ret );
3043 $this->assertSame( 0, $user->getId() );
3044 $this->assertNotEquals( $username, $user->getName() );
3045 $this->assertSame( 0, $session->getUser()->getId() );
3046 $this->assertSame( [
3047 [ LogLevel::DEBUG, 'blacklisted in session {sessionid}' ],
3048 ], $logger->getBuffer() );
3049 $logger->clearBuffer();
3050
3051 // Invalid name
3052 $session->clear();
3053 $user = User::newFromName( $username . "\u{0080}", false );
3054 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3055 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3056 $this->unhook( 'LocalUserCreated' );
3057 $this->assertEquals( Status::newFatal( 'noname' ), $ret );
3058 $this->assertSame( 0, $user->getId() );
3059 $this->assertNotEquals( $username . "\u{0080}", $user->getId() );
3060 $this->assertSame( 0, $session->getUser()->getId() );
3061 $this->assertSame( [
3062 [ LogLevel::DEBUG, 'name "{username}" is not usable' ],
3063 ], $logger->getBuffer() );
3064 $logger->clearBuffer();
3065 $this->assertSame( 'noname', $session->get( AuthManager::AUTOCREATE_BLOCKLIST ) );
3066
3067 // IP unable to create accounts
3068 $this->setGroupPermissions( '*', 'createaccount', false );
3069 $this->setGroupPermissions( '*', 'autocreateaccount', false );
3070 $this->initializeManager( true );
3071 $session = $this->request->getSession();
3072 $user = User::newFromName( $username );
3073 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3074 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3075 $this->unhook( 'LocalUserCreated' );
3076 $this->assertTrue( $ret->hasMessage( 'badaccess-group0' ) );
3077 $this->assertSame( 0, $user->getId() );
3078 $this->assertNotEquals( $username, $user->getName() );
3079 $this->assertSame( 0, $session->getUser()->getId() );
3080 $this->assertSame( [
3081 [ LogLevel::DEBUG, 'cannot create or autocreate accounts' ],
3082 ], $logger->getBuffer() );
3083 $logger->clearBuffer();
3084 $this->assertEquals(
3085 (string)$ret, (string)$session->get( AuthManager::AUTOCREATE_BLOCKLIST )
3086 );
3087
3088 // maintenance scripts always work
3089 $expectedSource = AuthManager::AUTOCREATE_SOURCE_MAINT;
3090 $this->setGroupPermissions( '*', 'createaccount', false );
3091 $this->setGroupPermissions( '*', 'autocreateaccount', false );
3092 $this->initializeManager( true );
3093 $session = $this->request->getSession();
3094 $user = User::newFromName( $username );
3095 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3096 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_MAINT, true, false );
3097 $this->unhook( 'LocalUserCreated' );
3098 $this->assertStatusError( 'ok', $ret );
3099
3100 // Test that both permutations of permissions are allowed
3101 // (this hits the two "ok" entries in $mocks['pre'])
3102 $expectedSource = AuthManager::AUTOCREATE_SOURCE_SESSION;
3103 $this->setGroupPermissions( '*', 'createaccount', false );
3104 $this->setGroupPermissions( '*', 'autocreateaccount', true );
3105 $this->initializeManager( true );
3106 $session = $this->request->getSession();
3107 $user = User::newFromName( $username );
3108 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3109 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3110 $this->unhook( 'LocalUserCreated' );
3111 $this->assertStatusError( 'ok', $ret );
3112
3113 $this->setGroupPermissions( '*', 'createaccount', true );
3114 $this->setGroupPermissions( '*', 'autocreateaccount', false );
3115 $this->initializeManager( true );
3116 $session = $this->request->getSession();
3117 $user = User::newFromName( $username );
3118 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3119 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3120 $this->unhook( 'LocalUserCreated' );
3121 $this->assertStatusError( 'ok', $ret );
3122 $logger->clearBuffer();
3123
3124 // Test lock fail
3125 $session->clear();
3126 $user = User::newFromName( $username );
3127 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3128 $cache = $this->objectCacheFactory->getLocalClusterInstance();
3129 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
3130 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3131 unset( $lock );
3132 $this->unhook( 'LocalUserCreated' );
3133 $this->assertStatusError( 'usernameinprogress', $ret );
3134 $this->assertSame( 0, $user->getId() );
3135 $this->assertNotEquals( $username, $user->getName() );
3136 $this->assertSame( 0, $session->getUser()->getId() );
3137 $this->assertSame( [
3138 [ LogLevel::DEBUG, 'Could not acquire account creation lock' ],
3139 ], $logger->getBuffer() );
3140 $logger->clearBuffer();
3141
3142 // Test pre-authentication provider fail
3143 $session->clear();
3144 $user = User::newFromName( $username );
3145 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3146 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3147 $this->unhook( 'LocalUserCreated' );
3148 $this->assertStatusError( 'fail-in-pre', $ret );
3149 $this->assertSame( 0, $user->getId() );
3150 $this->assertNotEquals( $username, $user->getName() );
3151 $this->assertSame( 0, $session->getUser()->getId() );
3152 $this->assertSame( [
3153 [ LogLevel::DEBUG, 'Provider denied creation of {username}: {reason}' ],
3154 ], $logger->getBuffer() );
3155 $logger->clearBuffer();
3156 $this->assertEquals(
3157 StatusValue::newFatal( 'fail-in-pre' ), $session->get( AuthManager::AUTOCREATE_BLOCKLIST )
3158 );
3159
3160 $session->clear();
3161 $user = User::newFromName( $username );
3162 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3163 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3164 $this->unhook( 'LocalUserCreated' );
3165 $this->assertStatusError( 'fail-in-primary', $ret );
3166 $this->assertSame( 0, $user->getId() );
3167 $this->assertNotEquals( $username, $user->getName() );
3168 $this->assertSame( 0, $session->getUser()->getId() );
3169 $this->assertSame( [
3170 [ LogLevel::DEBUG, 'Provider denied creation of {username}: {reason}' ],
3171 ], $logger->getBuffer() );
3172 $logger->clearBuffer();
3173 $this->assertEquals(
3174 StatusValue::newFatal( 'fail-in-primary' ), $session->get( AuthManager::AUTOCREATE_BLOCKLIST )
3175 );
3176
3177 $session->clear();
3178 $user = User::newFromName( $username );
3179 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3180 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3181 $this->unhook( 'LocalUserCreated' );
3182 $this->assertStatusError( 'fail-in-secondary', $ret );
3183 $this->assertSame( 0, $user->getId() );
3184 $this->assertNotEquals( $username, $user->getName() );
3185 $this->assertSame( 0, $session->getUser()->getId() );
3186 $this->assertSame( [
3187 [ LogLevel::DEBUG, 'Provider denied creation of {username}: {reason}' ],
3188 ], $logger->getBuffer() );
3189 $logger->clearBuffer();
3190 $this->assertEquals(
3191 StatusValue::newFatal( 'fail-in-secondary' ), $session->get( AuthManager::AUTOCREATE_BLOCKLIST )
3192 );
3193
3194 // Test backoff
3195 $cache = $this->objectCacheFactory->getLocalClusterInstance();
3196 $backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
3197 $cache->set( $backoffKey, true );
3198 $session->clear();
3199 $user = User::newFromName( $username );
3200 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3201 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3202 $this->unhook( 'LocalUserCreated' );
3203 $this->assertStatusError( 'authmanager-autocreate-exception', $ret );
3204 $this->assertSame( 0, $user->getId() );
3205 $this->assertNotEquals( $username, $user->getName() );
3206 $this->assertSame( 0, $session->getUser()->getId() );
3207 $this->assertSame( [
3208 [ LogLevel::DEBUG, '{username} denied by prior creation attempt failures' ],
3209 ], $logger->getBuffer() );
3210 $logger->clearBuffer();
3211 $this->assertSame( null, $session->get( AuthManager::AUTOCREATE_BLOCKLIST ) );
3212 $cache->delete( $backoffKey );
3213
3214 // Test addToDatabase fails
3215 $session->clear();
3216 $user = $this->getMockBuilder( User::class )
3217 ->onlyMethods( [ 'addToDatabase' ] )->getMock();
3218 $user->expects( $this->once() )->method( 'addToDatabase' )
3219 ->willReturn( Status::newFatal( 'because' ) );
3220 $user->setName( $username );
3221 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3222 $this->assertStatusError( 'because', $ret );
3223 $this->assertSame( 0, $user->getId() );
3224 $this->assertNotEquals( $username, $user->getName() );
3225 $this->assertSame( 0, $session->getUser()->getId() );
3226 $this->assertSame( [
3227 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
3228 [ LogLevel::ERROR, '{username} failed with message {msg}' ],
3229 ], $logger->getBuffer() );
3230 $logger->clearBuffer();
3231 $this->assertSame( null, $session->get( AuthManager::AUTOCREATE_BLOCKLIST ) );
3232
3233 // Test addToDatabase throws an exception
3234 $cache = $this->objectCacheFactory->getLocalClusterInstance();
3235 $backoffKey = $cache->makeKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
3236 $this->assertFalse( $cache->get( $backoffKey ) );
3237 $session->clear();
3238 $user = $this->getMockBuilder( User::class )
3239 ->onlyMethods( [ 'addToDatabase' ] )->getMock();
3240 $user->expects( $this->once() )->method( 'addToDatabase' )
3241 ->willThrowException( new Exception( 'Excepted' ) );
3242 $user->setName( $username );
3243 try {
3244 $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3245 $this->fail( 'Expected exception not thrown' );
3246 } catch ( Exception $ex ) {
3247 $this->assertSame( 'Excepted', $ex->getMessage() );
3248 }
3249 $this->assertSame( 0, $user->getId() );
3250 $this->assertSame( 0, $session->getUser()->getId() );
3251 $this->assertSame( [
3252 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
3253 [ LogLevel::ERROR, '{username} failed with exception {exception}' ],
3254 ], $logger->getBuffer() );
3255 $logger->clearBuffer();
3256 $this->assertSame( null, $session->get( AuthManager::AUTOCREATE_BLOCKLIST ) );
3257 $this->assertNotFalse( $cache->get( $backoffKey ) );
3258 $cache->delete( $backoffKey );
3259
3260 // Test addToDatabase fails because the user already exists.
3261 $session->clear();
3262 $user = $this->getMockBuilder( User::class )
3263 ->onlyMethods( [ 'addToDatabase' ] )->getMock();
3264 $user->expects( $this->once() )->method( 'addToDatabase' )
3265 ->willReturnCallback( function () use ( $username, &$user ) {
3266 $oldUser = User::newFromName( $username );
3267 $status = $oldUser->addToDatabase();
3268 $this->assertStatusOK( $status );
3269 $user->setId( $oldUser->getId() );
3270 return Status::newFatal( 'userexists' );
3271 } );
3272 $user->setName( $username );
3273 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3274 $expect = Status::newGood();
3275 $expect->warning( 'userexists' );
3276 $this->assertEquals( $expect, $ret );
3277 $this->assertNotEquals( 0, $user->getId() );
3278 $this->assertEquals( $username, $user->getName() );
3279 $this->assertEquals( $user->getId(), $session->getUser()->getId() );
3280 $this->assertSame( [
3281 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
3282 [ LogLevel::INFO, '{username} already exists locally (race)' ],
3283 ], $logger->getBuffer() );
3284 $logger->clearBuffer();
3285 $this->assertSame( null, $session->get( AuthManager::AUTOCREATE_BLOCKLIST ) );
3286
3287 // Success!
3288 $session->clear();
3289 $username = self::usernameForCreation();
3290 $user = User::newFromName( $username );
3291 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->once() )
3292 ->with( $callback, true );
3293 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true, true );
3294 $this->unhook( 'LocalUserCreated' );
3295 $this->assertEquals( Status::newGood(), $ret );
3296 $this->assertNotEquals( 0, $user->getId() );
3297 $this->assertEquals( $username, $user->getName() );
3298 $this->assertEquals( $user->getId(), $session->getUser()->getId() );
3299 $this->assertSame( [
3300 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
3301 ], $logger->getBuffer() );
3302 $logger->clearBuffer();
3303
3304 $dbw = $this->getDb();
3305 $maxLogId = $dbw->newSelectQueryBuilder()
3306 ->select( 'MAX(log_id)' )
3307 ->from( 'logging' )
3308 ->where( [ 'log_type' => 'newusers' ] )
3309 ->fetchField();
3310 $session->clear();
3311 $username = self::usernameForCreation();
3312 $user = User::newFromName( $username );
3313 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->once() )
3314 ->with( $callback, true );
3315 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, false, true );
3316 $this->unhook( 'LocalUserCreated' );
3317 $this->assertEquals( Status::newGood(), $ret );
3318 $this->assertNotEquals( 0, $user->getId() );
3319 $this->assertEquals( $username, $user->getName() );
3320 $this->assertSame( 0, $session->getUser()->getId() );
3321 $this->assertSame( [
3322 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
3323 ], $logger->getBuffer() );
3324 $logger->clearBuffer();
3325 $this->assertSame(
3326 $maxLogId,
3327 $dbw->newSelectQueryBuilder()
3328 ->select( 'MAX(log_id)' )
3329 ->from( 'logging' )
3330 ->where( [ 'log_type' => 'newusers' ] )
3331 ->fetchField() );
3332
3333 $this->config->set( MainConfigNames::NewUserLog, true );
3334 $session->clear();
3335 $username = self::usernameForCreation();
3336 $user = User::newFromName( $username );
3337 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, false, true );
3338 $this->assertEquals( Status::newGood(), $ret );
3339 $logger->clearBuffer();
3340
3341 $queryBuilder = DatabaseLogEntry::newSelectQueryBuilder( $dbw )
3342 ->where( [ 'log_id > ' . (int)$maxLogId, 'log_type' => 'newusers' ] );
3343 $rows = iterator_to_array( $queryBuilder->caller( __METHOD__ )->fetchResultSet() );
3344 $this->assertCount( 1, $rows );
3345 $entry = DatabaseLogEntry::newFromRow( reset( $rows ) );
3346
3347 $this->assertSame( 'autocreate', $entry->getSubtype() );
3348 $this->assertSame( $user->getId(), $entry->getPerformerIdentity()->getId() );
3349 $this->assertSame( $user->getName(), $entry->getPerformerIdentity()->getName() );
3350 $this->assertSame( $user->getUserPage()->getFullText(), $entry->getTarget()->getFullText() );
3351 $this->assertSame( [ '4::userid' => $user->getId() ], $entry->getParameters() );
3352
3353 $workaroundPHPUnitBug = true;
3354 }
3355
3356 /**
3357 * @dataProvider provideAutoCreateUserBlocks
3358 */
3359 public function testAutoCreateUserBlocks(
3360 string $blockType,
3361 array $blockOptions,
3362 string $performerType,
3363 bool $expectedStatus
3364
3365 ) {
3366 if ( $blockType === 'ip' ) {
3367 $blockOptions['address'] = '127.0.0.0/24';
3368 } elseif ( $blockType === 'global-ip' ) {
3369 $this->setTemporaryHook( 'GetUserBlock',
3370 static function ( $user, $ip, &$block ) use ( $blockOptions ) {
3371 $block = new SystemBlock( $blockOptions );
3372 $block->isCreateAccountBlocked( true );
3373 }
3374 );
3375 $blockOptions = null;
3376 } elseif ( $blockType === 'none' ) {
3377 $blockOptions = null;
3378 } else {
3379 $this->fail( "Unknown block type \"$blockType\"" );
3380 }
3381
3382 if ( $blockOptions !== null ) {
3383 $blockOptions += [
3384 'by' => $this->getTestSysop()->getUser(),
3385 'reason' => __METHOD__,
3386 'expiry' => time() + 100500,
3387 ];
3388 $blockStore = $this->getServiceContainer()->getDatabaseBlockStore();
3389 $block = new DatabaseBlock( $blockOptions );
3390 $blockStore->insertBlock( $block );
3391 }
3392
3393 if ( $performerType === 'sysop' ) {
3394 $performer = $this->getTestSysop()->getUser();
3395 } elseif ( $performerType === 'anon' ) {
3396 $performer = null;
3397 } else {
3398 $this->fail( "Unknown performer type \"$performerType\"" );
3399 }
3400
3401 $this->logger = LoggerFactory::getInstance( 'AuthManagerTest' );
3402 $this->initializeManager( true );
3403
3404 $user = $this->userFactory->newFromName( 'NewUser' );
3405 $status = $this->manager->autoCreateUser( $user,
3406 AuthManager::AUTOCREATE_SOURCE_SESSION, true, true, $performer );
3407 $this->assertSame( $expectedStatus, $status->isGood() );
3408 }
3409
3410 public static function provideAutoCreateUserBlocks() {
3411 return [
3412 // block type (ip/global/none), block options, performer, expected status
3413 'not blocked' => [ 'none', [], 'anon', true ],
3414 'ip-blocked' => [ 'ip', [], 'anon', true ],
3415 'ip-blocked with createAccount' => [
3416 'ip',
3417 [ 'createAccount' => true ],
3418 'anon',
3419 false
3420 ],
3421 'partially ip-blocked' => [
3422 'ip',
3423 [ 'restrictions' => [ new PageRestriction( 0, 1 ) ] ],
3424 'anon',
3425 true
3426 ],
3427 'ip-blocked with sysop performer' => [
3428 'ip',
3429 [ 'createAccount' => true ],
3430 'sysop',
3431 true
3432 ],
3433 'globally blocked' => [
3434 'global-ip',
3435 [ 'systemBlock' => 'test-systemBlock' ],
3436 'anon',
3437 false
3438 ],
3439 ];
3440 }
3441
3442 /**
3443 * @dataProvider provideGetAuthenticationRequests
3444 * @param string $action
3445 * @param array $expect
3446 * @param array $state
3447 */
3448 public function testGetAuthenticationRequests( $action, $expect, $state = [] ) {
3449 $makeReq = function ( $key ) use ( $action ) {
3450 $req = $this->createMock( AuthenticationRequest::class );
3451 $req->method( 'getUniqueId' )
3452 ->willReturn( $key );
3453 $req->action = $action === AuthManager::ACTION_UNLINK ? AuthManager::ACTION_REMOVE : $action;
3454 return $req;
3455 };
3456 $cmpReqs = static function ( $a, $b ) {
3457 $ret = strcmp( get_class( $a ), get_class( $b ) );
3458 if ( !$ret ) {
3459 $ret = strcmp( $a->getUniqueId(), $b->getUniqueId() );
3460 }
3461 return $ret;
3462 };
3463
3464 $good = StatusValue::newGood();
3465
3466 $mocks = [];
3467 $mocks['pre'] = $this->createMock( AbstractPreAuthenticationProvider::class );
3468 $mocks['pre']->method( 'getUniqueId' )
3469 ->willReturn( 'pre' );
3470 $mocks['pre']->method( 'getAuthenticationRequests' )
3471 ->willReturnCallback( static function ( $action ) use ( $makeReq ) {
3472 return [ $makeReq( "pre-$action" ), $makeReq( 'generic' ) ];
3473 } );
3474 foreach ( [ 'primary', 'secondary' ] as $key ) {
3475 $class = ucfirst( $key ) . 'AuthenticationProvider';
3476 $mocks[$key] = $this->createMock( "MediaWiki\\Auth\\Abstract$class" );
3477 $mocks[$key]->method( 'getUniqueId' )
3478 ->willReturn( $key );
3479 $mocks[$key]->method( 'getAuthenticationRequests' )
3480 ->willReturnCallback( static function ( $action ) use ( $key, $makeReq ) {
3481 return [ $makeReq( "$key-$action" ), $makeReq( 'generic' ) ];
3482 } );
3483 $mocks[$key]->method( 'providerAllowsAuthenticationDataChange' )
3484 ->willReturn( $good );
3485 }
3486
3487 foreach ( [
3488 PrimaryAuthenticationProvider::TYPE_NONE,
3489 PrimaryAuthenticationProvider::TYPE_CREATE,
3490 PrimaryAuthenticationProvider::TYPE_LINK
3491 ] as $type ) {
3492 $class = 'PrimaryAuthenticationProvider';
3493 $mocks["primary-$type"] = $this->createMock( "MediaWiki\\Auth\\Abstract$class" );
3494 $mocks["primary-$type"]->method( 'getUniqueId' )
3495 ->willReturn( "primary-$type" );
3496 $mocks["primary-$type"]->method( 'accountCreationType' )
3497 ->willReturn( $type );
3498 $mocks["primary-$type"]->method( 'getAuthenticationRequests' )
3499 ->willReturnCallback( static function ( $action ) use ( $type, $makeReq ) {
3500 return [ $makeReq( "primary-$type-$action" ), $makeReq( 'generic' ) ];
3501 } );
3502 $mocks["primary-$type"]->method( 'providerAllowsAuthenticationDataChange' )
3503 ->willReturn( $good );
3504 $this->primaryauthMocks[] = $mocks["primary-$type"];
3505 }
3506
3507 $mocks['primary2'] = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3508 $mocks['primary2']->method( 'getUniqueId' )
3509 ->willReturn( 'primary2' );
3510 $mocks['primary2']->method( 'accountCreationType' )
3511 ->willReturn( PrimaryAuthenticationProvider::TYPE_LINK );
3512 $mocks['primary2']->method( 'getAuthenticationRequests' )
3513 ->willReturn( [] );
3514 $mocks['primary2']->method( 'providerAllowsAuthenticationDataChange' )
3515 ->willReturnCallback( static function ( $req ) use ( $good ) {
3516 return $req->getUniqueId() === 'generic' ? StatusValue::newFatal( 'no' ) : $good;
3517 } );
3518 $this->primaryauthMocks[] = $mocks['primary2'];
3519
3520 $this->preauthMocks = [ $mocks['pre'] ];
3521 $this->secondaryauthMocks = [ $mocks['secondary'] ];
3522 $this->initializeManager( true );
3523
3524 if ( $state ) {
3525 if ( isset( $state['continueRequests'] ) ) {
3526 $state['continueRequests'] = array_map( $makeReq, $state['continueRequests'] );
3527 }
3528 if ( $action === AuthManager::ACTION_LOGIN_CONTINUE ) {
3529 $this->request->getSession()->setSecret( AuthManager::AUTHN_STATE, $state );
3530 } elseif ( $action === AuthManager::ACTION_CREATE_CONTINUE ) {
3531 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_CREATION_STATE, $state );
3532 } elseif ( $action === AuthManager::ACTION_LINK_CONTINUE ) {
3533 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_LINK_STATE, $state );
3534 }
3535 }
3536
3537 $expectReqs = array_map( $makeReq, $expect );
3538 if ( $action === AuthManager::ACTION_LOGIN ) {
3539 $req = new RememberMeAuthenticationRequest;
3540 $req->action = $action;
3541 $req->required = AuthenticationRequest::REQUIRED;
3542 $expectReqs[] = $req;
3543 } elseif ( $action === AuthManager::ACTION_CREATE ) {
3544 $req = new UsernameAuthenticationRequest;
3545 $req->action = $action;
3546 $expectReqs[] = $req;
3547 $req = new UserDataAuthenticationRequest;
3548 $req->action = $action;
3549 $req->required = AuthenticationRequest::REQUIRED;
3550 $expectReqs[] = $req;
3551 }
3552 usort( $expectReqs, $cmpReqs );
3553
3554 $actual = $this->manager->getAuthenticationRequests( $action );
3555 foreach ( $actual as $req ) {
3556 // Don't test this here.
3557 $req->required = AuthenticationRequest::REQUIRED;
3558 }
3559 usort( $actual, $cmpReqs );
3560
3561 $this->assertEquals( $expectReqs, $actual );
3562
3563 // Test CreationReasonAuthenticationRequest gets returned
3564 if ( $action === AuthManager::ACTION_CREATE ) {
3565 $req = new CreationReasonAuthenticationRequest;
3566 $req->action = $action;
3567 $req->required = AuthenticationRequest::REQUIRED;
3568 $expectReqs[] = $req;
3569 usort( $expectReqs, $cmpReqs );
3570
3571 $user = $this->getTestSysop()->getUser();
3572 $actual = $this->manager->getAuthenticationRequests( $action, $user );
3573 foreach ( $actual as $req ) {
3574 // Don't test this here.
3575 $req->required = AuthenticationRequest::REQUIRED;
3576 }
3577 usort( $actual, $cmpReqs );
3578
3579 $this->assertEquals( $expectReqs, $actual );
3580 }
3581 }
3582
3583 public static function provideGetAuthenticationRequests() {
3584 return [
3585 [
3586 AuthManager::ACTION_LOGIN,
3587 [ 'pre-login', 'primary-none-login', 'primary-create-login',
3588 'primary-link-login', 'secondary-login', 'generic' ],
3589 ],
3590 [
3591 AuthManager::ACTION_CREATE,
3592 [ 'pre-create', 'primary-none-create', 'primary-create-create',
3593 'primary-link-create', 'secondary-create', 'generic' ],
3594 ],
3595 [
3596 AuthManager::ACTION_LINK,
3597 [ 'primary-link-link', 'generic' ],
3598 ],
3599 [
3600 AuthManager::ACTION_CHANGE,
3601 [ 'primary-none-change', 'primary-create-change', 'primary-link-change',
3602 'secondary-change' ],
3603 ],
3604 [
3605 AuthManager::ACTION_REMOVE,
3606 [ 'primary-none-remove', 'primary-create-remove', 'primary-link-remove',
3607 'secondary-remove' ],
3608 ],
3609 [
3610 AuthManager::ACTION_UNLINK,
3611 [ 'primary-link-remove' ],
3612 ],
3613 [
3614 AuthManager::ACTION_LOGIN_CONTINUE,
3615 [],
3616 ],
3617 [
3618 AuthManager::ACTION_LOGIN_CONTINUE,
3619 $reqs = [ 'continue-login', 'foo', 'bar' ],
3620 [
3621 'continueRequests' => $reqs,
3622 ],
3623 ],
3624 [
3625 AuthManager::ACTION_CREATE_CONTINUE,
3626 [],
3627 ],
3628 [
3629 AuthManager::ACTION_CREATE_CONTINUE,
3630 $reqs = [ 'continue-create', 'foo', 'bar' ],
3631 [
3632 'continueRequests' => $reqs,
3633 ],
3634 ],
3635 [
3636 AuthManager::ACTION_LINK_CONTINUE,
3637 [],
3638 ],
3639 [
3640 AuthManager::ACTION_LINK_CONTINUE,
3641 $reqs = [ 'continue-link', 'foo', 'bar' ],
3642 [
3643 'continueRequests' => $reqs,
3644 ],
3645 ],
3646 ];
3647 }
3648
3649 public function testGetAuthenticationRequestsRequired() {
3650 $makeReq = function ( $key, $required ) {
3651 $req = $this->createMock( AuthenticationRequest::class );
3652 $req->method( 'getUniqueId' )
3653 ->willReturn( $key );
3654 $req->action = AuthManager::ACTION_LOGIN;
3655 $req->required = $required;
3656 return $req;
3657 };
3658 $cmpReqs = static function ( $a, $b ) {
3659 $ret = strcmp( get_class( $a ), get_class( $b ) );
3660 if ( !$ret ) {
3661 $ret = strcmp( $a->getUniqueId(), $b->getUniqueId() );
3662 }
3663 return $ret;
3664 };
3665
3666 $primary1 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3667 $primary1->method( 'getUniqueId' )
3668 ->willReturn( 'primary1' );
3669 $primary1->method( 'accountCreationType' )
3670 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
3671 $primary1->method( 'getAuthenticationRequests' )
3672 ->willReturnCallback( static function ( $action ) use ( $makeReq ) {
3673 return [
3674 $makeReq( "primary-shared", AuthenticationRequest::REQUIRED ),
3675 $makeReq( "required", AuthenticationRequest::REQUIRED ),
3676 $makeReq( "optional", AuthenticationRequest::OPTIONAL ),
3677 $makeReq( "foo", AuthenticationRequest::REQUIRED ),
3678 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3679 $makeReq( "baz", AuthenticationRequest::OPTIONAL ),
3680 ];
3681 } );
3682
3683 $primary2 = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3684 $primary2->method( 'getUniqueId' )
3685 ->willReturn( 'primary2' );
3686 $primary2->method( 'accountCreationType' )
3687 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
3688 $primary2->method( 'getAuthenticationRequests' )
3689 ->willReturnCallback( static function ( $action ) use ( $makeReq ) {
3690 return [
3691 $makeReq( "primary-shared", AuthenticationRequest::REQUIRED ),
3692 $makeReq( "required2", AuthenticationRequest::REQUIRED ),
3693 $makeReq( "optional2", AuthenticationRequest::OPTIONAL ),
3694 ];
3695 } );
3696
3697 $secondary = $this->createMock( AbstractSecondaryAuthenticationProvider::class );
3698 $secondary->method( 'getUniqueId' )
3699 ->willReturn( 'secondary' );
3700 $secondary->method( 'getAuthenticationRequests' )
3701 ->willReturnCallback( static function ( $action ) use ( $makeReq ) {
3702 return [
3703 $makeReq( "foo", AuthenticationRequest::OPTIONAL ),
3704 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3705 $makeReq( "baz", AuthenticationRequest::REQUIRED ),
3706 ];
3707 } );
3708
3709 $rememberReq = new RememberMeAuthenticationRequest;
3710 $rememberReq->action = AuthManager::ACTION_LOGIN;
3711
3712 $this->primaryauthMocks = [ $primary1, $primary2 ];
3713 $this->secondaryauthMocks = [ $secondary ];
3714 $this->initializeManager( true );
3715
3716 $actual = $this->manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN );
3717 $expected = [
3718 $rememberReq,
3719 $makeReq( "primary-shared", AuthenticationRequest::PRIMARY_REQUIRED ),
3720 $makeReq( "required", AuthenticationRequest::PRIMARY_REQUIRED ),
3721 $makeReq( "required2", AuthenticationRequest::PRIMARY_REQUIRED ),
3722 $makeReq( "optional", AuthenticationRequest::OPTIONAL ),
3723 $makeReq( "optional2", AuthenticationRequest::OPTIONAL ),
3724 $makeReq( "foo", AuthenticationRequest::PRIMARY_REQUIRED ),
3725 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3726 $makeReq( "baz", AuthenticationRequest::REQUIRED ),
3727 ];
3728 usort( $actual, $cmpReqs );
3729 usort( $expected, $cmpReqs );
3730 $this->assertEquals( $expected, $actual );
3731
3732 $this->primaryauthMocks = [ $primary1 ];
3733 $this->secondaryauthMocks = [ $secondary ];
3734 $this->initializeManager( true );
3735
3736 $actual = $this->manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN );
3737 $expected = [
3738 $rememberReq,
3739 $makeReq( "primary-shared", AuthenticationRequest::PRIMARY_REQUIRED ),
3740 $makeReq( "required", AuthenticationRequest::PRIMARY_REQUIRED ),
3741 $makeReq( "optional", AuthenticationRequest::OPTIONAL ),
3742 $makeReq( "foo", AuthenticationRequest::PRIMARY_REQUIRED ),
3743 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3744 $makeReq( "baz", AuthenticationRequest::REQUIRED ),
3745 ];
3746 usort( $actual, $cmpReqs );
3747 usort( $expected, $cmpReqs );
3748 $this->assertEquals( $expected, $actual );
3749 }
3750
3751 public function testAllowsPropertyChange() {
3752 $mocks = [];
3753 foreach ( [ 'primary', 'secondary' ] as $key ) {
3754 $class = ucfirst( $key ) . 'AuthenticationProvider';
3755 $mocks[$key] = $this->createMock( "MediaWiki\\Auth\\Abstract$class" );
3756 $mocks[$key]->method( 'getUniqueId' )
3757 ->willReturn( $key );
3758 $mocks[$key]->method( 'providerAllowsPropertyChange' )
3759 ->willReturnCallback( static function ( $prop ) use ( $key ) {
3760 return $prop !== $key;
3761 } );
3762 }
3763
3764 $this->primaryauthMocks = [ $mocks['primary'] ];
3765 $this->secondaryauthMocks = [ $mocks['secondary'] ];
3766 $this->initializeManager( true );
3767
3768 $this->assertTrue( $this->manager->allowsPropertyChange( 'foo' ) );
3769 $this->assertFalse( $this->manager->allowsPropertyChange( 'primary' ) );
3770 $this->assertFalse( $this->manager->allowsPropertyChange( 'secondary' ) );
3771 }
3772
3773 public function testAutoCreateOnLogin() {
3774 $username = self::usernameForCreation();
3775
3776 $req = $this->createMock( AuthenticationRequest::class );
3777
3778 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3779 $mock->method( 'getUniqueId' )->willReturn( 'primary' );
3780 $mock->method( 'beginPrimaryAuthentication' )
3781 ->willReturn( AuthenticationResponse::newPass( $username ) );
3782 $mock->method( 'accountCreationType' )
3783 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
3784 $mock->method( 'testUserExists' )->willReturn( true );
3785 $mock->method( 'testUserForCreation' )
3786 ->willReturn( StatusValue::newGood() );
3787
3788 $mock2 = $this->createMock( AbstractSecondaryAuthenticationProvider::class );
3789 $mock2->method( 'getUniqueId' )
3790 ->willReturn( 'secondary' );
3791 $mock2->method( 'beginSecondaryAuthentication' )
3792 ->willReturn( AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ) );
3793 $mock2->method( 'continueSecondaryAuthentication' )
3794 ->willReturn( AuthenticationResponse::newAbstain() );
3795 $mock2->method( 'testUserForCreation' )
3796 ->willReturn( StatusValue::newGood() );
3797
3798 $this->primaryauthMocks = [ $mock ];
3799 $this->secondaryauthMocks = [ $mock2 ];
3800 $this->initializeManager( true );
3801 $this->manager->setLogger( new NullLogger() );
3802 $session = $this->request->getSession();
3803 $session->clear();
3804
3805 $this->assertSame( 0, User::newFromName( $username )->getId() );
3806
3807 $callback = $this->callback( static function ( $user ) use ( $username ) {
3808 return $user->getName() === $username;
3809 } );
3810
3811 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->never() );
3812 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->once() )
3813 ->with( $callback, true );
3814 $ret = $this->manager->beginAuthentication( [], 'http://localhost/' );
3815 $this->unhook( 'LocalUserCreated' );
3816 $this->unhook( 'UserLoggedIn' );
3817 $this->assertSame( AuthenticationResponse::UI, $ret->status );
3818
3819 $id = (int)User::newFromName( $username )->getId();
3820 $this->assertNotSame( 0, User::newFromName( $username )->getId() );
3821 $this->assertSame( 0, $session->getUser()->getId() );
3822
3823 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->once() )
3824 ->with( $callback );
3825 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3826 $ret = $this->manager->continueAuthentication( [] );
3827 $this->unhook( 'LocalUserCreated' );
3828 $this->unhook( 'UserLoggedIn' );
3829 $this->assertSame( AuthenticationResponse::PASS, $ret->status );
3830 $this->assertSame( $username, $ret->username );
3831 $this->assertSame( $id, $session->getUser()->getId() );
3832 }
3833
3834 public function testAutoCreateFailOnLogin() {
3835 $username = self::usernameForCreation();
3836
3837 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3838 $mock->method( 'getUniqueId' )->willReturn( 'primary' );
3839 $mock->method( 'beginPrimaryAuthentication' )
3840 ->willReturn( AuthenticationResponse::newPass( $username ) );
3841 $mock->method( 'accountCreationType' )
3842 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
3843 $mock->method( 'testUserExists' )->willReturn( true );
3844 $mock->method( 'testUserForCreation' )
3845 ->willReturn( StatusValue::newFatal( 'fail-from-primary' ) );
3846
3847 $this->primaryauthMocks = [ $mock ];
3848 $this->initializeManager( true );
3849 $this->manager->setLogger( new NullLogger() );
3850 $session = $this->request->getSession();
3851 $session->clear();
3852
3853 $this->assertSame( 0, $session->getUser()->getId() );
3854 $this->assertSame( 0, User::newFromName( $username )->getId() );
3855
3856 $this->hook( 'UserLoggedIn', UserLoggedInHook::class, $this->never() );
3857 $this->hook( 'LocalUserCreated', LocalUserCreatedHook::class, $this->never() );
3858 $ret = $this->manager->beginAuthentication( [], 'http://localhost/' );
3859 $this->unhook( 'LocalUserCreated' );
3860 $this->unhook( 'UserLoggedIn' );
3861 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3862 $this->assertSame( 'authmanager-authn-autocreate-failed', $ret->message->getKey() );
3863
3864 $this->assertSame( 0, User::newFromName( $username )->getId() );
3865 $this->assertSame( 0, $session->getUser()->getId() );
3866 }
3867
3868 public function testAuthenticationSessionData() {
3869 $this->initializeManager( true );
3870
3871 $this->assertNull( $this->manager->getAuthenticationSessionData( 'foo' ) );
3872 $this->manager->setAuthenticationSessionData( 'foo', 'foo!' );
3873 $this->manager->setAuthenticationSessionData( 'bar', 'bar!' );
3874 $this->assertSame( 'foo!', $this->manager->getAuthenticationSessionData( 'foo' ) );
3875 $this->assertSame( 'bar!', $this->manager->getAuthenticationSessionData( 'bar' ) );
3876 $this->manager->removeAuthenticationSessionData( 'foo' );
3877 $this->assertNull( $this->manager->getAuthenticationSessionData( 'foo' ) );
3878 $this->assertSame( 'bar!', $this->manager->getAuthenticationSessionData( 'bar' ) );
3879 $this->manager->removeAuthenticationSessionData( 'bar' );
3880 $this->assertNull( $this->manager->getAuthenticationSessionData( 'bar' ) );
3881
3882 $this->manager->setAuthenticationSessionData( 'foo', 'foo!' );
3883 $this->manager->setAuthenticationSessionData( 'bar', 'bar!' );
3884 $this->manager->removeAuthenticationSessionData( null );
3885 $this->assertNull( $this->manager->getAuthenticationSessionData( 'foo' ) );
3886 $this->assertNull( $this->manager->getAuthenticationSessionData( 'bar' ) );
3887 }
3888
3889 public function testCanLinkAccounts() {
3890 $types = [
3891 PrimaryAuthenticationProvider::TYPE_CREATE => false,
3892 PrimaryAuthenticationProvider::TYPE_LINK => true,
3893 PrimaryAuthenticationProvider::TYPE_NONE => false,
3894 ];
3895
3896 foreach ( $types as $type => $can ) {
3897 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3898 $mock->method( 'getUniqueId' )->willReturn( $type );
3899 $mock->method( 'accountCreationType' )
3900 ->willReturn( $type );
3901 $this->primaryauthMocks = [ $mock ];
3902 $this->initializeManager( true );
3903 $this->assertSame( $can, $this->manager->canLinkAccounts(), $type );
3904 }
3905 }
3906
3907 public function testBeginAccountLink() {
3908 $user = $this->getTestSysop()->getUser();
3909 $this->initializeManager();
3910
3911 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_LINK_STATE, 'test' );
3912 try {
3913 $this->manager->beginAccountLink( $user, [], 'http://localhost/' );
3914 $this->fail( 'Expected exception not thrown' );
3915 } catch ( LogicException $ex ) {
3916 $this->assertEquals( 'Account linking is not possible', $ex->getMessage() );
3917 }
3918 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::ACCOUNT_LINK_STATE ) );
3919
3920 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3921 $mock->method( 'getUniqueId' )->willReturn( 'X' );
3922 $mock->method( 'accountCreationType' )
3923 ->willReturn( PrimaryAuthenticationProvider::TYPE_LINK );
3924 $this->primaryauthMocks = [ $mock ];
3925 $this->initializeManager( true );
3926
3927 $ret = $this->manager->beginAccountLink( new User, [], 'http://localhost/' );
3928 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3929 $this->assertSame( 'noname', $ret->message->getKey() );
3930
3931 $ret = $this->manager->beginAccountLink(
3932 User::newFromName( 'UTDoesNotExist' ), [], 'http://localhost/'
3933 );
3934 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3935 $this->assertSame( 'authmanager-userdoesnotexist', $ret->message->getKey() );
3936 }
3937
3938 public function testContinueAccountLink() {
3939 $user = $this->getTestSysop()->getUser();
3940 $this->initializeManager();
3941
3942 $session = [
3943 'userid' => $user->getId(),
3944 'username' => $user->getName(),
3945 'primary' => 'X',
3946 ];
3947
3948 try {
3949 $this->manager->continueAccountLink( [] );
3950 $this->fail( 'Expected exception not thrown' );
3951 } catch ( LogicException $ex ) {
3952 $this->assertEquals( 'Account linking is not possible', $ex->getMessage() );
3953 }
3954
3955 $mock = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
3956 $mock->method( 'getUniqueId' )->willReturn( 'X' );
3957 $mock->method( 'accountCreationType' )
3958 ->willReturn( PrimaryAuthenticationProvider::TYPE_LINK );
3959 $mock->method( 'beginPrimaryAccountLink' )
3960 ->willReturn( AuthenticationResponse::newFail( $this->message( 'fail' ) ) );
3961 $this->primaryauthMocks = [ $mock ];
3962 $this->initializeManager( true );
3963
3964 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_LINK_STATE, null );
3965 $ret = $this->manager->continueAccountLink( [] );
3966 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3967 $this->assertSame( 'authmanager-link-not-in-progress', $ret->message->getKey() );
3968
3969 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_LINK_STATE,
3970 [ 'username' => $user->getName() . '<>' ] + $session );
3971 $ret = $this->manager->continueAccountLink( [] );
3972 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3973 $this->assertSame( 'noname', $ret->message->getKey() );
3974 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::ACCOUNT_LINK_STATE ) );
3975
3976 $id = $user->getId();
3977 $this->request->getSession()->setSecret( AuthManager::ACCOUNT_LINK_STATE,
3978 [ 'userid' => $id + 1 ] + $session );
3979 try {
3980 $ret = $this->manager->continueAccountLink( [] );
3981 $this->fail( 'Expected exception not thrown' );
3982 } catch ( UnexpectedValueException $ex ) {
3983 $this->assertEquals(
3984 "User \"{$user->getName()}\" is valid, but ID $id !== " . ( $id + 1 ) . '!',
3985 $ex->getMessage()
3986 );
3987 }
3988 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::ACCOUNT_LINK_STATE ) );
3989 }
3990
3991 /**
3992 * @dataProvider provideAccountLink
3993 */
3994 public function testAccountLink(
3995 StatusValue $preTest, array $primaryResponses, array $managerResponses
3996 ) {
3997 $user = $this->getTestSysop()->getUser();
3998
3999 $this->initializeManager();
4000
4001 // Set up lots of mocks...
4002 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
4003 $mocks = [];
4004
4005 foreach ( [ 'pre', 'primary' ] as $key ) {
4006 $class = ucfirst( $key ) . 'AuthenticationProvider';
4007 $mocks[$key] = $this->getMockBuilder( "MediaWiki\\Auth\\Abstract$class" )
4008 ->setMockClassName( "MockAbstract$class" )
4009 ->getMock();
4010 $mocks[$key]->method( 'getUniqueId' )
4011 ->willReturn( $key );
4012
4013 for ( $i = 2; $i <= 3; $i++ ) {
4014 $mocks[$key . $i] = $this->getMockBuilder( "MediaWiki\\Auth\\Abstract$class" )
4015 ->setMockClassName( "MockAbstract$class" )
4016 ->getMock();
4017 $mocks[$key . $i]->method( 'getUniqueId' )
4018 ->willReturn( $key . $i );
4019 }
4020 }
4021
4022 $mocks['pre']->method( 'testForAccountLink' )
4023 ->willReturnCallback(
4024 function ( $u )
4025 use ( $user, $preTest )
4026 {
4027 $this->assertSame( $user->getId(), $u->getId() );
4028 $this->assertSame( $user->getName(), $u->getName() );
4029 return $preTest;
4030 }
4031 );
4032
4033 $mocks['pre2']->expects( $this->atMost( 1 ) )->method( 'testForAccountLink' )
4034 ->willReturn( StatusValue::newGood() );
4035
4036 $mocks['primary']->method( 'accountCreationType' )
4037 ->willReturn( PrimaryAuthenticationProvider::TYPE_LINK );
4038 $ct = count( $primaryResponses );
4039 $callback = $this->returnCallback( function ( $u, $reqs ) use ( $user, $req, &$primaryResponses ) {
4040 $this->assertSame( $user->getId(), $u->getId() );
4041 $this->assertSame( $user->getName(), $u->getName() );
4042 $foundReq = false;
4043 foreach ( $reqs as $r ) {
4044 $this->assertSame( $user->getName(), $r->username );
4045 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
4046 }
4047 $this->assertTrue( $foundReq, '$reqs contains $req' );
4048 return array_shift( $primaryResponses );
4049 } );
4050 $mocks['primary']->expects( $this->exactly( min( 1, $ct ) ) )
4051 ->method( 'beginPrimaryAccountLink' )
4052 ->will( $callback );
4053 $mocks['primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
4054 ->method( 'continuePrimaryAccountLink' )
4055 ->will( $callback );
4056
4057 $abstain = AuthenticationResponse::newAbstain();
4058 $mocks['primary2']->method( 'accountCreationType' )
4059 ->willReturn( PrimaryAuthenticationProvider::TYPE_LINK );
4060 $mocks['primary2']->expects( $this->atMost( 1 ) )->method( 'beginPrimaryAccountLink' )
4061 ->willReturn( $abstain );
4062 $mocks['primary2']->expects( $this->never() )->method( 'continuePrimaryAccountLink' );
4063 $mocks['primary3']->method( 'accountCreationType' )
4064 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
4065 $mocks['primary3']->expects( $this->never() )->method( 'beginPrimaryAccountLink' );
4066 $mocks['primary3']->expects( $this->never() )->method( 'continuePrimaryAccountLink' );
4067
4068 $this->preauthMocks = [ $mocks['pre'], $mocks['pre2'] ];
4069 $this->primaryauthMocks = [ $mocks['primary3'], $mocks['primary2'], $mocks['primary'] ];
4070 $this->logger = new TestLogger( true, static function ( $message, $level ) {
4071 return $level === LogLevel::DEBUG ? null : $message;
4072 } );
4073 $this->initializeManager( true );
4074
4075 $constraint = Assert::logicalOr(
4076 $this->equalTo( AuthenticationResponse::PASS ),
4077 $this->equalTo( AuthenticationResponse::FAIL )
4078 );
4079 $providers = array_merge( $this->preauthMocks, $this->primaryauthMocks );
4080 foreach ( $providers as $p ) {
4081 DynamicPropertyTestHelper::setDynamicProperty( $p, 'postCalled', false );
4082 $p->expects( $this->atMost( 1 ) )->method( 'postAccountLink' )
4083 ->willReturnCallback( function ( $userArg, $response ) use ( $user, $constraint, $p ) {
4084 $this->assertInstanceOf( User::class, $userArg );
4085 $this->assertSame( $user->getName(), $userArg->getName() );
4086 $this->assertInstanceOf( AuthenticationResponse::class, $response );
4087 $this->assertThat( $response->status, $constraint );
4088 DynamicPropertyTestHelper::setDynamicProperty( $p, 'postCalled', $response->status );
4089 } );
4090 }
4091
4092 $first = true;
4093 $expectLog = [];
4094 foreach ( $managerResponses as $i => $response ) {
4095 if ( $response instanceof AuthenticationResponse &&
4096 $response->status === AuthenticationResponse::PASS
4097 ) {
4098 $expectLog[] = [ LogLevel::INFO, 'Account linked to {user} by primary' ];
4099 }
4100
4101 try {
4102 if ( $first ) {
4103 $ret = $this->manager->beginAccountLink( $user, [ $req ], 'http://localhost/' );
4104 } else {
4105 $ret = $this->manager->continueAccountLink( [ $req ] );
4106 }
4107 if ( $response instanceof Exception ) {
4108 $this->fail( 'Expected exception not thrown', "Response $i" );
4109 }
4110 } catch ( Exception $ex ) {
4111 if ( !$response instanceof Exception ) {
4112 throw $ex;
4113 }
4114 $this->assertEquals( $response->getMessage(), $ex->getMessage(), "Response $i, exception" );
4115 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::ACCOUNT_LINK_STATE ),
4116 "Response $i, exception, session state" );
4117 return;
4118 }
4119
4120 $this->assertSame( 'http://localhost/', $req->returnToUrl );
4121
4122 $ret->message = $this->message( $ret->message );
4123 $this->assertResponseEquals( $response, $ret, "Response $i, response" );
4124 if ( $response->status === AuthenticationResponse::PASS ||
4125 $response->status === AuthenticationResponse::FAIL
4126 ) {
4127 $this->assertNull( $this->request->getSession()->getSecret( AuthManager::ACCOUNT_LINK_STATE ),
4128 "Response $i, session state" );
4129 foreach ( $providers as $p ) {
4130 $this->assertSame( $response->status, DynamicPropertyTestHelper::getDynamicProperty( $p, 'postCalled' ),
4131 "Response $i, post-auth callback called" );
4132 }
4133 } else {
4134 $this->assertNotNull(
4135 $this->request->getSession()->getSecret( AuthManager::ACCOUNT_LINK_STATE ),
4136 "Response $i, session state"
4137 );
4138 foreach ( $ret->neededRequests as $neededReq ) {
4139 $this->assertEquals( AuthManager::ACTION_LINK, $neededReq->action,
4140 "Response $i, neededRequest action" );
4141 }
4142 $this->assertEquals(
4143 $ret->neededRequests,
4144 $this->manager->getAuthenticationRequests( AuthManager::ACTION_LINK_CONTINUE ),
4145 "Response $i, continuation check"
4146 );
4147 foreach ( $providers as $p ) {
4148 $this->assertFalse( DynamicPropertyTestHelper::getDynamicProperty( $p, 'postCalled' ), "Response $i, post-auth callback not called" );
4149 }
4150 }
4151
4152 $first = false;
4153 }
4154
4155 $this->assertSame( $expectLog, $this->logger->getBuffer() );
4156 }
4157
4158 public function provideAccountLink() {
4159 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
4160 $good = StatusValue::newGood();
4161
4162 return [
4163 'Pre-link test fail in pre' => [
4164 StatusValue::newFatal( 'fail-from-pre' ),
4165 [],
4166 [
4167 AuthenticationResponse::newFail( $this->message( 'fail-from-pre' ) ),
4168 ]
4169 ],
4170 'Failure in primary' => [
4171 $good,
4172 $tmp = [
4173 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
4174 ],
4175 $tmp
4176 ],
4177 'All primary abstain' => [
4178 $good,
4179 [
4180 AuthenticationResponse::newAbstain(),
4181 ],
4182 [
4183 AuthenticationResponse::newFail( $this->message( 'authmanager-link-no-primary' ) )
4184 ]
4185 ],
4186 'Primary UI, then redirect, then fail' => [
4187 $good,
4188 $tmp = [
4189 AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
4190 AuthenticationResponse::newRedirect( [ $req ], '/foo.html', [ 'foo' => 'bar' ] ),
4191 AuthenticationResponse::newFail( $this->message( 'fail-in-primary-continue' ) ),
4192 ],
4193 $tmp
4194 ],
4195 'Primary redirect, then abstain' => [
4196 $good,
4197 [
4198 $tmp = AuthenticationResponse::newRedirect(
4199 [ $req ], '/foo.html', [ 'foo' => 'bar' ]
4200 ),
4201 AuthenticationResponse::newAbstain(),
4202 ],
4203 [
4204 $tmp,
4205 new DomainException(
4206 'MockAbstractPrimaryAuthenticationProvider::continuePrimaryAccountLink() returned ABSTAIN'
4207 )
4208 ]
4209 ],
4210 'Primary UI, then pass' => [
4211 $good,
4212 [
4213 $tmp1 = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
4214 AuthenticationResponse::newPass(),
4215 ],
4216 [
4217 $tmp1,
4218 AuthenticationResponse::newPass( '' ),
4219 ]
4220 ],
4221 'Primary pass' => [
4222 $good,
4223 [
4224 AuthenticationResponse::newPass( '' ),
4225 ],
4226 [
4227 AuthenticationResponse::newPass( '' ),
4228 ]
4229 ],
4230 ];
4231 }
4232
4233 public function testSetRequestContextUserFromSessionUser() {
4234 $user = $this->getTestUser()->getUser();
4235 $context = RequestContext::getMain();
4236 $context->setUser( $this->getTestUser()->getUser() );
4237 $context->getRequest()->getSession()->setUser( $user );
4238 $this->assertSame( $context->getRequest()->getSession()->getUser()->getName(), $context->getUser()->getName() );
4239
4240 // Update the session with a new user, but leave the context user as the old user
4241 $newSessionUser = $this->getTestUser( 'sysop' )->getUser();
4242 $context->getRequest()->getSession()->setUser( $newSessionUser );
4243 $this->assertNotSame( $newSessionUser->getName(), $context->getUser()->getName() );
4244
4245 $authManager = $this->getServiceContainer()->getAuthManager();
4246 $authManager->setRequestContextUserFromSessionUser();
4247 $this->assertSame( $context->getRequest()->getSession()->getUser()->getName(), $newSessionUser->getName() );
4248 $this->assertSame( $context->getRequest()->getSession()->getUser()->getName(), $context->getUser()->getName() );
4249 }
4250
4251 /**
4252 * @dataProvider provideAccountCreationAuthenticationRequestTestCases
4253 *
4254 * @param Closure $userProvider Closure returning the user performing the account creation
4255 * @param string[] $expectedReqsByLevel Map of expected auth request classes keyed by requirement level
4256 */
4257 public function testDefaultAccountCreationAuthenticationRequests(
4258 Closure $userProvider,
4259 array $expectedReqsByLevel
4260 ): void {
4261 // Test the default primary and secondary authentication providers
4262 // irrespective of any potentially conflicting local configuration.
4263 $authConfig = $this->getServiceContainer()
4264 ->getConfigSchema()
4265 ->getDefaultFor( MainConfigNames::AuthManagerAutoConfig );
4266
4267 $this->overrideConfigValues( [
4268 MainConfigNames::AuthManagerConfig => null,
4269 MainConfigNames::AuthManagerAutoConfig => $authConfig
4270 ] );
4271
4272 $authManager = $this->getServiceContainer()->getAuthManager();
4273 $userProvider = $userProvider->bindTo( $this );
4274
4275 $reqs = $authManager->getAuthenticationRequests( AuthManager::ACTION_CREATE, $userProvider() );
4276
4277 $reqsByLevel = [];
4278 foreach ( $reqs as $req ) {
4279 $reqsByLevel[$req->required][] = get_class( $req );
4280 }
4281
4282 foreach ( $expectedReqsByLevel as $level => $expectedReqs ) {
4283 $reqs = $reqsByLevel[$level] ?? [];
4284 sort( $reqs );
4285 sort( $expectedReqs );
4286
4287 $this->assertSame( $expectedReqs, $reqs );
4288 }
4289 }
4290
4291 public static function provideAccountCreationAuthenticationRequestTestCases(): iterable {
4292 // phpcs:disable Squiz.Scope.StaticThisUsage.Found
4293 yield 'account creation on behalf of anonymous user' => [
4294 fn (): User => $this->getServiceContainer()->getUserFactory()->newAnonymous( '127.0.0.1' ),
4295 [
4296 AuthenticationRequest::OPTIONAL => [],
4297 AuthenticationRequest::REQUIRED => [
4298 UserDataAuthenticationRequest::class,
4299 UsernameAuthenticationRequest::class
4300 ],
4301 AuthenticationRequest::PRIMARY_REQUIRED => [ PasswordAuthenticationRequest::class ]
4302 ]
4303 ];
4304
4305 yield 'account creation on behalf of temporary user' => [
4306 function (): User {
4307 $req = new FauxRequest();
4308 return $this->getServiceContainer()
4309 ->getTempUserCreator()
4310 ->create( null, $req )
4311 ->getUser();
4312 },
4313 [
4314 AuthenticationRequest::OPTIONAL => [],
4315 AuthenticationRequest::REQUIRED => [
4316 UserDataAuthenticationRequest::class,
4317 UsernameAuthenticationRequest::class
4318 ],
4319 AuthenticationRequest::PRIMARY_REQUIRED => [ PasswordAuthenticationRequest::class ]
4320 ]
4321 ];
4322
4323 yield 'account creation on behalf of registered user' => [
4324 fn (): User => $this->getTestUser()->getUser(),
4325 [
4326 AuthenticationRequest::OPTIONAL => [ CreationReasonAuthenticationRequest::class ],
4327 AuthenticationRequest::REQUIRED => [
4328 UserDataAuthenticationRequest::class,
4329 UsernameAuthenticationRequest::class
4330 ],
4331 AuthenticationRequest::PRIMARY_REQUIRED => [
4332 PasswordAuthenticationRequest::class,
4333 TemporaryPasswordAuthenticationRequest::class
4334 ]
4335 ]
4336 ];
4337 // phpcs:enable
4338 }
4339
4340 public function testTemporaryAccountNamedAccountCreation() {
4341 $tempAccount = $this->getServiceContainer()->getTempUserCreator()->create( null, new FauxRequest() )->getUser();
4342 $this->clearHook( 'UserLogout' );
4343 $this->clearHook( 'SaveUserOptions' );
4344 $this->mergeMwGlobalArrayValue(
4345 'wgRevokePermissions',
4346 [
4347 'temp' => [
4348 'createaccount' => false
4349 ]
4350 ]
4351 );
4352 $primaryAuthProvider = $this->createMock( AbstractPrimaryAuthenticationProvider::class );
4353 $primaryAuthProvider->method( 'accountCreationType' )
4354 ->willReturn( PrimaryAuthenticationProvider::TYPE_CREATE );
4355 $primaryAuthProvider->method( 'continuePrimaryAuthentication' )->willReturn( AuthenticationResponse::PASS );
4356 $primaryAuthProvider->method( 'testForAccountCreation' )->willReturn( StatusValue::newGood() );
4357 $primaryAuthProvider->method( 'beginPrimaryAccountCreation' )->willReturn( AuthenticationResponse::newPass() );
4358 $primaryAuthProvider->method( 'testUserForCreation' )->willReturn( StatusValue::newGood() );
4359 $primaryAuthProvider->method( 'getUniqueId' )->willReturn( __METHOD__ );
4360 $this->primaryauthMocks = [ $primaryAuthProvider ];
4361 $this->logger = new TestLogger( true, static function ( $message, $level ) {
4362 return $message;
4363 } );
4364 $this->initializeManager();
4365 $this->logger->setCollectContext( true );
4366 $this->logger->setCollect( true );
4367
4368 $usernameAuthRequest = new UsernameAuthenticationRequest();
4369 $usernameAuthRequest->username = ucfirst( wfRandomString() );
4370 $userDataAuthRequest = new UserDataAuthenticationRequest();
4371 $userDataAuthRequest->username = $tempAccount->getName();
4372 $session = $this->request->getSession();
4373 $session->setUser( $tempAccount );
4374 $this->manager->setRequestContextUserFromSessionUser();
4375 $session->set( 'TempUser:name', $tempAccount->getName() );
4376 $result = $this->manager->beginAccountCreation( $tempAccount, [
4377 $usernameAuthRequest,
4378 $userDataAuthRequest
4379 ], '' );
4380 $this->assertSame( $usernameAuthRequest->username, $result->username );
4381 $this->assertSame( AuthenticationResponse::PASS, $result->status );
4382 $this->assertSame(
4383 [ 'username' => $usernameAuthRequest->username, 'creator' => '127.0.0.1' ],
4384 // Check the context variables on the last message passed to the logger
4385 $this->logger->getBuffer()[0][2]
4386 );
4387 $this->assertSame( null, $this->request->getSession()->get( 'TempUser:name' ) );
4388 }
4389 }