Move ResultWrapper subclasses to Rdbms
[mediawiki.git] / tests / phpunit / includes / auth / AuthManagerTest.php
blobf57db11b236987fb41d227d187f0e41fd6b41b2d
1 <?php
3 namespace MediaWiki\Auth;
5 use MediaWiki\Session\SessionInfo;
6 use MediaWiki\Session\UserInfo;
7 use Psr\Log\LogLevel;
8 use StatusValue;
9 use Wikimedia\ScopedCallback;
11 /**
12 * @group AuthManager
13 * @group Database
14 * @covers MediaWiki\Auth\AuthManager
16 class AuthManagerTest extends \MediaWikiTestCase {
17 /** @var WebRequest */
18 protected $request;
19 /** @var Config */
20 protected $config;
21 /** @var \\Psr\\Log\\LoggerInterface */
22 protected $logger;
24 protected $preauthMocks = [];
25 protected $primaryauthMocks = [];
26 protected $secondaryauthMocks = [];
28 /** @var AuthManager */
29 protected $manager;
30 /** @var TestingAccessWrapper */
31 protected $managerPriv;
33 protected function setUp() {
34 parent::setUp();
36 $this->setMwGlobals( [ 'wgAuth' => null ] );
37 $this->stashMwGlobals( [ 'wgHooks' ] );
40 /**
41 * Sets a mock on a hook
42 * @param string $hook
43 * @param object $expect From $this->once(), $this->never(), etc.
44 * @return object $mock->expects( $expect )->method( ... ).
46 protected function hook( $hook, $expect ) {
47 global $wgHooks;
48 $mock = $this->getMock( __CLASS__, [ "on$hook" ] );
49 $wgHooks[$hook] = [ $mock ];
50 return $mock->expects( $expect )->method( "on$hook" );
53 /**
54 * Unsets a hook
55 * @param string $hook
57 protected function unhook( $hook ) {
58 global $wgHooks;
59 $wgHooks[$hook] = [];
62 /**
63 * Ensure a value is a clean Message object
64 * @param string|Message $key
65 * @param array $params
66 * @return Message
68 protected function message( $key, $params = [] ) {
69 if ( $key === null ) {
70 return null;
72 if ( $key instanceof \MessageSpecifier ) {
73 $params = $key->getParams();
74 $key = $key->getKey();
76 return new \Message( $key, $params, \Language::factory( 'en' ) );
79 /**
80 * Initialize the AuthManagerConfig variable in $this->config
82 * Uses data from the various 'mocks' fields.
84 protected function initializeConfig() {
85 $config = [
86 'preauth' => [
88 'primaryauth' => [
90 'secondaryauth' => [
94 foreach ( [ 'preauth', 'primaryauth', 'secondaryauth' ] as $type ) {
95 $key = $type . 'Mocks';
96 foreach ( $this->$key as $mock ) {
97 $config[$type][$mock->getUniqueId()] = [ 'factory' => function () use ( $mock ) {
98 return $mock;
99 } ];
103 $this->config->set( 'AuthManagerConfig', $config );
104 $this->config->set( 'LanguageCode', 'en' );
105 $this->config->set( 'NewUserLog', false );
109 * Initialize $this->manager
110 * @param bool $regen Force a call to $this->initializeConfig()
112 protected function initializeManager( $regen = false ) {
113 if ( $regen || !$this->config ) {
114 $this->config = new \HashConfig();
116 if ( $regen || !$this->request ) {
117 $this->request = new \FauxRequest();
119 if ( !$this->logger ) {
120 $this->logger = new \TestLogger();
123 if ( $regen || !$this->config->has( 'AuthManagerConfig' ) ) {
124 $this->initializeConfig();
126 $this->manager = new AuthManager( $this->request, $this->config );
127 $this->manager->setLogger( $this->logger );
128 $this->managerPriv = \TestingAccessWrapper::newFromObject( $this->manager );
132 * Setup SessionManager with a mock session provider
133 * @param bool|null $canChangeUser If non-null, canChangeUser will be mocked to return this
134 * @param array $methods Additional methods to mock
135 * @return array (MediaWiki\Session\SessionProvider, ScopedCallback)
137 protected function getMockSessionProvider( $canChangeUser = null, array $methods = [] ) {
138 if ( !$this->config ) {
139 $this->config = new \HashConfig();
140 $this->initializeConfig();
142 $this->config->set( 'ObjectCacheSessionExpiry', 100 );
144 $methods[] = '__toString';
145 $methods[] = 'describe';
146 if ( $canChangeUser !== null ) {
147 $methods[] = 'canChangeUser';
149 $provider = $this->getMockBuilder( 'DummySessionProvider' )
150 ->setMethods( $methods )
151 ->getMock();
152 $provider->expects( $this->any() )->method( '__toString' )
153 ->will( $this->returnValue( 'MockSessionProvider' ) );
154 $provider->expects( $this->any() )->method( 'describe' )
155 ->will( $this->returnValue( 'MockSessionProvider sessions' ) );
156 if ( $canChangeUser !== null ) {
157 $provider->expects( $this->any() )->method( 'canChangeUser' )
158 ->will( $this->returnValue( $canChangeUser ) );
160 $this->config->set( 'SessionProviders', [
161 [ 'factory' => function () use ( $provider ) {
162 return $provider;
163 } ],
164 ] );
166 $manager = new \MediaWiki\Session\SessionManager( [
167 'config' => $this->config,
168 'logger' => new \Psr\Log\NullLogger(),
169 'store' => new \HashBagOStuff(),
170 ] );
171 \TestingAccessWrapper::newFromObject( $manager )->getProvider( (string)$provider );
173 $reset = \MediaWiki\Session\TestUtils::setSessionManagerSingleton( $manager );
175 if ( $this->request ) {
176 $manager->getSessionForRequest( $this->request );
179 return [ $provider, $reset ];
182 public function testSingleton() {
183 // Temporarily clear out the global singleton, if any, to test creating
184 // one.
185 $rProp = new \ReflectionProperty( AuthManager::class, 'instance' );
186 $rProp->setAccessible( true );
187 $old = $rProp->getValue();
188 $cb = new ScopedCallback( [ $rProp, 'setValue' ], [ $old ] );
189 $rProp->setValue( null );
191 $singleton = AuthManager::singleton();
192 $this->assertInstanceOf( AuthManager::class, AuthManager::singleton() );
193 $this->assertSame( $singleton, AuthManager::singleton() );
194 $this->assertSame( \RequestContext::getMain()->getRequest(), $singleton->getRequest() );
195 $this->assertSame(
196 \RequestContext::getMain()->getConfig(),
197 \TestingAccessWrapper::newFromObject( $singleton )->config
201 public function testCanAuthenticateNow() {
202 $this->initializeManager();
204 list( $provider, $reset ) = $this->getMockSessionProvider( false );
205 $this->assertFalse( $this->manager->canAuthenticateNow() );
206 ScopedCallback::consume( $reset );
208 list( $provider, $reset ) = $this->getMockSessionProvider( true );
209 $this->assertTrue( $this->manager->canAuthenticateNow() );
210 ScopedCallback::consume( $reset );
213 public function testNormalizeUsername() {
214 $mocks = [
215 $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class ),
216 $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class ),
217 $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class ),
218 $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class ),
220 foreach ( $mocks as $key => $mock ) {
221 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( $key ) );
223 $mocks[0]->expects( $this->once() )->method( 'providerNormalizeUsername' )
224 ->with( $this->identicalTo( 'XYZ' ) )
225 ->willReturn( 'Foo' );
226 $mocks[1]->expects( $this->once() )->method( 'providerNormalizeUsername' )
227 ->with( $this->identicalTo( 'XYZ' ) )
228 ->willReturn( 'Foo' );
229 $mocks[2]->expects( $this->once() )->method( 'providerNormalizeUsername' )
230 ->with( $this->identicalTo( 'XYZ' ) )
231 ->willReturn( null );
232 $mocks[3]->expects( $this->once() )->method( 'providerNormalizeUsername' )
233 ->with( $this->identicalTo( 'XYZ' ) )
234 ->willReturn( 'Bar!' );
236 $this->primaryauthMocks = $mocks;
238 $this->initializeManager();
240 $this->assertSame( [ 'Foo', 'Bar!' ], $this->manager->normalizeUsername( 'XYZ' ) );
244 * @dataProvider provideSecuritySensitiveOperationStatus
245 * @param bool $mutableSession
247 public function testSecuritySensitiveOperationStatus( $mutableSession ) {
248 $this->logger = new \Psr\Log\NullLogger();
249 $user = \User::newFromName( 'UTSysop' );
250 $provideUser = null;
251 $reauth = $mutableSession ? AuthManager::SEC_REAUTH : AuthManager::SEC_FAIL;
253 list( $provider, $reset ) = $this->getMockSessionProvider(
254 $mutableSession, [ 'provideSessionInfo' ]
256 $provider->expects( $this->any() )->method( 'provideSessionInfo' )
257 ->will( $this->returnCallback( function () use ( $provider, &$provideUser ) {
258 return new SessionInfo( SessionInfo::MIN_PRIORITY, [
259 'provider' => $provider,
260 'id' => \DummySessionProvider::ID,
261 'persisted' => true,
262 'userInfo' => UserInfo::newFromUser( $provideUser, true )
263 ] );
264 } ) );
265 $this->initializeManager();
267 $this->config->set( 'ReauthenticateTime', [] );
268 $this->config->set( 'AllowSecuritySensitiveOperationIfCannotReauthenticate', [] );
269 $provideUser = new \User;
270 $session = $provider->getManager()->getSessionForRequest( $this->request );
271 $this->assertSame( 0, $session->getUser()->getId(), 'sanity check' );
273 // Anonymous user => reauth
274 $session->set( 'AuthManager:lastAuthId', 0 );
275 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
276 $this->assertSame( $reauth, $this->manager->securitySensitiveOperationStatus( 'foo' ) );
278 $provideUser = $user;
279 $session = $provider->getManager()->getSessionForRequest( $this->request );
280 $this->assertSame( $user->getId(), $session->getUser()->getId(), 'sanity check' );
282 // Error for no default (only gets thrown for non-anonymous user)
283 $session->set( 'AuthManager:lastAuthId', $user->getId() + 1 );
284 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
285 try {
286 $this->manager->securitySensitiveOperationStatus( 'foo' );
287 $this->fail( 'Expected exception not thrown' );
288 } catch ( \UnexpectedValueException $ex ) {
289 $this->assertSame(
290 $mutableSession
291 ? '$wgReauthenticateTime lacks a default'
292 : '$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default',
293 $ex->getMessage()
297 if ( $mutableSession ) {
298 $this->config->set( 'ReauthenticateTime', [
299 'test' => 100,
300 'test2' => -1,
301 'default' => 10,
302 ] );
304 // Mismatched user ID
305 $session->set( 'AuthManager:lastAuthId', $user->getId() + 1 );
306 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
307 $this->assertSame(
308 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'foo' )
310 $this->assertSame(
311 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'test' )
313 $this->assertSame(
314 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'test2' )
317 // Missing time
318 $session->set( 'AuthManager:lastAuthId', $user->getId() );
319 $session->set( 'AuthManager:lastAuthTimestamp', null );
320 $this->assertSame(
321 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'foo' )
323 $this->assertSame(
324 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'test' )
326 $this->assertSame(
327 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'test2' )
330 // Recent enough to pass
331 $session->set( 'AuthManager:lastAuthTimestamp', time() - 5 );
332 $this->assertSame(
333 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'foo' )
336 // Not recent enough to pass
337 $session->set( 'AuthManager:lastAuthTimestamp', time() - 20 );
338 $this->assertSame(
339 AuthManager::SEC_REAUTH, $this->manager->securitySensitiveOperationStatus( 'foo' )
341 // But recent enough for the 'test' operation
342 $this->assertSame(
343 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'test' )
345 } else {
346 $this->config->set( 'AllowSecuritySensitiveOperationIfCannotReauthenticate', [
347 'test' => false,
348 'default' => true,
349 ] );
351 $this->assertEquals(
352 AuthManager::SEC_OK, $this->manager->securitySensitiveOperationStatus( 'foo' )
355 $this->assertEquals(
356 AuthManager::SEC_FAIL, $this->manager->securitySensitiveOperationStatus( 'test' )
360 // Test hook, all three possible values
361 foreach ( [
362 AuthManager::SEC_OK => AuthManager::SEC_OK,
363 AuthManager::SEC_REAUTH => $reauth,
364 AuthManager::SEC_FAIL => AuthManager::SEC_FAIL,
365 ] as $hook => $expect ) {
366 $this->hook( 'SecuritySensitiveOperationStatus', $this->exactly( 2 ) )
367 ->with(
368 $this->anything(),
369 $this->anything(),
370 $this->callback( function ( $s ) use ( $session ) {
371 return $s->getId() === $session->getId();
372 } ),
373 $mutableSession ? $this->equalTo( 500, 1 ) : $this->equalTo( -1 )
375 ->will( $this->returnCallback( function ( &$v ) use ( $hook ) {
376 $v = $hook;
377 return true;
378 } ) );
379 $session->set( 'AuthManager:lastAuthTimestamp', time() - 500 );
380 $this->assertEquals(
381 $expect, $this->manager->securitySensitiveOperationStatus( 'test' ), "hook $hook"
383 $this->assertEquals(
384 $expect, $this->manager->securitySensitiveOperationStatus( 'test2' ), "hook $hook"
386 $this->unhook( 'SecuritySensitiveOperationStatus' );
389 ScopedCallback::consume( $reset );
392 public function onSecuritySensitiveOperationStatus( &$status, $operation, $session, $time ) {
395 public static function provideSecuritySensitiveOperationStatus() {
396 return [
397 [ true ],
398 [ false ],
403 * @dataProvider provideUserCanAuthenticate
404 * @param bool $primary1Can
405 * @param bool $primary2Can
406 * @param bool $expect
408 public function testUserCanAuthenticate( $primary1Can, $primary2Can, $expect ) {
409 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
410 $mock1->expects( $this->any() )->method( 'getUniqueId' )
411 ->will( $this->returnValue( 'primary1' ) );
412 $mock1->expects( $this->any() )->method( 'testUserCanAuthenticate' )
413 ->with( $this->equalTo( 'UTSysop' ) )
414 ->will( $this->returnValue( $primary1Can ) );
415 $mock2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
416 $mock2->expects( $this->any() )->method( 'getUniqueId' )
417 ->will( $this->returnValue( 'primary2' ) );
418 $mock2->expects( $this->any() )->method( 'testUserCanAuthenticate' )
419 ->with( $this->equalTo( 'UTSysop' ) )
420 ->will( $this->returnValue( $primary2Can ) );
421 $this->primaryauthMocks = [ $mock1, $mock2 ];
423 $this->initializeManager( true );
424 $this->assertSame( $expect, $this->manager->userCanAuthenticate( 'UTSysop' ) );
427 public static function provideUserCanAuthenticate() {
428 return [
429 [ false, false, false ],
430 [ true, false, true ],
431 [ false, true, true ],
432 [ true, true, true ],
436 public function testRevokeAccessForUser() {
437 $this->initializeManager();
439 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
440 $mock->expects( $this->any() )->method( 'getUniqueId' )
441 ->will( $this->returnValue( 'primary' ) );
442 $mock->expects( $this->once() )->method( 'providerRevokeAccessForUser' )
443 ->with( $this->equalTo( 'UTSysop' ) );
444 $this->primaryauthMocks = [ $mock ];
446 $this->initializeManager( true );
447 $this->logger->setCollect( true );
449 $this->manager->revokeAccessForUser( 'UTSysop' );
451 $this->assertSame( [
452 [ LogLevel::INFO, 'Revoking access for {user}' ],
453 ], $this->logger->getBuffer() );
456 public function testProviderCreation() {
457 $mocks = [
458 'pre' => $this->getMockForAbstractClass( PreAuthenticationProvider::class ),
459 'primary' => $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class ),
460 'secondary' => $this->getMockForAbstractClass( SecondaryAuthenticationProvider::class ),
462 foreach ( $mocks as $key => $mock ) {
463 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( $key ) );
464 $mock->expects( $this->once() )->method( 'setLogger' );
465 $mock->expects( $this->once() )->method( 'setManager' );
466 $mock->expects( $this->once() )->method( 'setConfig' );
468 $this->preauthMocks = [ $mocks['pre'] ];
469 $this->primaryauthMocks = [ $mocks['primary'] ];
470 $this->secondaryauthMocks = [ $mocks['secondary'] ];
472 // Normal operation
473 $this->initializeManager();
474 $this->assertSame(
475 $mocks['primary'],
476 $this->managerPriv->getAuthenticationProvider( 'primary' )
478 $this->assertSame(
479 $mocks['secondary'],
480 $this->managerPriv->getAuthenticationProvider( 'secondary' )
482 $this->assertSame(
483 $mocks['pre'],
484 $this->managerPriv->getAuthenticationProvider( 'pre' )
486 $this->assertSame(
487 [ 'pre' => $mocks['pre'] ],
488 $this->managerPriv->getPreAuthenticationProviders()
490 $this->assertSame(
491 [ 'primary' => $mocks['primary'] ],
492 $this->managerPriv->getPrimaryAuthenticationProviders()
494 $this->assertSame(
495 [ 'secondary' => $mocks['secondary'] ],
496 $this->managerPriv->getSecondaryAuthenticationProviders()
499 // Duplicate IDs
500 $mock1 = $this->getMockForAbstractClass( PreAuthenticationProvider::class );
501 $mock2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
502 $mock1->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
503 $mock2->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
504 $this->preauthMocks = [ $mock1 ];
505 $this->primaryauthMocks = [ $mock2 ];
506 $this->secondaryauthMocks = [];
507 $this->initializeManager( true );
508 try {
509 $this->managerPriv->getAuthenticationProvider( 'Y' );
510 $this->fail( 'Expected exception not thrown' );
511 } catch ( \RuntimeException $ex ) {
512 $class1 = get_class( $mock1 );
513 $class2 = get_class( $mock2 );
514 $this->assertSame(
515 "Duplicate specifications for id X (classes $class1 and $class2)", $ex->getMessage()
519 // Wrong classes
520 $mock = $this->getMockForAbstractClass( AuthenticationProvider::class );
521 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
522 $class = get_class( $mock );
523 $this->preauthMocks = [ $mock ];
524 $this->primaryauthMocks = [ $mock ];
525 $this->secondaryauthMocks = [ $mock ];
526 $this->initializeManager( true );
527 try {
528 $this->managerPriv->getPreAuthenticationProviders();
529 $this->fail( 'Expected exception not thrown' );
530 } catch ( \RuntimeException $ex ) {
531 $this->assertSame(
532 "Expected instance of MediaWiki\\Auth\\PreAuthenticationProvider, got $class",
533 $ex->getMessage()
536 try {
537 $this->managerPriv->getPrimaryAuthenticationProviders();
538 $this->fail( 'Expected exception not thrown' );
539 } catch ( \RuntimeException $ex ) {
540 $this->assertSame(
541 "Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got $class",
542 $ex->getMessage()
545 try {
546 $this->managerPriv->getSecondaryAuthenticationProviders();
547 $this->fail( 'Expected exception not thrown' );
548 } catch ( \RuntimeException $ex ) {
549 $this->assertSame(
550 "Expected instance of MediaWiki\\Auth\\SecondaryAuthenticationProvider, got $class",
551 $ex->getMessage()
555 // Sorting
556 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
557 $mock2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
558 $mock3 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
559 $mock1->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'A' ) );
560 $mock2->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'B' ) );
561 $mock3->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'C' ) );
562 $this->preauthMocks = [];
563 $this->primaryauthMocks = [ $mock1, $mock2, $mock3 ];
564 $this->secondaryauthMocks = [];
565 $this->initializeConfig();
566 $config = $this->config->get( 'AuthManagerConfig' );
568 $this->initializeManager( false );
569 $this->assertSame(
570 [ 'A' => $mock1, 'B' => $mock2, 'C' => $mock3 ],
571 $this->managerPriv->getPrimaryAuthenticationProviders(),
572 'sanity check'
575 $config['primaryauth']['A']['sort'] = 100;
576 $config['primaryauth']['C']['sort'] = -1;
577 $this->config->set( 'AuthManagerConfig', $config );
578 $this->initializeManager( false );
579 $this->assertSame(
580 [ 'C' => $mock3, 'B' => $mock2, 'A' => $mock1 ],
581 $this->managerPriv->getPrimaryAuthenticationProviders()
585 public function testSetDefaultUserOptions() {
586 $this->initializeManager();
588 $context = \RequestContext::getMain();
589 $reset = new ScopedCallback( [ $context, 'setLanguage' ], [ $context->getLanguage() ] );
590 $context->setLanguage( 'de' );
591 $this->setMwGlobals( 'wgContLang', \Language::factory( 'zh' ) );
593 $user = \User::newFromName( self::usernameForCreation() );
594 $user->addToDatabase();
595 $oldToken = $user->getToken();
596 $this->managerPriv->setDefaultUserOptions( $user, false );
597 $user->saveSettings();
598 $this->assertNotEquals( $oldToken, $user->getToken() );
599 $this->assertSame( 'zh', $user->getOption( 'language' ) );
600 $this->assertSame( 'zh', $user->getOption( 'variant' ) );
602 $user = \User::newFromName( self::usernameForCreation() );
603 $user->addToDatabase();
604 $oldToken = $user->getToken();
605 $this->managerPriv->setDefaultUserOptions( $user, true );
606 $user->saveSettings();
607 $this->assertNotEquals( $oldToken, $user->getToken() );
608 $this->assertSame( 'de', $user->getOption( 'language' ) );
609 $this->assertSame( 'zh', $user->getOption( 'variant' ) );
611 $this->setMwGlobals( 'wgContLang', \Language::factory( 'en' ) );
613 $user = \User::newFromName( self::usernameForCreation() );
614 $user->addToDatabase();
615 $oldToken = $user->getToken();
616 $this->managerPriv->setDefaultUserOptions( $user, true );
617 $user->saveSettings();
618 $this->assertNotEquals( $oldToken, $user->getToken() );
619 $this->assertSame( 'de', $user->getOption( 'language' ) );
620 $this->assertSame( null, $user->getOption( 'variant' ) );
623 public function testForcePrimaryAuthenticationProviders() {
624 $mockA = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
625 $mockB = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
626 $mockB2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
627 $mockA->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'A' ) );
628 $mockB->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'B' ) );
629 $mockB2->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'B' ) );
630 $this->primaryauthMocks = [ $mockA ];
632 $this->logger = new \TestLogger( true );
634 // Test without first initializing the configured providers
635 $this->initializeManager();
636 $this->manager->forcePrimaryAuthenticationProviders( [ $mockB ], 'testing' );
637 $this->assertSame(
638 [ 'B' => $mockB ], $this->managerPriv->getPrimaryAuthenticationProviders()
640 $this->assertSame( null, $this->managerPriv->getAuthenticationProvider( 'A' ) );
641 $this->assertSame( $mockB, $this->managerPriv->getAuthenticationProvider( 'B' ) );
642 $this->assertSame( [
643 [ LogLevel::WARNING, 'Overriding AuthManager primary authn because testing' ],
644 ], $this->logger->getBuffer() );
645 $this->logger->clearBuffer();
647 // Test with first initializing the configured providers
648 $this->initializeManager();
649 $this->assertSame( $mockA, $this->managerPriv->getAuthenticationProvider( 'A' ) );
650 $this->assertSame( null, $this->managerPriv->getAuthenticationProvider( 'B' ) );
651 $this->request->getSession()->setSecret( 'AuthManager::authnState', 'test' );
652 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState', 'test' );
653 $this->manager->forcePrimaryAuthenticationProviders( [ $mockB ], 'testing' );
654 $this->assertSame(
655 [ 'B' => $mockB ], $this->managerPriv->getPrimaryAuthenticationProviders()
657 $this->assertSame( null, $this->managerPriv->getAuthenticationProvider( 'A' ) );
658 $this->assertSame( $mockB, $this->managerPriv->getAuthenticationProvider( 'B' ) );
659 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::authnState' ) );
660 $this->assertNull(
661 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
663 $this->assertSame( [
664 [ LogLevel::WARNING, 'Overriding AuthManager primary authn because testing' ],
666 LogLevel::WARNING,
667 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
669 ], $this->logger->getBuffer() );
670 $this->logger->clearBuffer();
672 // Test duplicate IDs
673 $this->initializeManager();
674 try {
675 $this->manager->forcePrimaryAuthenticationProviders( [ $mockB, $mockB2 ], 'testing' );
676 $this->fail( 'Expected exception not thrown' );
677 } catch ( \RuntimeException $ex ) {
678 $class1 = get_class( $mockB );
679 $class2 = get_class( $mockB2 );
680 $this->assertSame(
681 "Duplicate specifications for id B (classes $class2 and $class1)", $ex->getMessage()
685 // Wrong classes
686 $mock = $this->getMockForAbstractClass( AuthenticationProvider::class );
687 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
688 $class = get_class( $mock );
689 try {
690 $this->manager->forcePrimaryAuthenticationProviders( [ $mock ], 'testing' );
691 $this->fail( 'Expected exception not thrown' );
692 } catch ( \RuntimeException $ex ) {
693 $this->assertSame(
694 "Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got $class",
695 $ex->getMessage()
700 public function testBeginAuthentication() {
701 $this->initializeManager();
703 // Immutable session
704 list( $provider, $reset ) = $this->getMockSessionProvider( false );
705 $this->hook( 'UserLoggedIn', $this->never() );
706 $this->request->getSession()->setSecret( 'AuthManager::authnState', 'test' );
707 try {
708 $this->manager->beginAuthentication( [], 'http://localhost/' );
709 $this->fail( 'Expected exception not thrown' );
710 } catch ( \LogicException $ex ) {
711 $this->assertSame( 'Authentication is not possible now', $ex->getMessage() );
713 $this->unhook( 'UserLoggedIn' );
714 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::authnState' ) );
715 ScopedCallback::consume( $reset );
716 $this->initializeManager( true );
718 // CreatedAccountAuthenticationRequest
719 $user = \User::newFromName( 'UTSysop' );
720 $reqs = [
721 new CreatedAccountAuthenticationRequest( $user->getId(), $user->getName() )
723 $this->hook( 'UserLoggedIn', $this->never() );
724 try {
725 $this->manager->beginAuthentication( $reqs, 'http://localhost/' );
726 $this->fail( 'Expected exception not thrown' );
727 } catch ( \LogicException $ex ) {
728 $this->assertSame(
729 'CreatedAccountAuthenticationRequests are only valid on the same AuthManager ' .
730 'that created the account',
731 $ex->getMessage()
734 $this->unhook( 'UserLoggedIn' );
736 $this->request->getSession()->clear();
737 $this->request->getSession()->setSecret( 'AuthManager::authnState', 'test' );
738 $this->managerPriv->createdAccountAuthenticationRequests = [ $reqs[0] ];
739 $this->hook( 'UserLoggedIn', $this->once() )
740 ->with( $this->callback( function ( $u ) use ( $user ) {
741 return $user->getId() === $u->getId() && $user->getName() === $u->getName();
742 } ) );
743 $this->hook( 'AuthManagerLoginAuthenticateAudit', $this->once() );
744 $this->logger->setCollect( true );
745 $ret = $this->manager->beginAuthentication( $reqs, 'http://localhost/' );
746 $this->logger->setCollect( false );
747 $this->unhook( 'UserLoggedIn' );
748 $this->unhook( 'AuthManagerLoginAuthenticateAudit' );
749 $this->assertSame( AuthenticationResponse::PASS, $ret->status );
750 $this->assertSame( $user->getName(), $ret->username );
751 $this->assertSame( $user->getId(), $this->request->getSessionData( 'AuthManager:lastAuthId' ) );
752 $this->assertEquals(
753 time(), $this->request->getSessionData( 'AuthManager:lastAuthTimestamp' ),
754 'timestamp ±1', 1
756 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::authnState' ) );
757 $this->assertSame( $user->getId(), $this->request->getSession()->getUser()->getId() );
758 $this->assertSame( [
759 [ LogLevel::INFO, 'Logging in {user} after account creation' ],
760 ], $this->logger->getBuffer() );
763 public function testCreateFromLogin() {
764 $user = \User::newFromName( 'UTSysop' );
765 $req1 = $this->getMock( AuthenticationRequest::class );
766 $req2 = $this->getMock( AuthenticationRequest::class );
767 $req3 = $this->getMock( AuthenticationRequest::class );
768 $userReq = new UsernameAuthenticationRequest;
769 $userReq->username = 'UTDummy';
771 $req1->returnToUrl = 'http://localhost/';
772 $req2->returnToUrl = 'http://localhost/';
773 $req3->returnToUrl = 'http://localhost/';
774 $req3->username = 'UTDummy';
775 $userReq->returnToUrl = 'http://localhost/';
777 // Passing one into beginAuthentication(), and an immediate FAIL
778 $primary = $this->getMockForAbstractClass( AbstractPrimaryAuthenticationProvider::class );
779 $this->primaryauthMocks = [ $primary ];
780 $this->initializeManager( true );
781 $res = AuthenticationResponse::newFail( wfMessage( 'foo' ) );
782 $res->createRequest = $req1;
783 $primary->expects( $this->any() )->method( 'beginPrimaryAuthentication' )
784 ->will( $this->returnValue( $res ) );
785 $createReq = new CreateFromLoginAuthenticationRequest(
786 null, [ $req2->getUniqueId() => $req2 ]
788 $this->logger->setCollect( true );
789 $ret = $this->manager->beginAuthentication( [ $createReq ], 'http://localhost/' );
790 $this->logger->setCollect( false );
791 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
792 $this->assertInstanceOf( CreateFromLoginAuthenticationRequest::class, $ret->createRequest );
793 $this->assertSame( $req1, $ret->createRequest->createRequest );
794 $this->assertEquals( [ $req2->getUniqueId() => $req2 ], $ret->createRequest->maybeLink );
796 // UI, then FAIL in beginAuthentication()
797 $primary = $this->getMockBuilder( AbstractPrimaryAuthenticationProvider::class )
798 ->setMethods( [ 'continuePrimaryAuthentication' ] )
799 ->getMockForAbstractClass();
800 $this->primaryauthMocks = [ $primary ];
801 $this->initializeManager( true );
802 $primary->expects( $this->any() )->method( 'beginPrimaryAuthentication' )
803 ->will( $this->returnValue(
804 AuthenticationResponse::newUI( [ $req1 ], wfMessage( 'foo' ) )
805 ) );
806 $res = AuthenticationResponse::newFail( wfMessage( 'foo' ) );
807 $res->createRequest = $req2;
808 $primary->expects( $this->any() )->method( 'continuePrimaryAuthentication' )
809 ->will( $this->returnValue( $res ) );
810 $this->logger->setCollect( true );
811 $ret = $this->manager->beginAuthentication( [], 'http://localhost/' );
812 $this->assertSame( AuthenticationResponse::UI, $ret->status, 'sanity check' );
813 $ret = $this->manager->continueAuthentication( [] );
814 $this->logger->setCollect( false );
815 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
816 $this->assertInstanceOf( CreateFromLoginAuthenticationRequest::class, $ret->createRequest );
817 $this->assertSame( $req2, $ret->createRequest->createRequest );
818 $this->assertEquals( [], $ret->createRequest->maybeLink );
820 // Pass into beginAccountCreation(), see that maybeLink and createRequest get copied
821 $primary = $this->getMockForAbstractClass( AbstractPrimaryAuthenticationProvider::class );
822 $this->primaryauthMocks = [ $primary ];
823 $this->initializeManager( true );
824 $createReq = new CreateFromLoginAuthenticationRequest( $req3, [ $req2 ] );
825 $createReq->returnToUrl = 'http://localhost/';
826 $createReq->username = 'UTDummy';
827 $res = AuthenticationResponse::newUI( [ $req1 ], wfMessage( 'foo' ) );
828 $primary->expects( $this->any() )->method( 'beginPrimaryAccountCreation' )
829 ->with( $this->anything(), $this->anything(), [ $userReq, $createReq, $req3 ] )
830 ->will( $this->returnValue( $res ) );
831 $primary->expects( $this->any() )->method( 'accountCreationType' )
832 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
833 $this->logger->setCollect( true );
834 $ret = $this->manager->beginAccountCreation(
835 $user, [ $userReq, $createReq ], 'http://localhost/'
837 $this->logger->setCollect( false );
838 $this->assertSame( AuthenticationResponse::UI, $ret->status );
839 $state = $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' );
840 $this->assertNotNull( $state );
841 $this->assertEquals( [ $userReq, $createReq, $req3 ], $state['reqs'] );
842 $this->assertEquals( [ $req2 ], $state['maybeLink'] );
846 * @dataProvider provideAuthentication
847 * @param StatusValue $preResponse
848 * @param array $primaryResponses
849 * @param array $secondaryResponses
850 * @param array $managerResponses
851 * @param bool $link Whether the primary authentication provider is a "link" provider
853 public function testAuthentication(
854 StatusValue $preResponse, array $primaryResponses, array $secondaryResponses,
855 array $managerResponses, $link = false
857 $this->initializeManager();
858 $user = \User::newFromName( 'UTSysop' );
859 $id = $user->getId();
860 $name = $user->getName();
862 // Set up lots of mocks...
863 $req = new RememberMeAuthenticationRequest;
864 $req->rememberMe = (bool)rand( 0, 1 );
865 $req->pre = $preResponse;
866 $req->primary = $primaryResponses;
867 $req->secondary = $secondaryResponses;
868 $mocks = [];
869 foreach ( [ 'pre', 'primary', 'secondary' ] as $key ) {
870 $class = ucfirst( $key ) . 'AuthenticationProvider';
871 $mocks[$key] = $this->getMockForAbstractClass(
872 "MediaWiki\\Auth\\$class", [], "Mock$class"
874 $mocks[$key]->expects( $this->any() )->method( 'getUniqueId' )
875 ->will( $this->returnValue( $key ) );
876 $mocks[$key . '2'] = $this->getMockForAbstractClass(
877 "MediaWiki\\Auth\\$class", [], "Mock$class"
879 $mocks[$key . '2']->expects( $this->any() )->method( 'getUniqueId' )
880 ->will( $this->returnValue( $key . '2' ) );
881 $mocks[$key . '3'] = $this->getMockForAbstractClass(
882 "MediaWiki\\Auth\\$class", [], "Mock$class"
884 $mocks[$key . '3']->expects( $this->any() )->method( 'getUniqueId' )
885 ->will( $this->returnValue( $key . '3' ) );
887 foreach ( $mocks as $mock ) {
888 $mock->expects( $this->any() )->method( 'getAuthenticationRequests' )
889 ->will( $this->returnValue( [] ) );
892 $mocks['pre']->expects( $this->once() )->method( 'testForAuthentication' )
893 ->will( $this->returnCallback( function ( $reqs ) use ( $req ) {
894 $this->assertContains( $req, $reqs );
895 return $req->pre;
896 } ) );
898 $ct = count( $req->primary );
899 $callback = $this->returnCallback( function ( $reqs ) use ( $req ) {
900 $this->assertContains( $req, $reqs );
901 return array_shift( $req->primary );
902 } );
903 $mocks['primary']->expects( $this->exactly( min( 1, $ct ) ) )
904 ->method( 'beginPrimaryAuthentication' )
905 ->will( $callback );
906 $mocks['primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
907 ->method( 'continuePrimaryAuthentication' )
908 ->will( $callback );
909 if ( $link ) {
910 $mocks['primary']->expects( $this->any() )->method( 'accountCreationType' )
911 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_LINK ) );
914 $ct = count( $req->secondary );
915 $callback = $this->returnCallback( function ( $user, $reqs ) use ( $id, $name, $req ) {
916 $this->assertSame( $id, $user->getId() );
917 $this->assertSame( $name, $user->getName() );
918 $this->assertContains( $req, $reqs );
919 return array_shift( $req->secondary );
920 } );
921 $mocks['secondary']->expects( $this->exactly( min( 1, $ct ) ) )
922 ->method( 'beginSecondaryAuthentication' )
923 ->will( $callback );
924 $mocks['secondary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
925 ->method( 'continueSecondaryAuthentication' )
926 ->will( $callback );
928 $abstain = AuthenticationResponse::newAbstain();
929 $mocks['pre2']->expects( $this->atMost( 1 ) )->method( 'testForAuthentication' )
930 ->will( $this->returnValue( StatusValue::newGood() ) );
931 $mocks['primary2']->expects( $this->atMost( 1 ) )->method( 'beginPrimaryAuthentication' )
932 ->will( $this->returnValue( $abstain ) );
933 $mocks['primary2']->expects( $this->never() )->method( 'continuePrimaryAuthentication' );
934 $mocks['secondary2']->expects( $this->atMost( 1 ) )->method( 'beginSecondaryAuthentication' )
935 ->will( $this->returnValue( $abstain ) );
936 $mocks['secondary2']->expects( $this->never() )->method( 'continueSecondaryAuthentication' );
937 $mocks['secondary3']->expects( $this->atMost( 1 ) )->method( 'beginSecondaryAuthentication' )
938 ->will( $this->returnValue( $abstain ) );
939 $mocks['secondary3']->expects( $this->never() )->method( 'continueSecondaryAuthentication' );
941 $this->preauthMocks = [ $mocks['pre'], $mocks['pre2'] ];
942 $this->primaryauthMocks = [ $mocks['primary'], $mocks['primary2'] ];
943 $this->secondaryauthMocks = [
944 $mocks['secondary3'], $mocks['secondary'], $mocks['secondary2'],
945 // So linking happens
946 new ConfirmLinkSecondaryAuthenticationProvider,
948 $this->initializeManager( true );
949 $this->logger->setCollect( true );
951 $constraint = \PHPUnit_Framework_Assert::logicalOr(
952 $this->equalTo( AuthenticationResponse::PASS ),
953 $this->equalTo( AuthenticationResponse::FAIL )
955 $providers = array_filter(
956 array_merge(
957 $this->preauthMocks, $this->primaryauthMocks, $this->secondaryauthMocks
959 function ( $p ) {
960 return is_callable( [ $p, 'expects' ] );
963 foreach ( $providers as $p ) {
964 $p->postCalled = false;
965 $p->expects( $this->atMost( 1 ) )->method( 'postAuthentication' )
966 ->willReturnCallback( function ( $user, $response ) use ( $constraint, $p ) {
967 if ( $user !== null ) {
968 $this->assertInstanceOf( 'User', $user );
969 $this->assertSame( 'UTSysop', $user->getName() );
971 $this->assertInstanceOf( AuthenticationResponse::class, $response );
972 $this->assertThat( $response->status, $constraint );
973 $p->postCalled = $response->status;
974 } );
977 $session = $this->request->getSession();
978 $session->setRememberUser( !$req->rememberMe );
980 foreach ( $managerResponses as $i => $response ) {
981 $success = $response instanceof AuthenticationResponse &&
982 $response->status === AuthenticationResponse::PASS;
983 if ( $success ) {
984 $this->hook( 'UserLoggedIn', $this->once() )
985 ->with( $this->callback( function ( $user ) use ( $id, $name ) {
986 return $user->getId() === $id && $user->getName() === $name;
987 } ) );
988 } else {
989 $this->hook( 'UserLoggedIn', $this->never() );
991 if ( $success || (
992 $response instanceof AuthenticationResponse &&
993 $response->status === AuthenticationResponse::FAIL &&
994 $response->message->getKey() !== 'authmanager-authn-not-in-progress' &&
995 $response->message->getKey() !== 'authmanager-authn-no-primary'
998 $this->hook( 'AuthManagerLoginAuthenticateAudit', $this->once() );
999 } else {
1000 $this->hook( 'AuthManagerLoginAuthenticateAudit', $this->never() );
1003 $ex = null;
1004 try {
1005 if ( !$i ) {
1006 $ret = $this->manager->beginAuthentication( [ $req ], 'http://localhost/' );
1007 } else {
1008 $ret = $this->manager->continueAuthentication( [ $req ] );
1010 if ( $response instanceof \Exception ) {
1011 $this->fail( 'Expected exception not thrown', "Response $i" );
1013 } catch ( \Exception $ex ) {
1014 if ( !$response instanceof \Exception ) {
1015 throw $ex;
1017 $this->assertEquals( $response->getMessage(), $ex->getMessage(), "Response $i, exception" );
1018 $this->assertNull( $session->getSecret( 'AuthManager::authnState' ),
1019 "Response $i, exception, session state" );
1020 $this->unhook( 'UserLoggedIn' );
1021 $this->unhook( 'AuthManagerLoginAuthenticateAudit' );
1022 return;
1025 $this->unhook( 'UserLoggedIn' );
1026 $this->unhook( 'AuthManagerLoginAuthenticateAudit' );
1028 $this->assertSame( 'http://localhost/', $req->returnToUrl );
1030 $ret->message = $this->message( $ret->message );
1031 $this->assertEquals( $response, $ret, "Response $i, response" );
1032 if ( $success ) {
1033 $this->assertSame( $id, $session->getUser()->getId(),
1034 "Response $i, authn" );
1035 } else {
1036 $this->assertSame( 0, $session->getUser()->getId(),
1037 "Response $i, authn" );
1039 if ( $success || $response->status === AuthenticationResponse::FAIL ) {
1040 $this->assertNull( $session->getSecret( 'AuthManager::authnState' ),
1041 "Response $i, session state" );
1042 foreach ( $providers as $p ) {
1043 $this->assertSame( $response->status, $p->postCalled,
1044 "Response $i, post-auth callback called" );
1046 } else {
1047 $this->assertNotNull( $session->getSecret( 'AuthManager::authnState' ),
1048 "Response $i, session state" );
1049 foreach ( $ret->neededRequests as $neededReq ) {
1050 $this->assertEquals( AuthManager::ACTION_LOGIN, $neededReq->action,
1051 "Response $i, neededRequest action" );
1053 $this->assertEquals(
1054 $ret->neededRequests,
1055 $this->manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN_CONTINUE ),
1056 "Response $i, continuation check"
1058 foreach ( $providers as $p ) {
1059 $this->assertFalse( $p->postCalled, "Response $i, post-auth callback not called" );
1063 $state = $session->getSecret( 'AuthManager::authnState' );
1064 $maybeLink = isset( $state['maybeLink'] ) ? $state['maybeLink'] : [];
1065 if ( $link && $response->status === AuthenticationResponse::RESTART ) {
1066 $this->assertEquals(
1067 $response->createRequest->maybeLink,
1068 $maybeLink,
1069 "Response $i, maybeLink"
1071 } else {
1072 $this->assertEquals( [], $maybeLink, "Response $i, maybeLink" );
1076 if ( $success ) {
1077 $this->assertSame( $req->rememberMe, $session->shouldRememberUser(),
1078 'rememberMe checkbox had effect' );
1079 } else {
1080 $this->assertNotSame( $req->rememberMe, $session->shouldRememberUser(),
1081 'rememberMe checkbox wasn\'t applied' );
1085 public function provideAuthentication() {
1086 $user = \User::newFromName( 'UTSysop' );
1087 $id = $user->getId();
1088 $name = $user->getName();
1090 $rememberReq = new RememberMeAuthenticationRequest;
1091 $rememberReq->action = AuthManager::ACTION_LOGIN;
1093 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1094 $req->foobar = 'baz';
1095 $restartResponse = AuthenticationResponse::newRestart(
1096 $this->message( 'authmanager-authn-no-local-user' )
1098 $restartResponse->neededRequests = [ $rememberReq ];
1100 $restartResponse2Pass = AuthenticationResponse::newPass( null );
1101 $restartResponse2Pass->linkRequest = $req;
1102 $restartResponse2 = AuthenticationResponse::newRestart(
1103 $this->message( 'authmanager-authn-no-local-user-link' )
1105 $restartResponse2->createRequest = new CreateFromLoginAuthenticationRequest(
1106 null, [ $req->getUniqueId() => $req ]
1108 $restartResponse2->createRequest->action = AuthManager::ACTION_LOGIN;
1109 $restartResponse2->neededRequests = [ $rememberReq, $restartResponse2->createRequest ];
1111 return [
1112 'Failure in pre-auth' => [
1113 StatusValue::newFatal( 'fail-from-pre' ),
1117 AuthenticationResponse::newFail( $this->message( 'fail-from-pre' ) ),
1118 AuthenticationResponse::newFail(
1119 $this->message( 'authmanager-authn-not-in-progress' )
1123 'Failure in primary' => [
1124 StatusValue::newGood(),
1125 $tmp = [
1126 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
1129 $tmp
1131 'All primary abstain' => [
1132 StatusValue::newGood(),
1134 AuthenticationResponse::newAbstain(),
1138 AuthenticationResponse::newFail( $this->message( 'authmanager-authn-no-primary' ) )
1141 'Primary UI, then redirect, then fail' => [
1142 StatusValue::newGood(),
1143 $tmp = [
1144 AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1145 AuthenticationResponse::newRedirect( [ $req ], '/foo.html', [ 'foo' => 'bar' ] ),
1146 AuthenticationResponse::newFail( $this->message( 'fail-in-primary-continue' ) ),
1149 $tmp
1151 'Primary redirect, then abstain' => [
1152 StatusValue::newGood(),
1154 $tmp = AuthenticationResponse::newRedirect(
1155 [ $req ], '/foo.html', [ 'foo' => 'bar' ]
1157 AuthenticationResponse::newAbstain(),
1161 $tmp,
1162 new \DomainException(
1163 'MockPrimaryAuthenticationProvider::continuePrimaryAuthentication() returned ABSTAIN'
1167 'Primary UI, then pass with no local user' => [
1168 StatusValue::newGood(),
1170 $tmp = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1171 AuthenticationResponse::newPass( null ),
1175 $tmp,
1176 $restartResponse,
1179 'Primary UI, then pass with no local user (link type)' => [
1180 StatusValue::newGood(),
1182 $tmp = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1183 $restartResponse2Pass,
1187 $tmp,
1188 $restartResponse2,
1190 true
1192 'Primary pass with invalid username' => [
1193 StatusValue::newGood(),
1195 AuthenticationResponse::newPass( '<>' ),
1199 new \DomainException( 'MockPrimaryAuthenticationProvider returned an invalid username: <>' ),
1202 'Secondary fail' => [
1203 StatusValue::newGood(),
1205 AuthenticationResponse::newPass( $name ),
1207 $tmp = [
1208 AuthenticationResponse::newFail( $this->message( 'fail-in-secondary' ) ),
1210 $tmp
1212 'Secondary UI, then abstain' => [
1213 StatusValue::newGood(),
1215 AuthenticationResponse::newPass( $name ),
1218 $tmp = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
1219 AuthenticationResponse::newAbstain()
1222 $tmp,
1223 AuthenticationResponse::newPass( $name ),
1226 'Secondary pass' => [
1227 StatusValue::newGood(),
1229 AuthenticationResponse::newPass( $name ),
1232 AuthenticationResponse::newPass()
1235 AuthenticationResponse::newPass( $name ),
1242 * @dataProvider provideUserExists
1243 * @param bool $primary1Exists
1244 * @param bool $primary2Exists
1245 * @param bool $expect
1247 public function testUserExists( $primary1Exists, $primary2Exists, $expect ) {
1248 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1249 $mock1->expects( $this->any() )->method( 'getUniqueId' )
1250 ->will( $this->returnValue( 'primary1' ) );
1251 $mock1->expects( $this->any() )->method( 'testUserExists' )
1252 ->with( $this->equalTo( 'UTSysop' ) )
1253 ->will( $this->returnValue( $primary1Exists ) );
1254 $mock2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1255 $mock2->expects( $this->any() )->method( 'getUniqueId' )
1256 ->will( $this->returnValue( 'primary2' ) );
1257 $mock2->expects( $this->any() )->method( 'testUserExists' )
1258 ->with( $this->equalTo( 'UTSysop' ) )
1259 ->will( $this->returnValue( $primary2Exists ) );
1260 $this->primaryauthMocks = [ $mock1, $mock2 ];
1262 $this->initializeManager( true );
1263 $this->assertSame( $expect, $this->manager->userExists( 'UTSysop' ) );
1266 public static function provideUserExists() {
1267 return [
1268 [ false, false, false ],
1269 [ true, false, true ],
1270 [ false, true, true ],
1271 [ true, true, true ],
1276 * @dataProvider provideAllowsAuthenticationDataChange
1277 * @param StatusValue $primaryReturn
1278 * @param StatusValue $secondaryReturn
1279 * @param Status $expect
1281 public function testAllowsAuthenticationDataChange( $primaryReturn, $secondaryReturn, $expect ) {
1282 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1284 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1285 $mock1->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( '1' ) );
1286 $mock1->expects( $this->any() )->method( 'providerAllowsAuthenticationDataChange' )
1287 ->with( $this->equalTo( $req ) )
1288 ->will( $this->returnValue( $primaryReturn ) );
1289 $mock2 = $this->getMockForAbstractClass( SecondaryAuthenticationProvider::class );
1290 $mock2->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( '2' ) );
1291 $mock2->expects( $this->any() )->method( 'providerAllowsAuthenticationDataChange' )
1292 ->with( $this->equalTo( $req ) )
1293 ->will( $this->returnValue( $secondaryReturn ) );
1295 $this->primaryauthMocks = [ $mock1 ];
1296 $this->secondaryauthMocks = [ $mock2 ];
1297 $this->initializeManager( true );
1298 $this->assertEquals( $expect, $this->manager->allowsAuthenticationDataChange( $req ) );
1301 public static function provideAllowsAuthenticationDataChange() {
1302 $ignored = \Status::newGood( 'ignored' );
1303 $ignored->warning( 'authmanager-change-not-supported' );
1305 $okFromPrimary = StatusValue::newGood();
1306 $okFromPrimary->warning( 'warning-from-primary' );
1307 $okFromSecondary = StatusValue::newGood();
1308 $okFromSecondary->warning( 'warning-from-secondary' );
1310 return [
1312 StatusValue::newGood(),
1313 StatusValue::newGood(),
1314 \Status::newGood(),
1317 StatusValue::newGood(),
1318 StatusValue::newGood( 'ignore' ),
1319 \Status::newGood(),
1322 StatusValue::newGood( 'ignored' ),
1323 StatusValue::newGood(),
1324 \Status::newGood(),
1327 StatusValue::newGood( 'ignored' ),
1328 StatusValue::newGood( 'ignored' ),
1329 $ignored,
1332 StatusValue::newFatal( 'fail from primary' ),
1333 StatusValue::newGood(),
1334 \Status::newFatal( 'fail from primary' ),
1337 $okFromPrimary,
1338 StatusValue::newGood(),
1339 \Status::wrap( $okFromPrimary ),
1342 StatusValue::newGood(),
1343 StatusValue::newFatal( 'fail from secondary' ),
1344 \Status::newFatal( 'fail from secondary' ),
1347 StatusValue::newGood(),
1348 $okFromSecondary,
1349 \Status::wrap( $okFromSecondary ),
1354 public function testChangeAuthenticationData() {
1355 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1356 $req->username = 'UTSysop';
1358 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1359 $mock1->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( '1' ) );
1360 $mock1->expects( $this->once() )->method( 'providerChangeAuthenticationData' )
1361 ->with( $this->equalTo( $req ) );
1362 $mock2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1363 $mock2->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( '2' ) );
1364 $mock2->expects( $this->once() )->method( 'providerChangeAuthenticationData' )
1365 ->with( $this->equalTo( $req ) );
1367 $this->primaryauthMocks = [ $mock1, $mock2 ];
1368 $this->initializeManager( true );
1369 $this->logger->setCollect( true );
1370 $this->manager->changeAuthenticationData( $req );
1371 $this->assertSame( [
1372 [ LogLevel::INFO, 'Changing authentication data for {user} class {what}' ],
1373 ], $this->logger->getBuffer() );
1376 public function testCanCreateAccounts() {
1377 $types = [
1378 PrimaryAuthenticationProvider::TYPE_CREATE => true,
1379 PrimaryAuthenticationProvider::TYPE_LINK => true,
1380 PrimaryAuthenticationProvider::TYPE_NONE => false,
1383 foreach ( $types as $type => $can ) {
1384 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1385 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( $type ) );
1386 $mock->expects( $this->any() )->method( 'accountCreationType' )
1387 ->will( $this->returnValue( $type ) );
1388 $this->primaryauthMocks = [ $mock ];
1389 $this->initializeManager( true );
1390 $this->assertSame( $can, $this->manager->canCreateAccounts(), $type );
1394 public function testCheckAccountCreatePermissions() {
1395 global $wgGroupPermissions;
1397 $this->stashMwGlobals( [ 'wgGroupPermissions' ] );
1399 $this->initializeManager( true );
1401 $wgGroupPermissions['*']['createaccount'] = true;
1402 $this->assertEquals(
1403 \Status::newGood(),
1404 $this->manager->checkAccountCreatePermissions( new \User )
1407 $this->setMwGlobals( [ 'wgReadOnly' => 'Because' ] );
1408 $this->assertEquals(
1409 \Status::newFatal( 'readonlytext', 'Because' ),
1410 $this->manager->checkAccountCreatePermissions( new \User )
1412 $this->setMwGlobals( [ 'wgReadOnly' => false ] );
1414 $wgGroupPermissions['*']['createaccount'] = false;
1415 $status = $this->manager->checkAccountCreatePermissions( new \User );
1416 $this->assertFalse( $status->isOK() );
1417 $this->assertTrue( $status->hasMessage( 'badaccess-groups' ) );
1418 $wgGroupPermissions['*']['createaccount'] = true;
1420 $user = \User::newFromName( 'UTBlockee' );
1421 if ( $user->getID() == 0 ) {
1422 $user->addToDatabase();
1423 \TestUser::setPasswordForUser( $user, 'UTBlockeePassword' );
1424 $user->saveSettings();
1426 $oldBlock = \Block::newFromTarget( 'UTBlockee' );
1427 if ( $oldBlock ) {
1428 // An old block will prevent our new one from saving.
1429 $oldBlock->delete();
1431 $blockOptions = [
1432 'address' => 'UTBlockee',
1433 'user' => $user->getID(),
1434 'reason' => __METHOD__,
1435 'expiry' => time() + 100500,
1436 'createAccount' => true,
1438 $block = new \Block( $blockOptions );
1439 $block->insert();
1440 $status = $this->manager->checkAccountCreatePermissions( $user );
1441 $this->assertFalse( $status->isOK() );
1442 $this->assertTrue( $status->hasMessage( 'cantcreateaccount-text' ) );
1444 $blockOptions = [
1445 'address' => '127.0.0.0/24',
1446 'reason' => __METHOD__,
1447 'expiry' => time() + 100500,
1448 'createAccount' => true,
1450 $block = new \Block( $blockOptions );
1451 $block->insert();
1452 $scopeVariable = new ScopedCallback( [ $block, 'delete' ] );
1453 $status = $this->manager->checkAccountCreatePermissions( new \User );
1454 $this->assertFalse( $status->isOK() );
1455 $this->assertTrue( $status->hasMessage( 'cantcreateaccount-range-text' ) );
1456 ScopedCallback::consume( $scopeVariable );
1458 $this->setMwGlobals( [
1459 'wgEnableDnsBlacklist' => true,
1460 'wgDnsBlacklistUrls' => [
1461 'local.wmftest.net', // This will resolve for every subdomain, which works to test "listed?"
1463 'wgProxyWhitelist' => [],
1464 ] );
1465 $status = $this->manager->checkAccountCreatePermissions( new \User );
1466 $this->assertFalse( $status->isOK() );
1467 $this->assertTrue( $status->hasMessage( 'sorbs_create_account_reason' ) );
1468 $this->setMwGlobals( 'wgProxyWhitelist', [ '127.0.0.1' ] );
1469 $status = $this->manager->checkAccountCreatePermissions( new \User );
1470 $this->assertTrue( $status->isGood() );
1474 * @param string $uniq
1475 * @return string
1477 private static function usernameForCreation( $uniq = '' ) {
1478 $i = 0;
1479 do {
1480 $username = "UTAuthManagerTestAccountCreation" . $uniq . ++$i;
1481 } while ( \User::newFromName( $username )->getId() !== 0 );
1482 return $username;
1485 public function testCanCreateAccount() {
1486 $username = self::usernameForCreation();
1487 $this->initializeManager();
1489 $this->assertEquals(
1490 \Status::newFatal( 'authmanager-create-disabled' ),
1491 $this->manager->canCreateAccount( $username )
1494 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1495 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1496 $mock->expects( $this->any() )->method( 'accountCreationType' )
1497 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1498 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( true ) );
1499 $mock->expects( $this->any() )->method( 'testUserForCreation' )
1500 ->will( $this->returnValue( StatusValue::newGood() ) );
1501 $this->primaryauthMocks = [ $mock ];
1502 $this->initializeManager( true );
1504 $this->assertEquals(
1505 \Status::newFatal( 'userexists' ),
1506 $this->manager->canCreateAccount( $username )
1509 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1510 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1511 $mock->expects( $this->any() )->method( 'accountCreationType' )
1512 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1513 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( false ) );
1514 $mock->expects( $this->any() )->method( 'testUserForCreation' )
1515 ->will( $this->returnValue( StatusValue::newGood() ) );
1516 $this->primaryauthMocks = [ $mock ];
1517 $this->initializeManager( true );
1519 $this->assertEquals(
1520 \Status::newFatal( 'noname' ),
1521 $this->manager->canCreateAccount( $username . '<>' )
1524 $this->assertEquals(
1525 \Status::newFatal( 'userexists' ),
1526 $this->manager->canCreateAccount( 'UTSysop' )
1529 $this->assertEquals(
1530 \Status::newGood(),
1531 $this->manager->canCreateAccount( $username )
1534 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1535 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1536 $mock->expects( $this->any() )->method( 'accountCreationType' )
1537 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1538 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( false ) );
1539 $mock->expects( $this->any() )->method( 'testUserForCreation' )
1540 ->will( $this->returnValue( StatusValue::newFatal( 'fail' ) ) );
1541 $this->primaryauthMocks = [ $mock ];
1542 $this->initializeManager( true );
1544 $this->assertEquals(
1545 \Status::newFatal( 'fail' ),
1546 $this->manager->canCreateAccount( $username )
1550 public function testBeginAccountCreation() {
1551 $creator = \User::newFromName( 'UTSysop' );
1552 $userReq = new UsernameAuthenticationRequest;
1553 $this->logger = new \TestLogger( false, function ( $message, $level ) {
1554 return $level === LogLevel::DEBUG ? null : $message;
1555 } );
1556 $this->initializeManager();
1558 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState', 'test' );
1559 $this->hook( 'LocalUserCreated', $this->never() );
1560 try {
1561 $this->manager->beginAccountCreation(
1562 $creator, [], 'http://localhost/'
1564 $this->fail( 'Expected exception not thrown' );
1565 } catch ( \LogicException $ex ) {
1566 $this->assertEquals( 'Account creation is not possible', $ex->getMessage() );
1568 $this->unhook( 'LocalUserCreated' );
1569 $this->assertNull(
1570 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
1573 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1574 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1575 $mock->expects( $this->any() )->method( 'accountCreationType' )
1576 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1577 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( true ) );
1578 $mock->expects( $this->any() )->method( 'testUserForCreation' )
1579 ->will( $this->returnValue( StatusValue::newGood() ) );
1580 $this->primaryauthMocks = [ $mock ];
1581 $this->initializeManager( true );
1583 $this->hook( 'LocalUserCreated', $this->never() );
1584 $ret = $this->manager->beginAccountCreation( $creator, [], 'http://localhost/' );
1585 $this->unhook( 'LocalUserCreated' );
1586 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1587 $this->assertSame( 'noname', $ret->message->getKey() );
1589 $this->hook( 'LocalUserCreated', $this->never() );
1590 $userReq->username = self::usernameForCreation();
1591 $userReq2 = new UsernameAuthenticationRequest;
1592 $userReq2->username = $userReq->username . 'X';
1593 $ret = $this->manager->beginAccountCreation(
1594 $creator, [ $userReq, $userReq2 ], 'http://localhost/'
1596 $this->unhook( 'LocalUserCreated' );
1597 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1598 $this->assertSame( 'noname', $ret->message->getKey() );
1600 $this->setMwGlobals( [ 'wgReadOnly' => 'Because' ] );
1601 $this->hook( 'LocalUserCreated', $this->never() );
1602 $userReq->username = self::usernameForCreation();
1603 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
1604 $this->unhook( 'LocalUserCreated' );
1605 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1606 $this->assertSame( 'readonlytext', $ret->message->getKey() );
1607 $this->assertSame( [ 'Because' ], $ret->message->getParams() );
1608 $this->setMwGlobals( [ 'wgReadOnly' => false ] );
1610 $this->hook( 'LocalUserCreated', $this->never() );
1611 $userReq->username = self::usernameForCreation();
1612 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
1613 $this->unhook( 'LocalUserCreated' );
1614 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1615 $this->assertSame( 'userexists', $ret->message->getKey() );
1617 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1618 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1619 $mock->expects( $this->any() )->method( 'accountCreationType' )
1620 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1621 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( false ) );
1622 $mock->expects( $this->any() )->method( 'testUserForCreation' )
1623 ->will( $this->returnValue( StatusValue::newFatal( 'fail' ) ) );
1624 $this->primaryauthMocks = [ $mock ];
1625 $this->initializeManager( true );
1627 $this->hook( 'LocalUserCreated', $this->never() );
1628 $userReq->username = self::usernameForCreation();
1629 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
1630 $this->unhook( 'LocalUserCreated' );
1631 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1632 $this->assertSame( 'fail', $ret->message->getKey() );
1634 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1635 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1636 $mock->expects( $this->any() )->method( 'accountCreationType' )
1637 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1638 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( false ) );
1639 $mock->expects( $this->any() )->method( 'testUserForCreation' )
1640 ->will( $this->returnValue( StatusValue::newGood() ) );
1641 $this->primaryauthMocks = [ $mock ];
1642 $this->initializeManager( true );
1644 $this->hook( 'LocalUserCreated', $this->never() );
1645 $userReq->username = self::usernameForCreation() . '<>';
1646 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
1647 $this->unhook( 'LocalUserCreated' );
1648 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1649 $this->assertSame( 'noname', $ret->message->getKey() );
1651 $this->hook( 'LocalUserCreated', $this->never() );
1652 $userReq->username = $creator->getName();
1653 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ], 'http://localhost/' );
1654 $this->unhook( 'LocalUserCreated' );
1655 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1656 $this->assertSame( 'userexists', $ret->message->getKey() );
1658 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1659 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1660 $mock->expects( $this->any() )->method( 'accountCreationType' )
1661 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1662 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( false ) );
1663 $mock->expects( $this->any() )->method( 'testUserForCreation' )
1664 ->will( $this->returnValue( StatusValue::newGood() ) );
1665 $mock->expects( $this->any() )->method( 'testForAccountCreation' )
1666 ->will( $this->returnValue( StatusValue::newFatal( 'fail' ) ) );
1667 $this->primaryauthMocks = [ $mock ];
1668 $this->initializeManager( true );
1670 $req = $this->getMockBuilder( UserDataAuthenticationRequest::class )
1671 ->setMethods( [ 'populateUser' ] )
1672 ->getMock();
1673 $req->expects( $this->any() )->method( 'populateUser' )
1674 ->willReturn( \StatusValue::newFatal( 'populatefail' ) );
1675 $userReq->username = self::usernameForCreation();
1676 $ret = $this->manager->beginAccountCreation(
1677 $creator, [ $userReq, $req ], 'http://localhost/'
1679 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1680 $this->assertSame( 'populatefail', $ret->message->getKey() );
1682 $req = new UserDataAuthenticationRequest;
1683 $userReq->username = self::usernameForCreation();
1685 $ret = $this->manager->beginAccountCreation(
1686 $creator, [ $userReq, $req ], 'http://localhost/'
1688 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1689 $this->assertSame( 'fail', $ret->message->getKey() );
1691 $this->manager->beginAccountCreation(
1692 \User::newFromName( $userReq->username ), [ $userReq, $req ], 'http://localhost/'
1694 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1695 $this->assertSame( 'fail', $ret->message->getKey() );
1698 public function testContinueAccountCreation() {
1699 $creator = \User::newFromName( 'UTSysop' );
1700 $username = self::usernameForCreation();
1701 $this->logger = new \TestLogger( false, function ( $message, $level ) {
1702 return $level === LogLevel::DEBUG ? null : $message;
1703 } );
1704 $this->initializeManager();
1706 $session = [
1707 'userid' => 0,
1708 'username' => $username,
1709 'creatorid' => 0,
1710 'creatorname' => $username,
1711 'reqs' => [],
1712 'primary' => null,
1713 'primaryResponse' => null,
1714 'secondary' => [],
1715 'ranPreTests' => true,
1718 $this->hook( 'LocalUserCreated', $this->never() );
1719 try {
1720 $this->manager->continueAccountCreation( [] );
1721 $this->fail( 'Expected exception not thrown' );
1722 } catch ( \LogicException $ex ) {
1723 $this->assertEquals( 'Account creation is not possible', $ex->getMessage() );
1725 $this->unhook( 'LocalUserCreated' );
1727 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1728 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
1729 $mock->expects( $this->any() )->method( 'accountCreationType' )
1730 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1731 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( false ) );
1732 $mock->expects( $this->any() )->method( 'beginPrimaryAccountCreation' )->will(
1733 $this->returnValue( AuthenticationResponse::newFail( $this->message( 'fail' ) ) )
1735 $this->primaryauthMocks = [ $mock ];
1736 $this->initializeManager( true );
1738 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState', null );
1739 $this->hook( 'LocalUserCreated', $this->never() );
1740 $ret = $this->manager->continueAccountCreation( [] );
1741 $this->unhook( 'LocalUserCreated' );
1742 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1743 $this->assertSame( 'authmanager-create-not-in-progress', $ret->message->getKey() );
1745 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState',
1746 [ 'username' => "$username<>" ] + $session );
1747 $this->hook( 'LocalUserCreated', $this->never() );
1748 $ret = $this->manager->continueAccountCreation( [] );
1749 $this->unhook( 'LocalUserCreated' );
1750 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1751 $this->assertSame( 'noname', $ret->message->getKey() );
1752 $this->assertNull(
1753 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
1756 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState', $session );
1757 $this->hook( 'LocalUserCreated', $this->never() );
1758 $cache = \ObjectCache::getLocalClusterInstance();
1759 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
1760 $ret = $this->manager->continueAccountCreation( [] );
1761 unset( $lock );
1762 $this->unhook( 'LocalUserCreated' );
1763 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1764 $this->assertSame( 'usernameinprogress', $ret->message->getKey() );
1765 // This error shouldn't remove the existing session, because the
1766 // raced-with process "owns" it.
1767 $this->assertSame(
1768 $session, $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
1771 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState',
1772 [ 'username' => $creator->getName() ] + $session );
1773 $this->setMwGlobals( [ 'wgReadOnly' => 'Because' ] );
1774 $this->hook( 'LocalUserCreated', $this->never() );
1775 $ret = $this->manager->continueAccountCreation( [] );
1776 $this->unhook( 'LocalUserCreated' );
1777 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1778 $this->assertSame( 'readonlytext', $ret->message->getKey() );
1779 $this->assertSame( [ 'Because' ], $ret->message->getParams() );
1780 $this->setMwGlobals( [ 'wgReadOnly' => false ] );
1782 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState',
1783 [ 'username' => $creator->getName() ] + $session );
1784 $this->hook( 'LocalUserCreated', $this->never() );
1785 $ret = $this->manager->continueAccountCreation( [] );
1786 $this->unhook( 'LocalUserCreated' );
1787 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1788 $this->assertSame( 'userexists', $ret->message->getKey() );
1789 $this->assertNull(
1790 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
1793 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState',
1794 [ 'userid' => $creator->getId() ] + $session );
1795 $this->hook( 'LocalUserCreated', $this->never() );
1796 try {
1797 $ret = $this->manager->continueAccountCreation( [] );
1798 $this->fail( 'Expected exception not thrown' );
1799 } catch ( \UnexpectedValueException $ex ) {
1800 $this->assertEquals( "User \"{$username}\" should exist now, but doesn't!", $ex->getMessage() );
1802 $this->unhook( 'LocalUserCreated' );
1803 $this->assertNull(
1804 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
1807 $id = $creator->getId();
1808 $name = $creator->getName();
1809 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState',
1810 [ 'username' => $name, 'userid' => $id + 1 ] + $session );
1811 $this->hook( 'LocalUserCreated', $this->never() );
1812 try {
1813 $ret = $this->manager->continueAccountCreation( [] );
1814 $this->fail( 'Expected exception not thrown' );
1815 } catch ( \UnexpectedValueException $ex ) {
1816 $this->assertEquals(
1817 "User \"{$name}\" exists, but ID $id != " . ( $id + 1 ) . '!', $ex->getMessage()
1820 $this->unhook( 'LocalUserCreated' );
1821 $this->assertNull(
1822 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
1825 $req = $this->getMockBuilder( UserDataAuthenticationRequest::class )
1826 ->setMethods( [ 'populateUser' ] )
1827 ->getMock();
1828 $req->expects( $this->any() )->method( 'populateUser' )
1829 ->willReturn( \StatusValue::newFatal( 'populatefail' ) );
1830 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState',
1831 [ 'reqs' => [ $req ] ] + $session );
1832 $ret = $this->manager->continueAccountCreation( [] );
1833 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
1834 $this->assertSame( 'populatefail', $ret->message->getKey() );
1835 $this->assertNull(
1836 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' )
1841 * @dataProvider provideAccountCreation
1842 * @param StatusValue $preTest
1843 * @param StatusValue $primaryTest
1844 * @param StatusValue $secondaryTest
1845 * @param array $primaryResponses
1846 * @param array $secondaryResponses
1847 * @param array $managerResponses
1849 public function testAccountCreation(
1850 StatusValue $preTest, $primaryTest, $secondaryTest,
1851 array $primaryResponses, array $secondaryResponses, array $managerResponses
1853 $creator = \User::newFromName( 'UTSysop' );
1854 $username = self::usernameForCreation();
1856 $this->initializeManager();
1858 // Set up lots of mocks...
1859 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1860 $req->preTest = $preTest;
1861 $req->primaryTest = $primaryTest;
1862 $req->secondaryTest = $secondaryTest;
1863 $req->primary = $primaryResponses;
1864 $req->secondary = $secondaryResponses;
1865 $mocks = [];
1866 foreach ( [ 'pre', 'primary', 'secondary' ] as $key ) {
1867 $class = ucfirst( $key ) . 'AuthenticationProvider';
1868 $mocks[$key] = $this->getMockForAbstractClass(
1869 "MediaWiki\\Auth\\$class", [], "Mock$class"
1871 $mocks[$key]->expects( $this->any() )->method( 'getUniqueId' )
1872 ->will( $this->returnValue( $key ) );
1873 $mocks[$key]->expects( $this->any() )->method( 'testUserForCreation' )
1874 ->will( $this->returnValue( StatusValue::newGood() ) );
1875 $mocks[$key]->expects( $this->any() )->method( 'testForAccountCreation' )
1876 ->will( $this->returnCallback(
1877 function ( $user, $creatorIn, $reqs )
1878 use ( $username, $creator, $req, $key )
1880 $this->assertSame( $username, $user->getName() );
1881 $this->assertSame( $creator->getId(), $creatorIn->getId() );
1882 $this->assertSame( $creator->getName(), $creatorIn->getName() );
1883 $foundReq = false;
1884 foreach ( $reqs as $r ) {
1885 $this->assertSame( $username, $r->username );
1886 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
1888 $this->assertTrue( $foundReq, '$reqs contains $req' );
1889 $k = $key . 'Test';
1890 return $req->$k;
1892 ) );
1894 for ( $i = 2; $i <= 3; $i++ ) {
1895 $mocks[$key . $i] = $this->getMockForAbstractClass(
1896 "MediaWiki\\Auth\\$class", [], "Mock$class"
1898 $mocks[$key . $i]->expects( $this->any() )->method( 'getUniqueId' )
1899 ->will( $this->returnValue( $key . $i ) );
1900 $mocks[$key . $i]->expects( $this->any() )->method( 'testUserForCreation' )
1901 ->will( $this->returnValue( StatusValue::newGood() ) );
1902 $mocks[$key . $i]->expects( $this->atMost( 1 ) )->method( 'testForAccountCreation' )
1903 ->will( $this->returnValue( StatusValue::newGood() ) );
1907 $mocks['primary']->expects( $this->any() )->method( 'accountCreationType' )
1908 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
1909 $mocks['primary']->expects( $this->any() )->method( 'testUserExists' )
1910 ->will( $this->returnValue( false ) );
1911 $ct = count( $req->primary );
1912 $callback = $this->returnCallback( function ( $user, $creator, $reqs ) use ( $username, $req ) {
1913 $this->assertSame( $username, $user->getName() );
1914 $this->assertSame( 'UTSysop', $creator->getName() );
1915 $foundReq = false;
1916 foreach ( $reqs as $r ) {
1917 $this->assertSame( $username, $r->username );
1918 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
1920 $this->assertTrue( $foundReq, '$reqs contains $req' );
1921 return array_shift( $req->primary );
1922 } );
1923 $mocks['primary']->expects( $this->exactly( min( 1, $ct ) ) )
1924 ->method( 'beginPrimaryAccountCreation' )
1925 ->will( $callback );
1926 $mocks['primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
1927 ->method( 'continuePrimaryAccountCreation' )
1928 ->will( $callback );
1930 $ct = count( $req->secondary );
1931 $callback = $this->returnCallback( function ( $user, $creator, $reqs ) use ( $username, $req ) {
1932 $this->assertSame( $username, $user->getName() );
1933 $this->assertSame( 'UTSysop', $creator->getName() );
1934 $foundReq = false;
1935 foreach ( $reqs as $r ) {
1936 $this->assertSame( $username, $r->username );
1937 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
1939 $this->assertTrue( $foundReq, '$reqs contains $req' );
1940 return array_shift( $req->secondary );
1941 } );
1942 $mocks['secondary']->expects( $this->exactly( min( 1, $ct ) ) )
1943 ->method( 'beginSecondaryAccountCreation' )
1944 ->will( $callback );
1945 $mocks['secondary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
1946 ->method( 'continueSecondaryAccountCreation' )
1947 ->will( $callback );
1949 $abstain = AuthenticationResponse::newAbstain();
1950 $mocks['primary2']->expects( $this->any() )->method( 'accountCreationType' )
1951 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_LINK ) );
1952 $mocks['primary2']->expects( $this->any() )->method( 'testUserExists' )
1953 ->will( $this->returnValue( false ) );
1954 $mocks['primary2']->expects( $this->atMost( 1 ) )->method( 'beginPrimaryAccountCreation' )
1955 ->will( $this->returnValue( $abstain ) );
1956 $mocks['primary2']->expects( $this->never() )->method( 'continuePrimaryAccountCreation' );
1957 $mocks['primary3']->expects( $this->any() )->method( 'accountCreationType' )
1958 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_NONE ) );
1959 $mocks['primary3']->expects( $this->any() )->method( 'testUserExists' )
1960 ->will( $this->returnValue( false ) );
1961 $mocks['primary3']->expects( $this->never() )->method( 'beginPrimaryAccountCreation' );
1962 $mocks['primary3']->expects( $this->never() )->method( 'continuePrimaryAccountCreation' );
1963 $mocks['secondary2']->expects( $this->atMost( 1 ) )
1964 ->method( 'beginSecondaryAccountCreation' )
1965 ->will( $this->returnValue( $abstain ) );
1966 $mocks['secondary2']->expects( $this->never() )->method( 'continueSecondaryAccountCreation' );
1967 $mocks['secondary3']->expects( $this->atMost( 1 ) )
1968 ->method( 'beginSecondaryAccountCreation' )
1969 ->will( $this->returnValue( $abstain ) );
1970 $mocks['secondary3']->expects( $this->never() )->method( 'continueSecondaryAccountCreation' );
1972 $this->preauthMocks = [ $mocks['pre'], $mocks['pre2'] ];
1973 $this->primaryauthMocks = [ $mocks['primary3'], $mocks['primary'], $mocks['primary2'] ];
1974 $this->secondaryauthMocks = [
1975 $mocks['secondary3'], $mocks['secondary'], $mocks['secondary2']
1978 $this->logger = new \TestLogger( true, function ( $message, $level ) {
1979 return $level === LogLevel::DEBUG ? null : $message;
1980 } );
1981 $expectLog = [];
1982 $this->initializeManager( true );
1984 $constraint = \PHPUnit_Framework_Assert::logicalOr(
1985 $this->equalTo( AuthenticationResponse::PASS ),
1986 $this->equalTo( AuthenticationResponse::FAIL )
1988 $providers = array_merge(
1989 $this->preauthMocks, $this->primaryauthMocks, $this->secondaryauthMocks
1991 foreach ( $providers as $p ) {
1992 $p->postCalled = false;
1993 $p->expects( $this->atMost( 1 ) )->method( 'postAccountCreation' )
1994 ->willReturnCallback( function ( $user, $creator, $response )
1995 use ( $constraint, $p, $username )
1997 $this->assertInstanceOf( 'User', $user );
1998 $this->assertSame( $username, $user->getName() );
1999 $this->assertSame( 'UTSysop', $creator->getName() );
2000 $this->assertInstanceOf( AuthenticationResponse::class, $response );
2001 $this->assertThat( $response->status, $constraint );
2002 $p->postCalled = $response->status;
2003 } );
2006 // We're testing with $wgNewUserLog = false, so assert that it worked
2007 $dbw = wfGetDB( DB_MASTER );
2008 $maxLogId = $dbw->selectField( 'logging', 'MAX(log_id)', [ 'log_type' => 'newusers' ] );
2010 $first = true;
2011 $created = false;
2012 foreach ( $managerResponses as $i => $response ) {
2013 $success = $response instanceof AuthenticationResponse &&
2014 $response->status === AuthenticationResponse::PASS;
2015 if ( $i === 'created' ) {
2016 $created = true;
2017 $this->hook( 'LocalUserCreated', $this->once() )
2018 ->with(
2019 $this->callback( function ( $user ) use ( $username ) {
2020 return $user->getName() === $username;
2021 } ),
2022 $this->equalTo( false )
2024 $expectLog[] = [ LogLevel::INFO, "Creating user {user} during account creation" ];
2025 } else {
2026 $this->hook( 'LocalUserCreated', $this->never() );
2029 $ex = null;
2030 try {
2031 if ( $first ) {
2032 $userReq = new UsernameAuthenticationRequest;
2033 $userReq->username = $username;
2034 $ret = $this->manager->beginAccountCreation(
2035 $creator, [ $userReq, $req ], 'http://localhost/'
2037 } else {
2038 $ret = $this->manager->continueAccountCreation( [ $req ] );
2040 if ( $response instanceof \Exception ) {
2041 $this->fail( 'Expected exception not thrown', "Response $i" );
2043 } catch ( \Exception $ex ) {
2044 if ( !$response instanceof \Exception ) {
2045 throw $ex;
2047 $this->assertEquals( $response->getMessage(), $ex->getMessage(), "Response $i, exception" );
2048 $this->assertNull(
2049 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' ),
2050 "Response $i, exception, session state"
2052 $this->unhook( 'LocalUserCreated' );
2053 return;
2056 $this->unhook( 'LocalUserCreated' );
2058 $this->assertSame( 'http://localhost/', $req->returnToUrl );
2060 if ( $success ) {
2061 $this->assertNotNull( $ret->loginRequest, "Response $i, login marker" );
2062 $this->assertContains(
2063 $ret->loginRequest, $this->managerPriv->createdAccountAuthenticationRequests,
2064 "Response $i, login marker"
2067 $expectLog[] = [
2068 LogLevel::INFO,
2069 "MediaWiki\Auth\AuthManager::continueAccountCreation: Account creation succeeded for {user}"
2072 // Set some fields in the expected $response that we couldn't
2073 // know in provideAccountCreation().
2074 $response->username = $username;
2075 $response->loginRequest = $ret->loginRequest;
2076 } else {
2077 $this->assertNull( $ret->loginRequest, "Response $i, login marker" );
2078 $this->assertSame( [], $this->managerPriv->createdAccountAuthenticationRequests,
2079 "Response $i, login marker" );
2081 $ret->message = $this->message( $ret->message );
2082 $this->assertEquals( $response, $ret, "Response $i, response" );
2083 if ( $success || $response->status === AuthenticationResponse::FAIL ) {
2084 $this->assertNull(
2085 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' ),
2086 "Response $i, session state"
2088 foreach ( $providers as $p ) {
2089 $this->assertSame( $response->status, $p->postCalled,
2090 "Response $i, post-auth callback called" );
2092 } else {
2093 $this->assertNotNull(
2094 $this->request->getSession()->getSecret( 'AuthManager::accountCreationState' ),
2095 "Response $i, session state"
2097 foreach ( $ret->neededRequests as $neededReq ) {
2098 $this->assertEquals( AuthManager::ACTION_CREATE, $neededReq->action,
2099 "Response $i, neededRequest action" );
2101 $this->assertEquals(
2102 $ret->neededRequests,
2103 $this->manager->getAuthenticationRequests( AuthManager::ACTION_CREATE_CONTINUE ),
2104 "Response $i, continuation check"
2106 foreach ( $providers as $p ) {
2107 $this->assertFalse( $p->postCalled, "Response $i, post-auth callback not called" );
2111 if ( $created ) {
2112 $this->assertNotEquals( 0, \User::idFromName( $username ) );
2113 } else {
2114 $this->assertEquals( 0, \User::idFromName( $username ) );
2117 $first = false;
2120 $this->assertSame( $expectLog, $this->logger->getBuffer() );
2122 $this->assertSame(
2123 $maxLogId,
2124 $dbw->selectField( 'logging', 'MAX(log_id)', [ 'log_type' => 'newusers' ] )
2128 public function provideAccountCreation() {
2129 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
2130 $good = StatusValue::newGood();
2132 return [
2133 'Pre-creation test fail in pre' => [
2134 StatusValue::newFatal( 'fail-from-pre' ), $good, $good,
2138 AuthenticationResponse::newFail( $this->message( 'fail-from-pre' ) ),
2141 'Pre-creation test fail in primary' => [
2142 $good, StatusValue::newFatal( 'fail-from-primary' ), $good,
2146 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
2149 'Pre-creation test fail in secondary' => [
2150 $good, $good, StatusValue::newFatal( 'fail-from-secondary' ),
2154 AuthenticationResponse::newFail( $this->message( 'fail-from-secondary' ) ),
2157 'Failure in primary' => [
2158 $good, $good, $good,
2159 $tmp = [
2160 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
2163 $tmp
2165 'All primary abstain' => [
2166 $good, $good, $good,
2168 AuthenticationResponse::newAbstain(),
2172 AuthenticationResponse::newFail( $this->message( 'authmanager-create-no-primary' ) )
2175 'Primary UI, then redirect, then fail' => [
2176 $good, $good, $good,
2177 $tmp = [
2178 AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
2179 AuthenticationResponse::newRedirect( [ $req ], '/foo.html', [ 'foo' => 'bar' ] ),
2180 AuthenticationResponse::newFail( $this->message( 'fail-in-primary-continue' ) ),
2183 $tmp
2185 'Primary redirect, then abstain' => [
2186 $good, $good, $good,
2188 $tmp = AuthenticationResponse::newRedirect(
2189 [ $req ], '/foo.html', [ 'foo' => 'bar' ]
2191 AuthenticationResponse::newAbstain(),
2195 $tmp,
2196 new \DomainException(
2197 'MockPrimaryAuthenticationProvider::continuePrimaryAccountCreation() returned ABSTAIN'
2201 'Primary UI, then pass; secondary abstain' => [
2202 $good, $good, $good,
2204 $tmp1 = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
2205 AuthenticationResponse::newPass(),
2208 AuthenticationResponse::newAbstain(),
2211 $tmp1,
2212 'created' => AuthenticationResponse::newPass( '' ),
2215 'Primary pass; secondary UI then pass' => [
2216 $good, $good, $good,
2218 AuthenticationResponse::newPass( '' ),
2221 $tmp1 = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
2222 AuthenticationResponse::newPass( '' ),
2225 'created' => $tmp1,
2226 AuthenticationResponse::newPass( '' ),
2229 'Primary pass; secondary fail' => [
2230 $good, $good, $good,
2232 AuthenticationResponse::newPass(),
2235 AuthenticationResponse::newFail( $this->message( '...' ) ),
2238 'created' => new \DomainException(
2239 'MockSecondaryAuthenticationProvider::beginSecondaryAccountCreation() returned FAIL. ' .
2240 'Secondary providers are not allowed to fail account creation, ' .
2241 'that should have been done via testForAccountCreation().'
2249 * @dataProvider provideAccountCreationLogging
2250 * @param bool $isAnon
2251 * @param string|null $logSubtype
2253 public function testAccountCreationLogging( $isAnon, $logSubtype ) {
2254 $creator = $isAnon ? new \User : \User::newFromName( 'UTSysop' );
2255 $username = self::usernameForCreation();
2257 $this->initializeManager();
2259 // Set up lots of mocks...
2260 $mock = $this->getMockForAbstractClass(
2261 "MediaWiki\\Auth\\PrimaryAuthenticationProvider", []
2263 $mock->expects( $this->any() )->method( 'getUniqueId' )
2264 ->will( $this->returnValue( 'primary' ) );
2265 $mock->expects( $this->any() )->method( 'testUserForCreation' )
2266 ->will( $this->returnValue( StatusValue::newGood() ) );
2267 $mock->expects( $this->any() )->method( 'testForAccountCreation' )
2268 ->will( $this->returnValue( StatusValue::newGood() ) );
2269 $mock->expects( $this->any() )->method( 'accountCreationType' )
2270 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
2271 $mock->expects( $this->any() )->method( 'testUserExists' )
2272 ->will( $this->returnValue( false ) );
2273 $mock->expects( $this->any() )->method( 'beginPrimaryAccountCreation' )
2274 ->will( $this->returnValue( AuthenticationResponse::newPass( $username ) ) );
2275 $mock->expects( $this->any() )->method( 'finishAccountCreation' )
2276 ->will( $this->returnValue( $logSubtype ) );
2278 $this->primaryauthMocks = [ $mock ];
2279 $this->initializeManager( true );
2280 $this->logger->setCollect( true );
2282 $this->config->set( 'NewUserLog', true );
2284 $dbw = wfGetDB( DB_MASTER );
2285 $maxLogId = $dbw->selectField( 'logging', 'MAX(log_id)', [ 'log_type' => 'newusers' ] );
2287 $userReq = new UsernameAuthenticationRequest;
2288 $userReq->username = $username;
2289 $reasonReq = new CreationReasonAuthenticationRequest;
2290 $reasonReq->reason = $this->toString();
2291 $ret = $this->manager->beginAccountCreation(
2292 $creator, [ $userReq, $reasonReq ], 'http://localhost/'
2295 $this->assertSame( AuthenticationResponse::PASS, $ret->status );
2297 $user = \User::newFromName( $username );
2298 $this->assertNotEquals( 0, $user->getId(), 'sanity check' );
2299 $this->assertNotEquals( $creator->getId(), $user->getId(), 'sanity check' );
2301 $data = \DatabaseLogEntry::getSelectQueryData();
2302 $rows = iterator_to_array( $dbw->select(
2303 $data['tables'],
2304 $data['fields'],
2306 'log_id > ' . (int)$maxLogId,
2307 'log_type' => 'newusers'
2308 ] + $data['conds'],
2309 __METHOD__,
2310 $data['options'],
2311 $data['join_conds']
2312 ) );
2313 $this->assertCount( 1, $rows );
2314 $entry = \DatabaseLogEntry::newFromRow( reset( $rows ) );
2316 $this->assertSame( $logSubtype ?: ( $isAnon ? 'create' : 'create2' ), $entry->getSubtype() );
2317 $this->assertSame(
2318 $isAnon ? $user->getId() : $creator->getId(),
2319 $entry->getPerformer()->getId()
2321 $this->assertSame(
2322 $isAnon ? $user->getName() : $creator->getName(),
2323 $entry->getPerformer()->getName()
2325 $this->assertSame( $user->getUserPage()->getFullText(), $entry->getTarget()->getFullText() );
2326 $this->assertSame( [ '4::userid' => $user->getId() ], $entry->getParameters() );
2327 $this->assertSame( $this->toString(), $entry->getComment() );
2330 public static function provideAccountCreationLogging() {
2331 return [
2332 [ true, null ],
2333 [ true, 'foobar' ],
2334 [ false, null ],
2335 [ false, 'byemail' ],
2339 public function testAutoAccountCreation() {
2340 global $wgGroupPermissions, $wgHooks;
2342 // PHPUnit seems to have a bug where it will call the ->with()
2343 // callbacks for our hooks again after the test is run (WTF?), which
2344 // breaks here because $username no longer matches $user by the end of
2345 // the testing.
2346 $workaroundPHPUnitBug = false;
2348 $username = self::usernameForCreation();
2349 $this->initializeManager();
2351 $this->stashMwGlobals( [ 'wgGroupPermissions' ] );
2352 $wgGroupPermissions['*']['createaccount'] = true;
2353 $wgGroupPermissions['*']['autocreateaccount'] = false;
2355 \ObjectCache::$instances[__METHOD__] = new \HashBagOStuff();
2356 $this->setMwGlobals( [ 'wgMainCacheType' => __METHOD__ ] );
2358 // Set up lots of mocks...
2359 $mocks = [];
2360 foreach ( [ 'pre', 'primary', 'secondary' ] as $key ) {
2361 $class = ucfirst( $key ) . 'AuthenticationProvider';
2362 $mocks[$key] = $this->getMockForAbstractClass(
2363 "MediaWiki\\Auth\\$class", [], "Mock$class"
2365 $mocks[$key]->expects( $this->any() )->method( 'getUniqueId' )
2366 ->will( $this->returnValue( $key ) );
2369 $good = StatusValue::newGood();
2370 $callback = $this->callback( function ( $user ) use ( &$username, &$workaroundPHPUnitBug ) {
2371 return $workaroundPHPUnitBug || $user->getName() === $username;
2372 } );
2374 $mocks['pre']->expects( $this->exactly( 12 ) )->method( 'testUserForCreation' )
2375 ->with( $callback, $this->identicalTo( AuthManager::AUTOCREATE_SOURCE_SESSION ) )
2376 ->will( $this->onConsecutiveCalls(
2377 StatusValue::newFatal( 'ok' ), StatusValue::newFatal( 'ok' ), // For testing permissions
2378 StatusValue::newFatal( 'fail-in-pre' ), $good, $good,
2379 $good, // backoff test
2380 $good, // addToDatabase fails test
2381 $good, // addToDatabase throws test
2382 $good, // addToDatabase exists test
2383 $good, $good, $good // success
2384 ) );
2386 $mocks['primary']->expects( $this->any() )->method( 'accountCreationType' )
2387 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
2388 $mocks['primary']->expects( $this->any() )->method( 'testUserExists' )
2389 ->will( $this->returnValue( true ) );
2390 $mocks['primary']->expects( $this->exactly( 9 ) )->method( 'testUserForCreation' )
2391 ->with( $callback, $this->identicalTo( AuthManager::AUTOCREATE_SOURCE_SESSION ) )
2392 ->will( $this->onConsecutiveCalls(
2393 StatusValue::newFatal( 'fail-in-primary' ), $good,
2394 $good, // backoff test
2395 $good, // addToDatabase fails test
2396 $good, // addToDatabase throws test
2397 $good, // addToDatabase exists test
2398 $good, $good, $good
2399 ) );
2400 $mocks['primary']->expects( $this->exactly( 3 ) )->method( 'autoCreatedAccount' )
2401 ->with( $callback, $this->identicalTo( AuthManager::AUTOCREATE_SOURCE_SESSION ) );
2403 $mocks['secondary']->expects( $this->exactly( 8 ) )->method( 'testUserForCreation' )
2404 ->with( $callback, $this->identicalTo( AuthManager::AUTOCREATE_SOURCE_SESSION ) )
2405 ->will( $this->onConsecutiveCalls(
2406 StatusValue::newFatal( 'fail-in-secondary' ),
2407 $good, // backoff test
2408 $good, // addToDatabase fails test
2409 $good, // addToDatabase throws test
2410 $good, // addToDatabase exists test
2411 $good, $good, $good
2412 ) );
2413 $mocks['secondary']->expects( $this->exactly( 3 ) )->method( 'autoCreatedAccount' )
2414 ->with( $callback, $this->identicalTo( AuthManager::AUTOCREATE_SOURCE_SESSION ) );
2416 $this->preauthMocks = [ $mocks['pre'] ];
2417 $this->primaryauthMocks = [ $mocks['primary'] ];
2418 $this->secondaryauthMocks = [ $mocks['secondary'] ];
2419 $this->initializeManager( true );
2420 $session = $this->request->getSession();
2422 $logger = new \TestLogger( true, function ( $m ) {
2423 $m = str_replace( 'MediaWiki\\Auth\\AuthManager::autoCreateUser: ', '', $m );
2424 return $m;
2425 } );
2426 $this->manager->setLogger( $logger );
2428 try {
2429 $user = \User::newFromName( 'UTSysop' );
2430 $this->manager->autoCreateUser( $user, 'InvalidSource', true );
2431 $this->fail( 'Expected exception not thrown' );
2432 } catch ( \InvalidArgumentException $ex ) {
2433 $this->assertSame( 'Unknown auto-creation source: InvalidSource', $ex->getMessage() );
2436 // First, check an existing user
2437 $session->clear();
2438 $user = \User::newFromName( 'UTSysop' );
2439 $this->hook( 'LocalUserCreated', $this->never() );
2440 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2441 $this->unhook( 'LocalUserCreated' );
2442 $expect = \Status::newGood();
2443 $expect->warning( 'userexists' );
2444 $this->assertEquals( $expect, $ret );
2445 $this->assertNotEquals( 0, $user->getId() );
2446 $this->assertSame( 'UTSysop', $user->getName() );
2447 $this->assertEquals( $user->getId(), $session->getUser()->getId() );
2448 $this->assertSame( [
2449 [ LogLevel::DEBUG, '{username} already exists locally' ],
2450 ], $logger->getBuffer() );
2451 $logger->clearBuffer();
2453 $session->clear();
2454 $user = \User::newFromName( 'UTSysop' );
2455 $this->hook( 'LocalUserCreated', $this->never() );
2456 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, false );
2457 $this->unhook( 'LocalUserCreated' );
2458 $expect = \Status::newGood();
2459 $expect->warning( 'userexists' );
2460 $this->assertEquals( $expect, $ret );
2461 $this->assertNotEquals( 0, $user->getId() );
2462 $this->assertSame( 'UTSysop', $user->getName() );
2463 $this->assertEquals( 0, $session->getUser()->getId() );
2464 $this->assertSame( [
2465 [ LogLevel::DEBUG, '{username} already exists locally' ],
2466 ], $logger->getBuffer() );
2467 $logger->clearBuffer();
2469 // Wiki is read-only
2470 $session->clear();
2471 $this->setMwGlobals( [ 'wgReadOnly' => 'Because' ] );
2472 $user = \User::newFromName( $username );
2473 $this->hook( 'LocalUserCreated', $this->never() );
2474 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2475 $this->unhook( 'LocalUserCreated' );
2476 $this->assertEquals( \Status::newFatal( 'readonlytext', 'Because' ), $ret );
2477 $this->assertEquals( 0, $user->getId() );
2478 $this->assertNotEquals( $username, $user->getName() );
2479 $this->assertEquals( 0, $session->getUser()->getId() );
2480 $this->assertSame( [
2481 [ LogLevel::DEBUG, 'denied by wfReadOnly(): {reason}' ],
2482 ], $logger->getBuffer() );
2483 $logger->clearBuffer();
2484 $this->setMwGlobals( [ 'wgReadOnly' => false ] );
2486 // Session blacklisted
2487 $session->clear();
2488 $session->set( 'AuthManager::AutoCreateBlacklist', 'test' );
2489 $user = \User::newFromName( $username );
2490 $this->hook( 'LocalUserCreated', $this->never() );
2491 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2492 $this->unhook( 'LocalUserCreated' );
2493 $this->assertEquals( \Status::newFatal( 'test' ), $ret );
2494 $this->assertEquals( 0, $user->getId() );
2495 $this->assertNotEquals( $username, $user->getName() );
2496 $this->assertEquals( 0, $session->getUser()->getId() );
2497 $this->assertSame( [
2498 [ LogLevel::DEBUG, 'blacklisted in session {sessionid}' ],
2499 ], $logger->getBuffer() );
2500 $logger->clearBuffer();
2502 $session->clear();
2503 $session->set( 'AuthManager::AutoCreateBlacklist', StatusValue::newFatal( 'test2' ) );
2504 $user = \User::newFromName( $username );
2505 $this->hook( 'LocalUserCreated', $this->never() );
2506 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2507 $this->unhook( 'LocalUserCreated' );
2508 $this->assertEquals( \Status::newFatal( 'test2' ), $ret );
2509 $this->assertEquals( 0, $user->getId() );
2510 $this->assertNotEquals( $username, $user->getName() );
2511 $this->assertEquals( 0, $session->getUser()->getId() );
2512 $this->assertSame( [
2513 [ LogLevel::DEBUG, 'blacklisted in session {sessionid}' ],
2514 ], $logger->getBuffer() );
2515 $logger->clearBuffer();
2517 // Uncreatable name
2518 $session->clear();
2519 $user = \User::newFromName( $username . '@' );
2520 $this->hook( 'LocalUserCreated', $this->never() );
2521 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2522 $this->unhook( 'LocalUserCreated' );
2523 $this->assertEquals( \Status::newFatal( 'noname' ), $ret );
2524 $this->assertEquals( 0, $user->getId() );
2525 $this->assertNotEquals( $username . '@', $user->getId() );
2526 $this->assertEquals( 0, $session->getUser()->getId() );
2527 $this->assertSame( [
2528 [ LogLevel::DEBUG, 'name "{username}" is not creatable' ],
2529 ], $logger->getBuffer() );
2530 $logger->clearBuffer();
2531 $this->assertSame( 'noname', $session->get( 'AuthManager::AutoCreateBlacklist' ) );
2533 // IP unable to create accounts
2534 $wgGroupPermissions['*']['createaccount'] = false;
2535 $wgGroupPermissions['*']['autocreateaccount'] = false;
2536 $session->clear();
2537 $user = \User::newFromName( $username );
2538 $this->hook( 'LocalUserCreated', $this->never() );
2539 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2540 $this->unhook( 'LocalUserCreated' );
2541 $this->assertEquals( \Status::newFatal( 'authmanager-autocreate-noperm' ), $ret );
2542 $this->assertEquals( 0, $user->getId() );
2543 $this->assertNotEquals( $username, $user->getName() );
2544 $this->assertEquals( 0, $session->getUser()->getId() );
2545 $this->assertSame( [
2546 [ LogLevel::DEBUG, 'IP lacks the ability to create or autocreate accounts' ],
2547 ], $logger->getBuffer() );
2548 $logger->clearBuffer();
2549 $this->assertSame(
2550 'authmanager-autocreate-noperm', $session->get( 'AuthManager::AutoCreateBlacklist' )
2553 // Test that both permutations of permissions are allowed
2554 // (this hits the two "ok" entries in $mocks['pre'])
2555 $wgGroupPermissions['*']['createaccount'] = false;
2556 $wgGroupPermissions['*']['autocreateaccount'] = true;
2557 $session->clear();
2558 $user = \User::newFromName( $username );
2559 $this->hook( 'LocalUserCreated', $this->never() );
2560 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2561 $this->unhook( 'LocalUserCreated' );
2562 $this->assertEquals( \Status::newFatal( 'ok' ), $ret );
2564 $wgGroupPermissions['*']['createaccount'] = true;
2565 $wgGroupPermissions['*']['autocreateaccount'] = false;
2566 $session->clear();
2567 $user = \User::newFromName( $username );
2568 $this->hook( 'LocalUserCreated', $this->never() );
2569 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2570 $this->unhook( 'LocalUserCreated' );
2571 $this->assertEquals( \Status::newFatal( 'ok' ), $ret );
2572 $logger->clearBuffer();
2574 // Test lock fail
2575 $session->clear();
2576 $user = \User::newFromName( $username );
2577 $this->hook( 'LocalUserCreated', $this->never() );
2578 $cache = \ObjectCache::getLocalClusterInstance();
2579 $lock = $cache->getScopedLock( $cache->makeGlobalKey( 'account', md5( $username ) ) );
2580 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2581 unset( $lock );
2582 $this->unhook( 'LocalUserCreated' );
2583 $this->assertEquals( \Status::newFatal( 'usernameinprogress' ), $ret );
2584 $this->assertEquals( 0, $user->getId() );
2585 $this->assertNotEquals( $username, $user->getName() );
2586 $this->assertEquals( 0, $session->getUser()->getId() );
2587 $this->assertSame( [
2588 [ LogLevel::DEBUG, 'Could not acquire account creation lock' ],
2589 ], $logger->getBuffer() );
2590 $logger->clearBuffer();
2592 // Test pre-authentication provider fail
2593 $session->clear();
2594 $user = \User::newFromName( $username );
2595 $this->hook( 'LocalUserCreated', $this->never() );
2596 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2597 $this->unhook( 'LocalUserCreated' );
2598 $this->assertEquals( \Status::newFatal( 'fail-in-pre' ), $ret );
2599 $this->assertEquals( 0, $user->getId() );
2600 $this->assertNotEquals( $username, $user->getName() );
2601 $this->assertEquals( 0, $session->getUser()->getId() );
2602 $this->assertSame( [
2603 [ LogLevel::DEBUG, 'Provider denied creation of {username}: {reason}' ],
2604 ], $logger->getBuffer() );
2605 $logger->clearBuffer();
2606 $this->assertEquals(
2607 StatusValue::newFatal( 'fail-in-pre' ), $session->get( 'AuthManager::AutoCreateBlacklist' )
2610 $session->clear();
2611 $user = \User::newFromName( $username );
2612 $this->hook( 'LocalUserCreated', $this->never() );
2613 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2614 $this->unhook( 'LocalUserCreated' );
2615 $this->assertEquals( \Status::newFatal( 'fail-in-primary' ), $ret );
2616 $this->assertEquals( 0, $user->getId() );
2617 $this->assertNotEquals( $username, $user->getName() );
2618 $this->assertEquals( 0, $session->getUser()->getId() );
2619 $this->assertSame( [
2620 [ LogLevel::DEBUG, 'Provider denied creation of {username}: {reason}' ],
2621 ], $logger->getBuffer() );
2622 $logger->clearBuffer();
2623 $this->assertEquals(
2624 StatusValue::newFatal( 'fail-in-primary' ), $session->get( 'AuthManager::AutoCreateBlacklist' )
2627 $session->clear();
2628 $user = \User::newFromName( $username );
2629 $this->hook( 'LocalUserCreated', $this->never() );
2630 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2631 $this->unhook( 'LocalUserCreated' );
2632 $this->assertEquals( \Status::newFatal( 'fail-in-secondary' ), $ret );
2633 $this->assertEquals( 0, $user->getId() );
2634 $this->assertNotEquals( $username, $user->getName() );
2635 $this->assertEquals( 0, $session->getUser()->getId() );
2636 $this->assertSame( [
2637 [ LogLevel::DEBUG, 'Provider denied creation of {username}: {reason}' ],
2638 ], $logger->getBuffer() );
2639 $logger->clearBuffer();
2640 $this->assertEquals(
2641 StatusValue::newFatal( 'fail-in-secondary' ), $session->get( 'AuthManager::AutoCreateBlacklist' )
2644 // Test backoff
2645 $cache = \ObjectCache::getLocalClusterInstance();
2646 $backoffKey = wfMemcKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
2647 $cache->set( $backoffKey, true );
2648 $session->clear();
2649 $user = \User::newFromName( $username );
2650 $this->hook( 'LocalUserCreated', $this->never() );
2651 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2652 $this->unhook( 'LocalUserCreated' );
2653 $this->assertEquals( \Status::newFatal( 'authmanager-autocreate-exception' ), $ret );
2654 $this->assertEquals( 0, $user->getId() );
2655 $this->assertNotEquals( $username, $user->getName() );
2656 $this->assertEquals( 0, $session->getUser()->getId() );
2657 $this->assertSame( [
2658 [ LogLevel::DEBUG, '{username} denied by prior creation attempt failures' ],
2659 ], $logger->getBuffer() );
2660 $logger->clearBuffer();
2661 $this->assertSame( null, $session->get( 'AuthManager::AutoCreateBlacklist' ) );
2662 $cache->delete( $backoffKey );
2664 // Test addToDatabase fails
2665 $session->clear();
2666 $user = $this->getMock( 'User', [ 'addToDatabase' ] );
2667 $user->expects( $this->once() )->method( 'addToDatabase' )
2668 ->will( $this->returnValue( \Status::newFatal( 'because' ) ) );
2669 $user->setName( $username );
2670 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2671 $this->assertEquals( \Status::newFatal( 'because' ), $ret );
2672 $this->assertEquals( 0, $user->getId() );
2673 $this->assertNotEquals( $username, $user->getName() );
2674 $this->assertEquals( 0, $session->getUser()->getId() );
2675 $this->assertSame( [
2676 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
2677 [ LogLevel::ERROR, '{username} failed with message {msg}' ],
2678 ], $logger->getBuffer() );
2679 $logger->clearBuffer();
2680 $this->assertSame( null, $session->get( 'AuthManager::AutoCreateBlacklist' ) );
2682 // Test addToDatabase throws an exception
2683 $cache = \ObjectCache::getLocalClusterInstance();
2684 $backoffKey = wfMemcKey( 'AuthManager', 'autocreate-failed', md5( $username ) );
2685 $this->assertFalse( $cache->get( $backoffKey ), 'sanity check' );
2686 $session->clear();
2687 $user = $this->getMock( 'User', [ 'addToDatabase' ] );
2688 $user->expects( $this->once() )->method( 'addToDatabase' )
2689 ->will( $this->throwException( new \Exception( 'Excepted' ) ) );
2690 $user->setName( $username );
2691 try {
2692 $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2693 $this->fail( 'Expected exception not thrown' );
2694 } catch ( \Exception $ex ) {
2695 $this->assertSame( 'Excepted', $ex->getMessage() );
2697 $this->assertEquals( 0, $user->getId() );
2698 $this->assertEquals( 0, $session->getUser()->getId() );
2699 $this->assertSame( [
2700 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
2701 [ LogLevel::ERROR, '{username} failed with exception {exception}' ],
2702 ], $logger->getBuffer() );
2703 $logger->clearBuffer();
2704 $this->assertSame( null, $session->get( 'AuthManager::AutoCreateBlacklist' ) );
2705 $this->assertNotEquals( false, $cache->get( $backoffKey ) );
2706 $cache->delete( $backoffKey );
2708 // Test addToDatabase fails because the user already exists.
2709 $session->clear();
2710 $user = $this->getMock( 'User', [ 'addToDatabase' ] );
2711 $user->expects( $this->once() )->method( 'addToDatabase' )
2712 ->will( $this->returnCallback( function () use ( $username, &$user ) {
2713 $oldUser = \User::newFromName( $username );
2714 $status = $oldUser->addToDatabase();
2715 $this->assertTrue( $status->isOK(), 'sanity check' );
2716 $user->setId( $oldUser->getId() );
2717 return \Status::newFatal( 'userexists' );
2718 } ) );
2719 $user->setName( $username );
2720 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2721 $expect = \Status::newGood();
2722 $expect->warning( 'userexists' );
2723 $this->assertEquals( $expect, $ret );
2724 $this->assertNotEquals( 0, $user->getId() );
2725 $this->assertEquals( $username, $user->getName() );
2726 $this->assertEquals( $user->getId(), $session->getUser()->getId() );
2727 $this->assertSame( [
2728 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
2729 [ LogLevel::INFO, '{username} already exists locally (race)' ],
2730 ], $logger->getBuffer() );
2731 $logger->clearBuffer();
2732 $this->assertSame( null, $session->get( 'AuthManager::AutoCreateBlacklist' ) );
2734 // Success!
2735 $session->clear();
2736 $username = self::usernameForCreation();
2737 $user = \User::newFromName( $username );
2738 $this->hook( 'AuthPluginAutoCreate', $this->once() )
2739 ->with( $callback );
2740 $this->hideDeprecated( 'AuthPluginAutoCreate hook (used in ' .
2741 get_class( $wgHooks['AuthPluginAutoCreate'][0] ) . '::onAuthPluginAutoCreate)' );
2742 $this->hook( 'LocalUserCreated', $this->once() )
2743 ->with( $callback, $this->equalTo( true ) );
2744 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, true );
2745 $this->unhook( 'LocalUserCreated' );
2746 $this->unhook( 'AuthPluginAutoCreate' );
2747 $this->assertEquals( \Status::newGood(), $ret );
2748 $this->assertNotEquals( 0, $user->getId() );
2749 $this->assertEquals( $username, $user->getName() );
2750 $this->assertEquals( $user->getId(), $session->getUser()->getId() );
2751 $this->assertSame( [
2752 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
2753 ], $logger->getBuffer() );
2754 $logger->clearBuffer();
2756 $dbw = wfGetDB( DB_MASTER );
2757 $maxLogId = $dbw->selectField( 'logging', 'MAX(log_id)', [ 'log_type' => 'newusers' ] );
2758 $session->clear();
2759 $username = self::usernameForCreation();
2760 $user = \User::newFromName( $username );
2761 $this->hook( 'LocalUserCreated', $this->once() )
2762 ->with( $callback, $this->equalTo( true ) );
2763 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, false );
2764 $this->unhook( 'LocalUserCreated' );
2765 $this->assertEquals( \Status::newGood(), $ret );
2766 $this->assertNotEquals( 0, $user->getId() );
2767 $this->assertEquals( $username, $user->getName() );
2768 $this->assertEquals( 0, $session->getUser()->getId() );
2769 $this->assertSame( [
2770 [ LogLevel::INFO, 'creating new user ({username}) - from: {from}' ],
2771 ], $logger->getBuffer() );
2772 $logger->clearBuffer();
2773 $this->assertSame(
2774 $maxLogId,
2775 $dbw->selectField( 'logging', 'MAX(log_id)', [ 'log_type' => 'newusers' ] )
2778 $this->config->set( 'NewUserLog', true );
2779 $session->clear();
2780 $username = self::usernameForCreation();
2781 $user = \User::newFromName( $username );
2782 $ret = $this->manager->autoCreateUser( $user, AuthManager::AUTOCREATE_SOURCE_SESSION, false );
2783 $this->assertEquals( \Status::newGood(), $ret );
2784 $logger->clearBuffer();
2786 $data = \DatabaseLogEntry::getSelectQueryData();
2787 $rows = iterator_to_array( $dbw->select(
2788 $data['tables'],
2789 $data['fields'],
2791 'log_id > ' . (int)$maxLogId,
2792 'log_type' => 'newusers'
2793 ] + $data['conds'],
2794 __METHOD__,
2795 $data['options'],
2796 $data['join_conds']
2797 ) );
2798 $this->assertCount( 1, $rows );
2799 $entry = \DatabaseLogEntry::newFromRow( reset( $rows ) );
2801 $this->assertSame( 'autocreate', $entry->getSubtype() );
2802 $this->assertSame( $user->getId(), $entry->getPerformer()->getId() );
2803 $this->assertSame( $user->getName(), $entry->getPerformer()->getName() );
2804 $this->assertSame( $user->getUserPage()->getFullText(), $entry->getTarget()->getFullText() );
2805 $this->assertSame( [ '4::userid' => $user->getId() ], $entry->getParameters() );
2807 $workaroundPHPUnitBug = true;
2811 * @dataProvider provideGetAuthenticationRequests
2812 * @param string $action
2813 * @param array $expect
2814 * @param array $state
2816 public function testGetAuthenticationRequests( $action, $expect, $state = [] ) {
2817 $makeReq = function ( $key ) use ( $action ) {
2818 $req = $this->getMock( AuthenticationRequest::class );
2819 $req->expects( $this->any() )->method( 'getUniqueId' )
2820 ->will( $this->returnValue( $key ) );
2821 $req->action = $action === AuthManager::ACTION_UNLINK ? AuthManager::ACTION_REMOVE : $action;
2822 $req->key = $key;
2823 return $req;
2825 $cmpReqs = function ( $a, $b ) {
2826 $ret = strcmp( get_class( $a ), get_class( $b ) );
2827 if ( !$ret ) {
2828 $ret = strcmp( $a->key, $b->key );
2830 return $ret;
2833 $good = StatusValue::newGood();
2835 $mocks = [];
2836 foreach ( [ 'pre', 'primary', 'secondary' ] as $key ) {
2837 $class = ucfirst( $key ) . 'AuthenticationProvider';
2838 $mocks[$key] = $this->getMockForAbstractClass(
2839 "MediaWiki\\Auth\\$class", [], "Mock$class"
2841 $mocks[$key]->expects( $this->any() )->method( 'getUniqueId' )
2842 ->will( $this->returnValue( $key ) );
2843 $mocks[$key]->expects( $this->any() )->method( 'getAuthenticationRequests' )
2844 ->will( $this->returnCallback( function ( $action ) use ( $key, $makeReq ) {
2845 return [ $makeReq( "$key-$action" ), $makeReq( 'generic' ) ];
2846 } ) );
2847 $mocks[$key]->expects( $this->any() )->method( 'providerAllowsAuthenticationDataChange' )
2848 ->will( $this->returnValue( $good ) );
2851 $primaries = [];
2852 foreach ( [
2853 PrimaryAuthenticationProvider::TYPE_NONE,
2854 PrimaryAuthenticationProvider::TYPE_CREATE,
2855 PrimaryAuthenticationProvider::TYPE_LINK
2856 ] as $type ) {
2857 $class = 'PrimaryAuthenticationProvider';
2858 $mocks["primary-$type"] = $this->getMockForAbstractClass(
2859 "MediaWiki\\Auth\\$class", [], "Mock$class"
2861 $mocks["primary-$type"]->expects( $this->any() )->method( 'getUniqueId' )
2862 ->will( $this->returnValue( "primary-$type" ) );
2863 $mocks["primary-$type"]->expects( $this->any() )->method( 'accountCreationType' )
2864 ->will( $this->returnValue( $type ) );
2865 $mocks["primary-$type"]->expects( $this->any() )->method( 'getAuthenticationRequests' )
2866 ->will( $this->returnCallback( function ( $action ) use ( $type, $makeReq ) {
2867 return [ $makeReq( "primary-$type-$action" ), $makeReq( 'generic' ) ];
2868 } ) );
2869 $mocks["primary-$type"]->expects( $this->any() )
2870 ->method( 'providerAllowsAuthenticationDataChange' )
2871 ->will( $this->returnValue( $good ) );
2872 $this->primaryauthMocks[] = $mocks["primary-$type"];
2875 $mocks['primary2'] = $this->getMockForAbstractClass(
2876 PrimaryAuthenticationProvider::class, [], "MockPrimaryAuthenticationProvider"
2878 $mocks['primary2']->expects( $this->any() )->method( 'getUniqueId' )
2879 ->will( $this->returnValue( 'primary2' ) );
2880 $mocks['primary2']->expects( $this->any() )->method( 'accountCreationType' )
2881 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_LINK ) );
2882 $mocks['primary2']->expects( $this->any() )->method( 'getAuthenticationRequests' )
2883 ->will( $this->returnValue( [] ) );
2884 $mocks['primary2']->expects( $this->any() )
2885 ->method( 'providerAllowsAuthenticationDataChange' )
2886 ->will( $this->returnCallback( function ( $req ) use ( $good ) {
2887 return $req->key === 'generic' ? StatusValue::newFatal( 'no' ) : $good;
2888 } ) );
2889 $this->primaryauthMocks[] = $mocks['primary2'];
2891 $this->preauthMocks = [ $mocks['pre'] ];
2892 $this->secondaryauthMocks = [ $mocks['secondary'] ];
2893 $this->initializeManager( true );
2895 if ( $state ) {
2896 if ( isset( $state['continueRequests'] ) ) {
2897 $state['continueRequests'] = array_map( $makeReq, $state['continueRequests'] );
2899 if ( $action === AuthManager::ACTION_LOGIN_CONTINUE ) {
2900 $this->request->getSession()->setSecret( 'AuthManager::authnState', $state );
2901 } elseif ( $action === AuthManager::ACTION_CREATE_CONTINUE ) {
2902 $this->request->getSession()->setSecret( 'AuthManager::accountCreationState', $state );
2903 } elseif ( $action === AuthManager::ACTION_LINK_CONTINUE ) {
2904 $this->request->getSession()->setSecret( 'AuthManager::accountLinkState', $state );
2908 $expectReqs = array_map( $makeReq, $expect );
2909 if ( $action === AuthManager::ACTION_LOGIN ) {
2910 $req = new RememberMeAuthenticationRequest;
2911 $req->action = $action;
2912 $req->required = AuthenticationRequest::REQUIRED;
2913 $expectReqs[] = $req;
2914 } elseif ( $action === AuthManager::ACTION_CREATE ) {
2915 $req = new UsernameAuthenticationRequest;
2916 $req->action = $action;
2917 $expectReqs[] = $req;
2918 $req = new UserDataAuthenticationRequest;
2919 $req->action = $action;
2920 $req->required = AuthenticationRequest::REQUIRED;
2921 $expectReqs[] = $req;
2923 usort( $expectReqs, $cmpReqs );
2925 $actual = $this->manager->getAuthenticationRequests( $action );
2926 foreach ( $actual as $req ) {
2927 // Don't test this here.
2928 $req->required = AuthenticationRequest::REQUIRED;
2930 usort( $actual, $cmpReqs );
2932 $this->assertEquals( $expectReqs, $actual );
2934 // Test CreationReasonAuthenticationRequest gets returned
2935 if ( $action === AuthManager::ACTION_CREATE ) {
2936 $req = new CreationReasonAuthenticationRequest;
2937 $req->action = $action;
2938 $req->required = AuthenticationRequest::REQUIRED;
2939 $expectReqs[] = $req;
2940 usort( $expectReqs, $cmpReqs );
2942 $actual = $this->manager->getAuthenticationRequests( $action, \User::newFromName( 'UTSysop' ) );
2943 foreach ( $actual as $req ) {
2944 // Don't test this here.
2945 $req->required = AuthenticationRequest::REQUIRED;
2947 usort( $actual, $cmpReqs );
2949 $this->assertEquals( $expectReqs, $actual );
2953 public static function provideGetAuthenticationRequests() {
2954 return [
2956 AuthManager::ACTION_LOGIN,
2957 [ 'pre-login', 'primary-none-login', 'primary-create-login',
2958 'primary-link-login', 'secondary-login', 'generic' ],
2961 AuthManager::ACTION_CREATE,
2962 [ 'pre-create', 'primary-none-create', 'primary-create-create',
2963 'primary-link-create', 'secondary-create', 'generic' ],
2966 AuthManager::ACTION_LINK,
2967 [ 'primary-link-link', 'generic' ],
2970 AuthManager::ACTION_CHANGE,
2971 [ 'primary-none-change', 'primary-create-change', 'primary-link-change',
2972 'secondary-change' ],
2975 AuthManager::ACTION_REMOVE,
2976 [ 'primary-none-remove', 'primary-create-remove', 'primary-link-remove',
2977 'secondary-remove' ],
2980 AuthManager::ACTION_UNLINK,
2981 [ 'primary-link-remove' ],
2984 AuthManager::ACTION_LOGIN_CONTINUE,
2988 AuthManager::ACTION_LOGIN_CONTINUE,
2989 $reqs = [ 'continue-login', 'foo', 'bar' ],
2991 'continueRequests' => $reqs,
2995 AuthManager::ACTION_CREATE_CONTINUE,
2999 AuthManager::ACTION_CREATE_CONTINUE,
3000 $reqs = [ 'continue-create', 'foo', 'bar' ],
3002 'continueRequests' => $reqs,
3006 AuthManager::ACTION_LINK_CONTINUE,
3010 AuthManager::ACTION_LINK_CONTINUE,
3011 $reqs = [ 'continue-link', 'foo', 'bar' ],
3013 'continueRequests' => $reqs,
3019 public function testGetAuthenticationRequestsRequired() {
3020 $makeReq = function ( $key, $required ) {
3021 $req = $this->getMock( AuthenticationRequest::class );
3022 $req->expects( $this->any() )->method( 'getUniqueId' )
3023 ->will( $this->returnValue( $key ) );
3024 $req->action = AuthManager::ACTION_LOGIN;
3025 $req->key = $key;
3026 $req->required = $required;
3027 return $req;
3029 $cmpReqs = function ( $a, $b ) {
3030 $ret = strcmp( get_class( $a ), get_class( $b ) );
3031 if ( !$ret ) {
3032 $ret = strcmp( $a->key, $b->key );
3034 return $ret;
3037 $good = StatusValue::newGood();
3039 $primary1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3040 $primary1->expects( $this->any() )->method( 'getUniqueId' )
3041 ->will( $this->returnValue( 'primary1' ) );
3042 $primary1->expects( $this->any() )->method( 'accountCreationType' )
3043 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
3044 $primary1->expects( $this->any() )->method( 'getAuthenticationRequests' )
3045 ->will( $this->returnCallback( function ( $action ) use ( $makeReq ) {
3046 return [
3047 $makeReq( "primary-shared", AuthenticationRequest::REQUIRED ),
3048 $makeReq( "required", AuthenticationRequest::REQUIRED ),
3049 $makeReq( "optional", AuthenticationRequest::OPTIONAL ),
3050 $makeReq( "foo", AuthenticationRequest::REQUIRED ),
3051 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3052 $makeReq( "baz", AuthenticationRequest::OPTIONAL ),
3054 } ) );
3056 $primary2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3057 $primary2->expects( $this->any() )->method( 'getUniqueId' )
3058 ->will( $this->returnValue( 'primary2' ) );
3059 $primary2->expects( $this->any() )->method( 'accountCreationType' )
3060 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
3061 $primary2->expects( $this->any() )->method( 'getAuthenticationRequests' )
3062 ->will( $this->returnCallback( function ( $action ) use ( $makeReq ) {
3063 return [
3064 $makeReq( "primary-shared", AuthenticationRequest::REQUIRED ),
3065 $makeReq( "required2", AuthenticationRequest::REQUIRED ),
3066 $makeReq( "optional2", AuthenticationRequest::OPTIONAL ),
3068 } ) );
3070 $secondary = $this->getMockForAbstractClass( SecondaryAuthenticationProvider::class );
3071 $secondary->expects( $this->any() )->method( 'getUniqueId' )
3072 ->will( $this->returnValue( 'secondary' ) );
3073 $secondary->expects( $this->any() )->method( 'getAuthenticationRequests' )
3074 ->will( $this->returnCallback( function ( $action ) use ( $makeReq ) {
3075 return [
3076 $makeReq( "foo", AuthenticationRequest::OPTIONAL ),
3077 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3078 $makeReq( "baz", AuthenticationRequest::REQUIRED ),
3080 } ) );
3082 $rememberReq = new RememberMeAuthenticationRequest;
3083 $rememberReq->action = AuthManager::ACTION_LOGIN;
3085 $this->primaryauthMocks = [ $primary1, $primary2 ];
3086 $this->secondaryauthMocks = [ $secondary ];
3087 $this->initializeManager( true );
3089 $actual = $this->manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN );
3090 $expected = [
3091 $rememberReq,
3092 $makeReq( "primary-shared", AuthenticationRequest::PRIMARY_REQUIRED ),
3093 $makeReq( "required", AuthenticationRequest::PRIMARY_REQUIRED ),
3094 $makeReq( "required2", AuthenticationRequest::PRIMARY_REQUIRED ),
3095 $makeReq( "optional", AuthenticationRequest::OPTIONAL ),
3096 $makeReq( "optional2", AuthenticationRequest::OPTIONAL ),
3097 $makeReq( "foo", AuthenticationRequest::PRIMARY_REQUIRED ),
3098 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3099 $makeReq( "baz", AuthenticationRequest::REQUIRED ),
3101 usort( $actual, $cmpReqs );
3102 usort( $expected, $cmpReqs );
3103 $this->assertEquals( $expected, $actual );
3105 $this->primaryauthMocks = [ $primary1 ];
3106 $this->secondaryauthMocks = [ $secondary ];
3107 $this->initializeManager( true );
3109 $actual = $this->manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN );
3110 $expected = [
3111 $rememberReq,
3112 $makeReq( "primary-shared", AuthenticationRequest::PRIMARY_REQUIRED ),
3113 $makeReq( "required", AuthenticationRequest::PRIMARY_REQUIRED ),
3114 $makeReq( "optional", AuthenticationRequest::OPTIONAL ),
3115 $makeReq( "foo", AuthenticationRequest::PRIMARY_REQUIRED ),
3116 $makeReq( "bar", AuthenticationRequest::REQUIRED ),
3117 $makeReq( "baz", AuthenticationRequest::REQUIRED ),
3119 usort( $actual, $cmpReqs );
3120 usort( $expected, $cmpReqs );
3121 $this->assertEquals( $expected, $actual );
3124 public function testAllowsPropertyChange() {
3125 $mocks = [];
3126 foreach ( [ 'primary', 'secondary' ] as $key ) {
3127 $class = ucfirst( $key ) . 'AuthenticationProvider';
3128 $mocks[$key] = $this->getMockForAbstractClass(
3129 "MediaWiki\\Auth\\$class", [], "Mock$class"
3131 $mocks[$key]->expects( $this->any() )->method( 'getUniqueId' )
3132 ->will( $this->returnValue( $key ) );
3133 $mocks[$key]->expects( $this->any() )->method( 'providerAllowsPropertyChange' )
3134 ->will( $this->returnCallback( function ( $prop ) use ( $key ) {
3135 return $prop !== $key;
3136 } ) );
3139 $this->primaryauthMocks = [ $mocks['primary'] ];
3140 $this->secondaryauthMocks = [ $mocks['secondary'] ];
3141 $this->initializeManager( true );
3143 $this->assertTrue( $this->manager->allowsPropertyChange( 'foo' ) );
3144 $this->assertFalse( $this->manager->allowsPropertyChange( 'primary' ) );
3145 $this->assertFalse( $this->manager->allowsPropertyChange( 'secondary' ) );
3148 public function testAutoCreateOnLogin() {
3149 $username = self::usernameForCreation();
3151 $req = $this->getMock( AuthenticationRequest::class );
3153 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3154 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'primary' ) );
3155 $mock->expects( $this->any() )->method( 'beginPrimaryAuthentication' )
3156 ->will( $this->returnValue( AuthenticationResponse::newPass( $username ) ) );
3157 $mock->expects( $this->any() )->method( 'accountCreationType' )
3158 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
3159 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( true ) );
3160 $mock->expects( $this->any() )->method( 'testUserForCreation' )
3161 ->will( $this->returnValue( StatusValue::newGood() ) );
3163 $mock2 = $this->getMockForAbstractClass( SecondaryAuthenticationProvider::class );
3164 $mock2->expects( $this->any() )->method( 'getUniqueId' )
3165 ->will( $this->returnValue( 'secondary' ) );
3166 $mock2->expects( $this->any() )->method( 'beginSecondaryAuthentication' )->will(
3167 $this->returnValue(
3168 AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) )
3171 $mock2->expects( $this->any() )->method( 'continueSecondaryAuthentication' )
3172 ->will( $this->returnValue( AuthenticationResponse::newAbstain() ) );
3173 $mock2->expects( $this->any() )->method( 'testUserForCreation' )
3174 ->will( $this->returnValue( StatusValue::newGood() ) );
3176 $this->primaryauthMocks = [ $mock ];
3177 $this->secondaryauthMocks = [ $mock2 ];
3178 $this->initializeManager( true );
3179 $this->manager->setLogger( new \Psr\Log\NullLogger() );
3180 $session = $this->request->getSession();
3181 $session->clear();
3183 $this->assertSame( 0, \User::newFromName( $username )->getId(),
3184 'sanity check' );
3186 $callback = $this->callback( function ( $user ) use ( $username ) {
3187 return $user->getName() === $username;
3188 } );
3190 $this->hook( 'UserLoggedIn', $this->never() );
3191 $this->hook( 'LocalUserCreated', $this->once() )->with( $callback, $this->equalTo( true ) );
3192 $ret = $this->manager->beginAuthentication( [], 'http://localhost/' );
3193 $this->unhook( 'LocalUserCreated' );
3194 $this->unhook( 'UserLoggedIn' );
3195 $this->assertSame( AuthenticationResponse::UI, $ret->status );
3197 $id = (int)\User::newFromName( $username )->getId();
3198 $this->assertNotSame( 0, \User::newFromName( $username )->getId() );
3199 $this->assertSame( 0, $session->getUser()->getId() );
3201 $this->hook( 'UserLoggedIn', $this->once() )->with( $callback );
3202 $this->hook( 'LocalUserCreated', $this->never() );
3203 $ret = $this->manager->continueAuthentication( [] );
3204 $this->unhook( 'LocalUserCreated' );
3205 $this->unhook( 'UserLoggedIn' );
3206 $this->assertSame( AuthenticationResponse::PASS, $ret->status );
3207 $this->assertSame( $username, $ret->username );
3208 $this->assertSame( $id, $session->getUser()->getId() );
3211 public function testAutoCreateFailOnLogin() {
3212 $username = self::usernameForCreation();
3214 $mock = $this->getMockForAbstractClass(
3215 PrimaryAuthenticationProvider::class, [], "MockPrimaryAuthenticationProvider" );
3216 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'primary' ) );
3217 $mock->expects( $this->any() )->method( 'beginPrimaryAuthentication' )
3218 ->will( $this->returnValue( AuthenticationResponse::newPass( $username ) ) );
3219 $mock->expects( $this->any() )->method( 'accountCreationType' )
3220 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
3221 $mock->expects( $this->any() )->method( 'testUserExists' )->will( $this->returnValue( true ) );
3222 $mock->expects( $this->any() )->method( 'testUserForCreation' )
3223 ->will( $this->returnValue( StatusValue::newFatal( 'fail-from-primary' ) ) );
3225 $this->primaryauthMocks = [ $mock ];
3226 $this->initializeManager( true );
3227 $this->manager->setLogger( new \Psr\Log\NullLogger() );
3228 $session = $this->request->getSession();
3229 $session->clear();
3231 $this->assertSame( 0, $session->getUser()->getId(),
3232 'sanity check' );
3233 $this->assertSame( 0, \User::newFromName( $username )->getId(),
3234 'sanity check' );
3236 $this->hook( 'UserLoggedIn', $this->never() );
3237 $this->hook( 'LocalUserCreated', $this->never() );
3238 $ret = $this->manager->beginAuthentication( [], 'http://localhost/' );
3239 $this->unhook( 'LocalUserCreated' );
3240 $this->unhook( 'UserLoggedIn' );
3241 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3242 $this->assertSame( 'authmanager-authn-autocreate-failed', $ret->message->getKey() );
3244 $this->assertSame( 0, \User::newFromName( $username )->getId() );
3245 $this->assertSame( 0, $session->getUser()->getId() );
3248 public function testAuthenticationSessionData() {
3249 $this->initializeManager( true );
3251 $this->assertNull( $this->manager->getAuthenticationSessionData( 'foo' ) );
3252 $this->manager->setAuthenticationSessionData( 'foo', 'foo!' );
3253 $this->manager->setAuthenticationSessionData( 'bar', 'bar!' );
3254 $this->assertSame( 'foo!', $this->manager->getAuthenticationSessionData( 'foo' ) );
3255 $this->assertSame( 'bar!', $this->manager->getAuthenticationSessionData( 'bar' ) );
3256 $this->manager->removeAuthenticationSessionData( 'foo' );
3257 $this->assertNull( $this->manager->getAuthenticationSessionData( 'foo' ) );
3258 $this->assertSame( 'bar!', $this->manager->getAuthenticationSessionData( 'bar' ) );
3259 $this->manager->removeAuthenticationSessionData( 'bar' );
3260 $this->assertNull( $this->manager->getAuthenticationSessionData( 'bar' ) );
3262 $this->manager->setAuthenticationSessionData( 'foo', 'foo!' );
3263 $this->manager->setAuthenticationSessionData( 'bar', 'bar!' );
3264 $this->manager->removeAuthenticationSessionData( null );
3265 $this->assertNull( $this->manager->getAuthenticationSessionData( 'foo' ) );
3266 $this->assertNull( $this->manager->getAuthenticationSessionData( 'bar' ) );
3269 public function testCanLinkAccounts() {
3270 $types = [
3271 PrimaryAuthenticationProvider::TYPE_CREATE => true,
3272 PrimaryAuthenticationProvider::TYPE_LINK => true,
3273 PrimaryAuthenticationProvider::TYPE_NONE => false,
3276 foreach ( $types as $type => $can ) {
3277 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3278 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( $type ) );
3279 $mock->expects( $this->any() )->method( 'accountCreationType' )
3280 ->will( $this->returnValue( $type ) );
3281 $this->primaryauthMocks = [ $mock ];
3282 $this->initializeManager( true );
3283 $this->assertSame( $can, $this->manager->canCreateAccounts(), $type );
3287 public function testBeginAccountLink() {
3288 $user = \User::newFromName( 'UTSysop' );
3289 $this->initializeManager();
3291 $this->request->getSession()->setSecret( 'AuthManager::accountLinkState', 'test' );
3292 try {
3293 $this->manager->beginAccountLink( $user, [], 'http://localhost/' );
3294 $this->fail( 'Expected exception not thrown' );
3295 } catch ( \LogicException $ex ) {
3296 $this->assertEquals( 'Account linking is not possible', $ex->getMessage() );
3298 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' ) );
3300 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3301 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
3302 $mock->expects( $this->any() )->method( 'accountCreationType' )
3303 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_LINK ) );
3304 $this->primaryauthMocks = [ $mock ];
3305 $this->initializeManager( true );
3307 $ret = $this->manager->beginAccountLink( new \User, [], 'http://localhost/' );
3308 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3309 $this->assertSame( 'noname', $ret->message->getKey() );
3311 $ret = $this->manager->beginAccountLink(
3312 \User::newFromName( 'UTDoesNotExist' ), [], 'http://localhost/'
3314 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3315 $this->assertSame( 'authmanager-userdoesnotexist', $ret->message->getKey() );
3318 public function testContinueAccountLink() {
3319 $user = \User::newFromName( 'UTSysop' );
3320 $this->initializeManager();
3322 $session = [
3323 'userid' => $user->getId(),
3324 'username' => $user->getName(),
3325 'primary' => 'X',
3328 try {
3329 $this->manager->continueAccountLink( [] );
3330 $this->fail( 'Expected exception not thrown' );
3331 } catch ( \LogicException $ex ) {
3332 $this->assertEquals( 'Account linking is not possible', $ex->getMessage() );
3335 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3336 $mock->expects( $this->any() )->method( 'getUniqueId' )->will( $this->returnValue( 'X' ) );
3337 $mock->expects( $this->any() )->method( 'accountCreationType' )
3338 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_LINK ) );
3339 $mock->expects( $this->any() )->method( 'beginPrimaryAccountLink' )->will(
3340 $this->returnValue( AuthenticationResponse::newFail( $this->message( 'fail' ) ) )
3342 $this->primaryauthMocks = [ $mock ];
3343 $this->initializeManager( true );
3345 $this->request->getSession()->setSecret( 'AuthManager::accountLinkState', null );
3346 $ret = $this->manager->continueAccountLink( [] );
3347 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3348 $this->assertSame( 'authmanager-link-not-in-progress', $ret->message->getKey() );
3350 $this->request->getSession()->setSecret( 'AuthManager::accountLinkState',
3351 [ 'username' => $user->getName() . '<>' ] + $session );
3352 $ret = $this->manager->continueAccountLink( [] );
3353 $this->assertSame( AuthenticationResponse::FAIL, $ret->status );
3354 $this->assertSame( 'noname', $ret->message->getKey() );
3355 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' ) );
3357 $id = $user->getId();
3358 $this->request->getSession()->setSecret( 'AuthManager::accountLinkState',
3359 [ 'userid' => $id + 1 ] + $session );
3360 try {
3361 $ret = $this->manager->continueAccountLink( [] );
3362 $this->fail( 'Expected exception not thrown' );
3363 } catch ( \UnexpectedValueException $ex ) {
3364 $this->assertEquals(
3365 "User \"{$user->getName()}\" is valid, but ID $id != " . ( $id + 1 ) . '!',
3366 $ex->getMessage()
3369 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' ) );
3373 * @dataProvider provideAccountLink
3374 * @param StatusValue $preTest
3375 * @param array $primaryResponses
3376 * @param array $managerResponses
3378 public function testAccountLink(
3379 StatusValue $preTest, array $primaryResponses, array $managerResponses
3381 $user = \User::newFromName( 'UTSysop' );
3383 $this->initializeManager();
3385 // Set up lots of mocks...
3386 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
3387 $req->primary = $primaryResponses;
3388 $mocks = [];
3390 foreach ( [ 'pre', 'primary' ] as $key ) {
3391 $class = ucfirst( $key ) . 'AuthenticationProvider';
3392 $mocks[$key] = $this->getMockForAbstractClass(
3393 "MediaWiki\\Auth\\$class", [], "Mock$class"
3395 $mocks[$key]->expects( $this->any() )->method( 'getUniqueId' )
3396 ->will( $this->returnValue( $key ) );
3398 for ( $i = 2; $i <= 3; $i++ ) {
3399 $mocks[$key . $i] = $this->getMockForAbstractClass(
3400 "MediaWiki\\Auth\\$class", [], "Mock$class"
3402 $mocks[$key . $i]->expects( $this->any() )->method( 'getUniqueId' )
3403 ->will( $this->returnValue( $key . $i ) );
3407 $mocks['pre']->expects( $this->any() )->method( 'testForAccountLink' )
3408 ->will( $this->returnCallback(
3409 function ( $u )
3410 use ( $user, $preTest )
3412 $this->assertSame( $user->getId(), $u->getId() );
3413 $this->assertSame( $user->getName(), $u->getName() );
3414 return $preTest;
3416 ) );
3418 $mocks['pre2']->expects( $this->atMost( 1 ) )->method( 'testForAccountLink' )
3419 ->will( $this->returnValue( StatusValue::newGood() ) );
3421 $mocks['primary']->expects( $this->any() )->method( 'accountCreationType' )
3422 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_LINK ) );
3423 $ct = count( $req->primary );
3424 $callback = $this->returnCallback( function ( $u, $reqs ) use ( $user, $req ) {
3425 $this->assertSame( $user->getId(), $u->getId() );
3426 $this->assertSame( $user->getName(), $u->getName() );
3427 $foundReq = false;
3428 foreach ( $reqs as $r ) {
3429 $this->assertSame( $user->getName(), $r->username );
3430 $foundReq = $foundReq || get_class( $r ) === get_class( $req );
3432 $this->assertTrue( $foundReq, '$reqs contains $req' );
3433 return array_shift( $req->primary );
3434 } );
3435 $mocks['primary']->expects( $this->exactly( min( 1, $ct ) ) )
3436 ->method( 'beginPrimaryAccountLink' )
3437 ->will( $callback );
3438 $mocks['primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
3439 ->method( 'continuePrimaryAccountLink' )
3440 ->will( $callback );
3442 $abstain = AuthenticationResponse::newAbstain();
3443 $mocks['primary2']->expects( $this->any() )->method( 'accountCreationType' )
3444 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_LINK ) );
3445 $mocks['primary2']->expects( $this->atMost( 1 ) )->method( 'beginPrimaryAccountLink' )
3446 ->will( $this->returnValue( $abstain ) );
3447 $mocks['primary2']->expects( $this->never() )->method( 'continuePrimaryAccountLink' );
3448 $mocks['primary3']->expects( $this->any() )->method( 'accountCreationType' )
3449 ->will( $this->returnValue( PrimaryAuthenticationProvider::TYPE_CREATE ) );
3450 $mocks['primary3']->expects( $this->never() )->method( 'beginPrimaryAccountLink' );
3451 $mocks['primary3']->expects( $this->never() )->method( 'continuePrimaryAccountLink' );
3453 $this->preauthMocks = [ $mocks['pre'], $mocks['pre2'] ];
3454 $this->primaryauthMocks = [ $mocks['primary3'], $mocks['primary2'], $mocks['primary'] ];
3455 $this->logger = new \TestLogger( true, function ( $message, $level ) {
3456 return $level === LogLevel::DEBUG ? null : $message;
3457 } );
3458 $this->initializeManager( true );
3460 $constraint = \PHPUnit_Framework_Assert::logicalOr(
3461 $this->equalTo( AuthenticationResponse::PASS ),
3462 $this->equalTo( AuthenticationResponse::FAIL )
3464 $providers = array_merge( $this->preauthMocks, $this->primaryauthMocks );
3465 foreach ( $providers as $p ) {
3466 $p->postCalled = false;
3467 $p->expects( $this->atMost( 1 ) )->method( 'postAccountLink' )
3468 ->willReturnCallback( function ( $user, $response ) use ( $constraint, $p ) {
3469 $this->assertInstanceOf( 'User', $user );
3470 $this->assertSame( 'UTSysop', $user->getName() );
3471 $this->assertInstanceOf( AuthenticationResponse::class, $response );
3472 $this->assertThat( $response->status, $constraint );
3473 $p->postCalled = $response->status;
3474 } );
3477 $first = true;
3478 $created = false;
3479 $expectLog = [];
3480 foreach ( $managerResponses as $i => $response ) {
3481 if ( $response instanceof AuthenticationResponse &&
3482 $response->status === AuthenticationResponse::PASS
3484 $expectLog[] = [ LogLevel::INFO, 'Account linked to {user} by primary' ];
3487 $ex = null;
3488 try {
3489 if ( $first ) {
3490 $ret = $this->manager->beginAccountLink( $user, [ $req ], 'http://localhost/' );
3491 } else {
3492 $ret = $this->manager->continueAccountLink( [ $req ] );
3494 if ( $response instanceof \Exception ) {
3495 $this->fail( 'Expected exception not thrown', "Response $i" );
3497 } catch ( \Exception $ex ) {
3498 if ( !$response instanceof \Exception ) {
3499 throw $ex;
3501 $this->assertEquals( $response->getMessage(), $ex->getMessage(), "Response $i, exception" );
3502 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' ),
3503 "Response $i, exception, session state" );
3504 return;
3507 $this->assertSame( 'http://localhost/', $req->returnToUrl );
3509 $ret->message = $this->message( $ret->message );
3510 $this->assertEquals( $response, $ret, "Response $i, response" );
3511 if ( $response->status === AuthenticationResponse::PASS ||
3512 $response->status === AuthenticationResponse::FAIL
3514 $this->assertNull( $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' ),
3515 "Response $i, session state" );
3516 foreach ( $providers as $p ) {
3517 $this->assertSame( $response->status, $p->postCalled,
3518 "Response $i, post-auth callback called" );
3520 } else {
3521 $this->assertNotNull(
3522 $this->request->getSession()->getSecret( 'AuthManager::accountLinkState' ),
3523 "Response $i, session state"
3525 foreach ( $ret->neededRequests as $neededReq ) {
3526 $this->assertEquals( AuthManager::ACTION_LINK, $neededReq->action,
3527 "Response $i, neededRequest action" );
3529 $this->assertEquals(
3530 $ret->neededRequests,
3531 $this->manager->getAuthenticationRequests( AuthManager::ACTION_LINK_CONTINUE ),
3532 "Response $i, continuation check"
3534 foreach ( $providers as $p ) {
3535 $this->assertFalse( $p->postCalled, "Response $i, post-auth callback not called" );
3539 $first = false;
3542 $this->assertSame( $expectLog, $this->logger->getBuffer() );
3545 public function provideAccountLink() {
3546 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
3547 $good = StatusValue::newGood();
3549 return [
3550 'Pre-link test fail in pre' => [
3551 StatusValue::newFatal( 'fail-from-pre' ),
3554 AuthenticationResponse::newFail( $this->message( 'fail-from-pre' ) ),
3557 'Failure in primary' => [
3558 $good,
3559 $tmp = [
3560 AuthenticationResponse::newFail( $this->message( 'fail-from-primary' ) ),
3562 $tmp
3564 'All primary abstain' => [
3565 $good,
3567 AuthenticationResponse::newAbstain(),
3570 AuthenticationResponse::newFail( $this->message( 'authmanager-link-no-primary' ) )
3573 'Primary UI, then redirect, then fail' => [
3574 $good,
3575 $tmp = [
3576 AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
3577 AuthenticationResponse::newRedirect( [ $req ], '/foo.html', [ 'foo' => 'bar' ] ),
3578 AuthenticationResponse::newFail( $this->message( 'fail-in-primary-continue' ) ),
3580 $tmp
3582 'Primary redirect, then abstain' => [
3583 $good,
3585 $tmp = AuthenticationResponse::newRedirect(
3586 [ $req ], '/foo.html', [ 'foo' => 'bar' ]
3588 AuthenticationResponse::newAbstain(),
3591 $tmp,
3592 new \DomainException(
3593 'MockPrimaryAuthenticationProvider::continuePrimaryAccountLink() returned ABSTAIN'
3597 'Primary UI, then pass' => [
3598 $good,
3600 $tmp1 = AuthenticationResponse::newUI( [ $req ], $this->message( '...' ) ),
3601 AuthenticationResponse::newPass(),
3604 $tmp1,
3605 AuthenticationResponse::newPass( '' ),
3608 'Primary pass' => [
3609 $good,
3611 AuthenticationResponse::newPass( '' ),
3614 AuthenticationResponse::newPass( '' ),