9use Wikimedia\ScopedCallback;
46 protected function hook( $hook, $expect ) {
48 $mock = $this->getMock( __CLASS__, [
"on$hook" ] );
50 return $mock->expects( $expect )->method(
"on$hook" );
69 if ( $key ===
null ) {
74 $key = $key->getKey();
76 return new \Message( $key,
$params, \Language::factory(
'en' ) );
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 ) {
103 $this->config->set(
'AuthManagerConfig',
$config );
104 $this->config->set(
'LanguageCode',
'en' );
105 $this->config->set(
'NewUserLog',
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' ) ) {
127 $this->manager->setLogger( $this->logger );
128 $this->managerPriv = \TestingAccessWrapper::newFromObject( $this->manager );
138 if ( !$this->config ) {
139 $this->config = new \HashConfig();
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 )
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 ) {
166 $manager = new \MediaWiki\Session\SessionManager( [
167 'config' => $this->config,
168 'logger' =>
new \Psr\Log\NullLogger(),
171 \TestingAccessWrapper::newFromObject(
$manager )->getProvider( (
string)$provider );
173 $reset = \MediaWiki\Session\TestUtils::setSessionManagerSingleton(
$manager );
179 return [ $provider, $reset ];
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 );
197 \TestingAccessWrapper::newFromObject( $singleton )->config
205 $this->assertFalse( $this->manager->canAuthenticateNow() );
206 ScopedCallback::consume( $reset );
209 $this->assertTrue( $this->manager->canAuthenticateNow() );
210 ScopedCallback::consume( $reset );
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;
240 $this->assertSame( [
'Foo',
'Bar!' ], $this->manager->normalizeUsername(
'XYZ' ) );
248 $this->logger = new \Psr\Log\NullLogger();
249 $user = \User::newFromName(
'UTSysop' );
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,
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' );
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' );
283 $session->set(
'AuthManager:lastAuthId',
$user->getId() + 1 );
284 $session->set(
'AuthManager:lastAuthTimestamp', time() - 5 );
286 $this->manager->securitySensitiveOperationStatus(
'foo' );
287 $this->fail(
'Expected exception not thrown' );
288 }
catch ( \UnexpectedValueException $ex ) {
291 ?
'$wgReauthenticateTime lacks a default'
292 :
'$wgAllowSecuritySensitiveOperationIfCannotReauthenticate lacks a default',
297 if ( $mutableSession ) {
298 $this->config->set(
'ReauthenticateTime', [
305 $session->set(
'AuthManager:lastAuthId',
$user->getId() + 1 );
306 $session->set(
'AuthManager:lastAuthTimestamp', time() - 5 );
318 $session->set(
'AuthManager:lastAuthId',
$user->getId() );
319 $session->set(
'AuthManager:lastAuthTimestamp',
null );
331 $session->set(
'AuthManager:lastAuthTimestamp', time() - 5 );
337 $session->set(
'AuthManager:lastAuthTimestamp', time() - 20 );
346 $this->config->set(
'AllowSecuritySensitiveOperationIfCannotReauthenticate', [
365 ]
as $hook => $expect ) {
366 $this->
hook(
'SecuritySensitiveOperationStatus', $this->exactly( 2 ) )
370 $this->callback(
function (
$s )
use ( $session ) {
371 return $s->getId() === $session->getId();
373 $mutableSession ? $this->equalTo( 500, 1 ) : $this->equalTo( -1 )
375 ->
will( $this->returnCallback(
function ( &$v )
use ( $hook ) {
379 $session->set(
'AuthManager:lastAuthTimestamp', time() - 500 );
381 $expect, $this->manager->securitySensitiveOperationStatus(
'test' ),
"hook $hook"
384 $expect, $this->manager->securitySensitiveOperationStatus(
'test2' ),
"hook $hook"
386 $this->
unhook(
'SecuritySensitiveOperationStatus' );
389 ScopedCallback::consume( $reset );
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 ];
424 $this->assertSame( $expect, $this->manager->userCanAuthenticate(
'UTSysop' ) );
429 [
false,
false,
false ],
430 [
true,
false,
true ],
431 [
false,
true,
true ],
432 [
true,
true,
true ],
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 ];
447 $this->logger->setCollect(
true );
449 $this->manager->revokeAccessForUser(
'UTSysop' );
452 [ LogLevel::INFO,
'Revoking access for {user}' ],
453 ], $this->logger->getBuffer() );
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'] ];
476 $this->managerPriv->getAuthenticationProvider(
'primary' )
480 $this->managerPriv->getAuthenticationProvider(
'secondary' )
484 $this->managerPriv->getAuthenticationProvider(
'pre' )
487 [
'pre' => $mocks[
'pre'] ],
488 $this->managerPriv->getPreAuthenticationProviders()
491 [
'primary' => $mocks[
'primary'] ],
492 $this->managerPriv->getPrimaryAuthenticationProviders()
495 [
'secondary' => $mocks[
'secondary'] ],
496 $this->managerPriv->getSecondaryAuthenticationProviders()
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 = [];
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 );
515 "Duplicate specifications for id X (classes $class1 and $class2)", $ex->getMessage()
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 ];
528 $this->managerPriv->getPreAuthenticationProviders();
529 $this->fail(
'Expected exception not thrown' );
530 }
catch ( \RuntimeException $ex ) {
532 "Expected instance of MediaWiki\\Auth\\PreAuthenticationProvider, got $class",
537 $this->managerPriv->getPrimaryAuthenticationProviders();
538 $this->fail(
'Expected exception not thrown' );
539 }
catch ( \RuntimeException $ex ) {
541 "Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got $class",
546 $this->managerPriv->getSecondaryAuthenticationProviders();
547 $this->fail(
'Expected exception not thrown' );
548 }
catch ( \RuntimeException $ex ) {
550 "Expected instance of MediaWiki\\Auth\\SecondaryAuthenticationProvider, got $class",
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 = [];
566 $config = $this->config->
get(
'AuthManagerConfig' );
570 [
'A' => $mock1,
'B' => $mock2,
'C' => $mock3 ],
571 $this->managerPriv->getPrimaryAuthenticationProviders(),
575 $config[
'primaryauth'][
'A'][
'sort'] = 100;
576 $config[
'primaryauth'][
'C'][
'sort'] = -1;
577 $this->config->set(
'AuthManagerConfig',
$config );
580 [
'C' => $mock3,
'B' => $mock2,
'A' => $mock1 ],
581 $this->managerPriv->getPrimaryAuthenticationProviders()
588 $context = \RequestContext::getMain();
589 $reset =
new ScopedCallback( [
$context,
'setLanguage' ], [
$context->getLanguage() ] );
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' ) );
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 );
636 $this->manager->forcePrimaryAuthenticationProviders( [ $mockB ],
'testing' );
638 [
'B' => $mockB ], $this->managerPriv->getPrimaryAuthenticationProviders()
640 $this->assertSame(
null, $this->managerPriv->getAuthenticationProvider(
'A' ) );
641 $this->assertSame( $mockB, $this->managerPriv->getAuthenticationProvider(
'B' ) );
643 [ LogLevel::WARNING,
'Overriding AuthManager primary authn because testing' ],
644 ], $this->logger->getBuffer() );
645 $this->logger->clearBuffer();
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' );
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' ) );
661 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
664 [ LogLevel::WARNING,
'Overriding AuthManager primary authn because testing' ],
667 'PrimaryAuthenticationProviders have already been accessed! I hope nothing breaks.'
669 ], $this->logger->getBuffer() );
670 $this->logger->clearBuffer();
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 );
681 "Duplicate specifications for id B (classes $class2 and $class1)", $ex->getMessage()
686 $mock = $this->getMockForAbstractClass( AuthenticationProvider::class );
687 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
688 $class = get_class( $mock );
690 $this->manager->forcePrimaryAuthenticationProviders( [ $mock ],
'testing' );
691 $this->fail(
'Expected exception not thrown' );
692 }
catch ( \RuntimeException $ex ) {
694 "Expected instance of MediaWiki\\Auth\\PrimaryAuthenticationProvider, got $class",
706 $this->
hook(
'UserLoggedIn', $this->never() );
707 $this->
request->getSession()->setSecret(
'AuthManager::authnState',
'test' );
709 $this->manager->beginAuthentication( [],
'http://localhost/' );
710 $this->fail(
'Expected exception not thrown' );
711 }
catch ( \LogicException $ex ) {
712 $this->assertSame(
'Authentication is not possible now', $ex->getMessage() );
714 $this->
unhook(
'UserLoggedIn' );
715 $this->assertNull( $this->
request->getSession()->getSecret(
'AuthManager::authnState' ) );
716 ScopedCallback::consume( $reset );
720 $user = \User::newFromName(
'UTSysop' );
724 $this->
hook(
'UserLoggedIn', $this->never() );
726 $this->manager->beginAuthentication( $reqs,
'http://localhost/' );
727 $this->fail(
'Expected exception not thrown' );
728 }
catch ( \LogicException $ex ) {
730 'CreatedAccountAuthenticationRequests are only valid on the same AuthManager ' .
731 'that created the account',
735 $this->
unhook(
'UserLoggedIn' );
737 $this->
request->getSession()->clear();
738 $this->
request->getSession()->setSecret(
'AuthManager::authnState',
'test' );
739 $this->managerPriv->createdAccountAuthenticationRequests = [ $reqs[0] ];
740 $this->
hook(
'UserLoggedIn', $this->once() )
741 ->with( $this->callback(
function ( $u )
use (
$user ) {
742 return $user->getId() === $u->getId() &&
$user->getName() === $u->getName();
744 $this->
hook(
'AuthManagerLoginAuthenticateAudit', $this->once() );
745 $this->logger->setCollect(
true );
746 $ret = $this->manager->beginAuthentication( $reqs,
'http://localhost/' );
747 $this->logger->setCollect(
false );
748 $this->
unhook(
'UserLoggedIn' );
749 $this->
unhook(
'AuthManagerLoginAuthenticateAudit' );
751 $this->assertSame(
$user->getName(),
$ret->username );
752 $this->assertSame(
$user->getId(), $this->request->getSessionData(
'AuthManager:lastAuthId' ) );
754 time(), $this->
request->getSessionData(
'AuthManager:lastAuthTimestamp' ),
757 $this->assertNull( $this->
request->getSession()->getSecret(
'AuthManager::authnState' ) );
758 $this->assertSame(
$user->getId(), $this->request->getSession()->getUser()->getId() );
760 [ LogLevel::INFO,
'Logging in {user} after account creation' ],
761 ], $this->logger->getBuffer() );
765 $user = \User::newFromName(
'UTSysop' );
766 $req1 = $this->getMock( AuthenticationRequest::class );
767 $req2 = $this->getMock( AuthenticationRequest::class );
768 $req3 = $this->getMock( AuthenticationRequest::class );
770 $userReq->username =
'UTDummy';
772 $req1->returnToUrl =
'http://localhost/';
773 $req2->returnToUrl =
'http://localhost/';
774 $req3->returnToUrl =
'http://localhost/';
775 $req3->username =
'UTDummy';
776 $userReq->returnToUrl =
'http://localhost/';
779 $primary = $this->getMockForAbstractClass( AbstractPrimaryAuthenticationProvider::class );
780 $this->primaryauthMocks = [ $primary ];
783 $res->createRequest = $req1;
784 $primary->expects( $this->any() )->method(
'beginPrimaryAuthentication' )
785 ->will( $this->returnValue(
$res ) );
787 null, [ $req2->getUniqueId() => $req2 ]
789 $this->logger->setCollect(
true );
790 $ret = $this->manager->beginAuthentication( [ $createReq ],
'http://localhost/' );
791 $this->logger->setCollect(
false );
793 $this->assertInstanceOf( CreateFromLoginAuthenticationRequest::class,
$ret->createRequest );
794 $this->assertSame( $req1,
$ret->createRequest->createRequest );
795 $this->assertEquals( [ $req2->getUniqueId() => $req2 ],
$ret->createRequest->maybeLink );
798 $primary = $this->getMockBuilder( AbstractPrimaryAuthenticationProvider::class )
799 ->setMethods( [
'continuePrimaryAuthentication' ] )
800 ->getMockForAbstractClass();
801 $this->primaryauthMocks = [ $primary ];
803 $primary->expects( $this->any() )->method(
'beginPrimaryAuthentication' )
804 ->will( $this->returnValue(
808 $res->createRequest = $req2;
809 $primary->expects( $this->any() )->method(
'continuePrimaryAuthentication' )
810 ->will( $this->returnValue(
$res ) );
811 $this->logger->setCollect(
true );
812 $ret = $this->manager->beginAuthentication( [],
'http://localhost/' );
814 $ret = $this->manager->continueAuthentication( [] );
815 $this->logger->setCollect(
false );
817 $this->assertInstanceOf( CreateFromLoginAuthenticationRequest::class,
$ret->createRequest );
818 $this->assertSame( $req2,
$ret->createRequest->createRequest );
819 $this->assertEquals( [],
$ret->createRequest->maybeLink );
822 $primary = $this->getMockForAbstractClass( AbstractPrimaryAuthenticationProvider::class );
823 $this->primaryauthMocks = [ $primary ];
826 $createReq->returnToUrl =
'http://localhost/';
827 $createReq->username =
'UTDummy';
829 $primary->expects( $this->any() )->method(
'beginPrimaryAccountCreation' )
830 ->with( $this->
anything(), $this->
anything(), [ $userReq, $createReq, $req3 ] )
831 ->will( $this->returnValue(
$res ) );
832 $primary->expects( $this->any() )->method(
'accountCreationType' )
834 $this->logger->setCollect(
true );
835 $ret = $this->manager->beginAccountCreation(
836 $user, [ $userReq, $createReq ],
'http://localhost/'
838 $this->logger->setCollect(
false );
840 $state = $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' );
841 $this->assertNotNull( $state );
842 $this->assertEquals( [ $userReq, $createReq, $req3 ], $state[
'reqs'] );
843 $this->assertEquals( [ $req2 ], $state[
'maybeLink'] );
859 $user = \User::newFromName(
'UTSysop' );
860 $id =
$user->getId();
865 $req->rememberMe = (bool)rand( 0, 1 );
866 $req->pre = $preResponse;
867 $req->primary = $primaryResponses;
868 $req->secondary = $secondaryResponses;
870 foreach ( [
'pre',
'primary',
'secondary' ]
as $key ) {
871 $class = ucfirst( $key ) .
'AuthenticationProvider';
872 $mocks[$key] = $this->getMockForAbstractClass(
873 "MediaWiki\\Auth\\$class", [],
"Mock$class"
875 $mocks[$key]->expects( $this->any() )->method(
'getUniqueId' )
876 ->will( $this->returnValue( $key ) );
877 $mocks[$key .
'2'] = $this->getMockForAbstractClass(
878 "MediaWiki\\Auth\\$class", [],
"Mock$class"
880 $mocks[$key .
'2']->expects( $this->any() )->method(
'getUniqueId' )
881 ->will( $this->returnValue( $key .
'2' ) );
882 $mocks[$key .
'3'] = $this->getMockForAbstractClass(
883 "MediaWiki\\Auth\\$class", [],
"Mock$class"
885 $mocks[$key .
'3']->expects( $this->any() )->method(
'getUniqueId' )
886 ->will( $this->returnValue( $key .
'3' ) );
888 foreach ( $mocks
as $mock ) {
889 $mock->expects( $this->any() )->method(
'getAuthenticationRequests' )
890 ->will( $this->returnValue( [] ) );
893 $mocks[
'pre']->expects( $this->once() )->method(
'testForAuthentication' )
894 ->will( $this->returnCallback(
function ( $reqs )
use (
$req ) {
895 $this->assertContains(
$req, $reqs );
899 $ct = count(
$req->primary );
900 $callback = $this->returnCallback(
function ( $reqs )
use (
$req ) {
901 $this->assertContains(
$req, $reqs );
902 return array_shift(
$req->primary );
904 $mocks[
'primary']->expects( $this->exactly( min( 1, $ct ) ) )
905 ->method(
'beginPrimaryAuthentication' )
907 $mocks[
'primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
908 ->method(
'continuePrimaryAuthentication' )
911 $mocks[
'primary']->expects( $this->any() )->method(
'accountCreationType' )
915 $ct = count(
$req->secondary );
916 $callback = $this->returnCallback(
function (
$user, $reqs )
use ( $id,
$name,
$req ) {
917 $this->assertSame( $id,
$user->getId() );
919 $this->assertContains(
$req, $reqs );
920 return array_shift(
$req->secondary );
922 $mocks[
'secondary']->expects( $this->exactly( min( 1, $ct ) ) )
923 ->method(
'beginSecondaryAuthentication' )
925 $mocks[
'secondary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
926 ->method(
'continueSecondaryAuthentication' )
930 $mocks[
'pre2']->expects( $this->atMost( 1 ) )->method(
'testForAuthentication' )
931 ->will( $this->returnValue( StatusValue::newGood() ) );
932 $mocks[
'primary2']->expects( $this->atMost( 1 ) )->method(
'beginPrimaryAuthentication' )
933 ->will( $this->returnValue( $abstain ) );
934 $mocks[
'primary2']->expects( $this->never() )->method(
'continuePrimaryAuthentication' );
935 $mocks[
'secondary2']->expects( $this->atMost( 1 ) )->method(
'beginSecondaryAuthentication' )
936 ->will( $this->returnValue( $abstain ) );
937 $mocks[
'secondary2']->expects( $this->never() )->method(
'continueSecondaryAuthentication' );
938 $mocks[
'secondary3']->expects( $this->atMost( 1 ) )->method(
'beginSecondaryAuthentication' )
939 ->will( $this->returnValue( $abstain ) );
940 $mocks[
'secondary3']->expects( $this->never() )->method(
'continueSecondaryAuthentication' );
942 $this->preauthMocks = [ $mocks[
'pre'], $mocks[
'pre2'] ];
943 $this->primaryauthMocks = [ $mocks[
'primary'], $mocks[
'primary2'] ];
944 $this->secondaryauthMocks = [
945 $mocks[
'secondary3'], $mocks[
'secondary'], $mocks[
'secondary2'],
950 $this->logger->setCollect(
true );
952 $constraint = \PHPUnit_Framework_Assert::logicalOr(
956 $providers = array_filter(
958 $this->preauthMocks, $this->primaryauthMocks, $this->secondaryauthMocks
961 return is_callable( [ $p,
'expects' ] );
964 foreach ( $providers
as $p ) {
965 $p->postCalled =
false;
966 $p->expects( $this->atMost( 1 ) )->method(
'postAuthentication' )
968 if (
$user !==
null ) {
969 $this->assertInstanceOf(
'User',
$user );
970 $this->assertSame(
'UTSysop',
$user->getName() );
972 $this->assertInstanceOf( AuthenticationResponse::class,
$response );
973 $this->assertThat(
$response->status, $constraint );
978 $session = $this->
request->getSession();
979 $session->setRememberUser( !
$req->rememberMe );
985 $this->
hook(
'UserLoggedIn', $this->once() )
986 ->with( $this->callback(
function (
$user )
use ( $id,
$name ) {
990 $this->
hook(
'UserLoggedIn', $this->never() );
995 $response->message->getKey() !==
'authmanager-authn-not-in-progress' &&
996 $response->message->getKey() !==
'authmanager-authn-no-primary'
999 $this->
hook(
'AuthManagerLoginAuthenticateAudit', $this->once() );
1001 $this->
hook(
'AuthManagerLoginAuthenticateAudit', $this->never() );
1007 $ret = $this->manager->beginAuthentication( [
$req ],
'http://localhost/' );
1009 $ret = $this->manager->continueAuthentication( [
$req ] );
1011 if (
$response instanceof \Exception ) {
1012 $this->fail(
'Expected exception not thrown',
"Response $i" );
1014 }
catch ( \Exception $ex ) {
1015 if ( !
$response instanceof \Exception ) {
1018 $this->assertEquals(
$response->getMessage(), $ex->getMessage(),
"Response $i, exception" );
1019 $this->assertNull( $session->getSecret(
'AuthManager::authnState' ),
1020 "Response $i, exception, session state" );
1021 $this->
unhook(
'UserLoggedIn' );
1022 $this->
unhook(
'AuthManagerLoginAuthenticateAudit' );
1026 $this->
unhook(
'UserLoggedIn' );
1027 $this->
unhook(
'AuthManagerLoginAuthenticateAudit' );
1029 $this->assertSame(
'http://localhost/',
$req->returnToUrl );
1032 $this->assertEquals(
$response,
$ret,
"Response $i, response" );
1034 $this->assertSame( $id, $session->getUser()->getId(),
1035 "Response $i, authn" );
1037 $this->assertSame( 0, $session->getUser()->getId(),
1038 "Response $i, authn" );
1041 $this->assertNull( $session->getSecret(
'AuthManager::authnState' ),
1042 "Response $i, session state" );
1043 foreach ( $providers
as $p ) {
1044 $this->assertSame(
$response->status, $p->postCalled,
1045 "Response $i, post-auth callback called" );
1048 $this->assertNotNull( $session->getSecret(
'AuthManager::authnState' ),
1049 "Response $i, session state" );
1050 foreach (
$ret->neededRequests
as $neededReq ) {
1052 "Response $i, neededRequest action" );
1054 $this->assertEquals(
1055 $ret->neededRequests,
1057 "Response $i, continuation check"
1059 foreach ( $providers
as $p ) {
1060 $this->assertFalse( $p->postCalled,
"Response $i, post-auth callback not called" );
1064 $state = $session->getSecret(
'AuthManager::authnState' );
1065 $maybeLink = isset( $state[
'maybeLink'] ) ? $state[
'maybeLink'] : [];
1067 $this->assertEquals(
1070 "Response $i, maybeLink"
1073 $this->assertEquals( [], $maybeLink,
"Response $i, maybeLink" );
1078 $this->assertSame(
$req->rememberMe, $session->shouldRememberUser(),
1079 'rememberMe checkbox had effect' );
1081 $this->assertNotSame(
$req->rememberMe, $session->shouldRememberUser(),
1082 'rememberMe checkbox wasn\'t applied' );
1087 $user = \User::newFromName(
'UTSysop' );
1088 $id =
$user->getId();
1094 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1095 $req->foobar =
'baz';
1097 $this->
message(
'authmanager-authn-no-local-user' )
1099 $restartResponse->neededRequests = [ $rememberReq ];
1102 $restartResponse2Pass->linkRequest =
$req;
1104 $this->
message(
'authmanager-authn-no-local-user-link' )
1107 null, [
$req->getUniqueId() =>
$req ]
1110 $restartResponse2->neededRequests = [ $rememberReq, $restartResponse2->createRequest ];
1113 'Failure in pre-auth' => [
1114 StatusValue::newFatal(
'fail-from-pre' ),
1120 $this->
message(
'authmanager-authn-not-in-progress' )
1124 'Failure in primary' => [
1125 StatusValue::newGood(),
1132 'All primary abstain' => [
1133 StatusValue::newGood(),
1142 'Primary UI, then redirect, then fail' => [
1143 StatusValue::newGood(),
1152 'Primary redirect, then abstain' => [
1153 StatusValue::newGood(),
1156 [
$req ],
'/foo.html', [
'foo' =>
'bar' ]
1163 new \DomainException(
1164 'MockPrimaryAuthenticationProvider::continuePrimaryAuthentication() returned ABSTAIN'
1168 'Primary UI, then pass with no local user' => [
1169 StatusValue::newGood(),
1180 'Primary UI, then pass with no local user (link type)' => [
1181 StatusValue::newGood(),
1184 $restartResponse2Pass,
1193 'Primary pass with invalid username' => [
1194 StatusValue::newGood(),
1200 new \DomainException(
'MockPrimaryAuthenticationProvider returned an invalid username: <>' ),
1203 'Secondary fail' => [
1204 StatusValue::newGood(),
1213 'Secondary UI, then abstain' => [
1214 StatusValue::newGood(),
1227 'Secondary pass' => [
1228 StatusValue::newGood(),
1249 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1250 $mock1->expects( $this->any() )->method(
'getUniqueId' )
1251 ->will( $this->returnValue(
'primary1' ) );
1252 $mock1->expects( $this->any() )->method(
'testUserExists' )
1253 ->with( $this->equalTo(
'UTSysop' ) )
1254 ->will( $this->returnValue( $primary1Exists ) );
1255 $mock2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1256 $mock2->expects( $this->any() )->method(
'getUniqueId' )
1257 ->will( $this->returnValue(
'primary2' ) );
1258 $mock2->expects( $this->any() )->method(
'testUserExists' )
1259 ->with( $this->equalTo(
'UTSysop' ) )
1260 ->will( $this->returnValue( $primary2Exists ) );
1261 $this->primaryauthMocks = [ $mock1, $mock2 ];
1264 $this->assertSame( $expect, $this->manager->userExists(
'UTSysop' ) );
1269 [
false,
false,
false ],
1270 [
true,
false,
true ],
1271 [
false,
true,
true ],
1272 [
true,
true,
true ],
1283 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1285 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1286 $mock1->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'1' ) );
1287 $mock1->expects( $this->any() )->method(
'providerAllowsAuthenticationDataChange' )
1288 ->with( $this->equalTo(
$req ) )
1289 ->will( $this->returnValue( $primaryReturn ) );
1290 $mock2 = $this->getMockForAbstractClass( SecondaryAuthenticationProvider::class );
1291 $mock2->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'2' ) );
1292 $mock2->expects( $this->any() )->method(
'providerAllowsAuthenticationDataChange' )
1293 ->with( $this->equalTo(
$req ) )
1294 ->will( $this->returnValue( $secondaryReturn ) );
1296 $this->primaryauthMocks = [ $mock1 ];
1297 $this->secondaryauthMocks = [ $mock2 ];
1299 $this->assertEquals( $expect, $this->manager->allowsAuthenticationDataChange(
$req ) );
1303 $ignored = \Status::newGood(
'ignored' );
1304 $ignored->warning(
'authmanager-change-not-supported' );
1306 $okFromPrimary = StatusValue::newGood();
1307 $okFromPrimary->warning(
'warning-from-primary' );
1308 $okFromSecondary = StatusValue::newGood();
1309 $okFromSecondary->warning(
'warning-from-secondary' );
1313 StatusValue::newGood(),
1314 StatusValue::newGood(),
1318 StatusValue::newGood(),
1319 StatusValue::newGood(
'ignore' ),
1323 StatusValue::newGood(
'ignored' ),
1324 StatusValue::newGood(),
1328 StatusValue::newGood(
'ignored' ),
1329 StatusValue::newGood(
'ignored' ),
1333 StatusValue::newFatal(
'fail from primary' ),
1334 StatusValue::newGood(),
1335 \Status::newFatal(
'fail from primary' ),
1339 StatusValue::newGood(),
1340 \Status::wrap( $okFromPrimary ),
1343 StatusValue::newGood(),
1344 StatusValue::newFatal(
'fail from secondary' ),
1345 \Status::newFatal(
'fail from secondary' ),
1348 StatusValue::newGood(),
1350 \Status::wrap( $okFromSecondary ),
1356 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1357 $req->username =
'UTSysop';
1359 $mock1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1360 $mock1->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'1' ) );
1361 $mock1->expects( $this->once() )->method(
'providerChangeAuthenticationData' )
1362 ->with( $this->equalTo(
$req ) );
1363 $mock2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1364 $mock2->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'2' ) );
1365 $mock2->expects( $this->once() )->method(
'providerChangeAuthenticationData' )
1366 ->with( $this->equalTo(
$req ) );
1368 $this->primaryauthMocks = [ $mock1, $mock2 ];
1370 $this->logger->setCollect(
true );
1371 $this->manager->changeAuthenticationData(
$req );
1372 $this->assertSame( [
1373 [ LogLevel::INFO,
'Changing authentication data for {user} class {what}' ],
1374 ], $this->logger->getBuffer() );
1384 foreach ( $types
as $type => $can ) {
1385 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1386 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
$type ) );
1387 $mock->expects( $this->any() )->method(
'accountCreationType' )
1388 ->will( $this->returnValue(
$type ) );
1389 $this->primaryauthMocks = [ $mock ];
1391 $this->assertSame( $can, $this->manager->canCreateAccounts(),
$type );
1402 $wgGroupPermissions[
'*'][
'createaccount'] =
true;
1403 $this->assertEquals(
1405 $this->manager->checkAccountCreatePermissions(
new \
User )
1409 $this->assertEquals(
1410 \Status::newFatal(
'readonlytext',
'Because' ),
1411 $this->manager->checkAccountCreatePermissions(
new \
User )
1415 $wgGroupPermissions[
'*'][
'createaccount'] =
false;
1416 $status = $this->manager->checkAccountCreatePermissions(
new \
User );
1417 $this->assertFalse(
$status->isOK() );
1418 $this->assertTrue(
$status->hasMessage(
'badaccess-groups' ) );
1421 $user = \User::newFromName(
'UTBlockee' );
1422 if (
$user->getID() == 0 ) {
1423 $user->addToDatabase();
1424 \TestUser::setPasswordForUser(
$user,
'UTBlockeePassword' );
1425 $user->saveSettings();
1427 $oldBlock = \Block::newFromTarget(
'UTBlockee' );
1430 $oldBlock->delete();
1433 'address' =>
'UTBlockee',
1434 'user' =>
$user->getID(),
1435 'reason' => __METHOD__,
1436 'expiry' => time() + 100500,
1437 'createAccount' =>
true,
1439 $block = new \Block( $blockOptions );
1441 $status = $this->manager->checkAccountCreatePermissions(
$user );
1442 $this->assertFalse(
$status->isOK() );
1443 $this->assertTrue(
$status->hasMessage(
'cantcreateaccount-text' ) );
1446 'address' =>
'127.0.0.0/24',
1447 'reason' => __METHOD__,
1448 'expiry' => time() + 100500,
1449 'createAccount' =>
true,
1451 $block = new \Block( $blockOptions );
1453 $scopeVariable =
new ScopedCallback( [ $block,
'delete' ] );
1454 $status = $this->manager->checkAccountCreatePermissions(
new \
User );
1455 $this->assertFalse(
$status->isOK() );
1456 $this->assertTrue(
$status->hasMessage(
'cantcreateaccount-range-text' ) );
1457 ScopedCallback::consume( $scopeVariable );
1460 'wgEnableDnsBlacklist' =>
true,
1461 'wgDnsBlacklistUrls' => [
1462 'local.wmftest.net',
1464 'wgProxyWhitelist' => [],
1466 $status = $this->manager->checkAccountCreatePermissions(
new \
User );
1467 $this->assertFalse(
$status->isOK() );
1468 $this->assertTrue(
$status->hasMessage(
'sorbs_create_account_reason' ) );
1469 $this->
setMwGlobals(
'wgProxyWhitelist', [
'127.0.0.1' ] );
1470 $status = $this->manager->checkAccountCreatePermissions(
new \
User );
1471 $this->assertTrue(
$status->isGood() );
1481 $username =
"UTAuthManagerTestAccountCreation" . $uniq . ++$i;
1482 }
while ( \User::newFromName(
$username )->getId() !== 0 );
1490 $this->assertEquals(
1491 \Status::newFatal(
'authmanager-create-disabled' ),
1492 $this->manager->canCreateAccount(
$username )
1495 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1496 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1497 $mock->expects( $this->any() )->method(
'accountCreationType' )
1499 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
true ) );
1500 $mock->expects( $this->any() )->method(
'testUserForCreation' )
1501 ->will( $this->returnValue( StatusValue::newGood() ) );
1502 $this->primaryauthMocks = [ $mock ];
1505 $this->assertEquals(
1506 \Status::newFatal(
'userexists' ),
1507 $this->manager->canCreateAccount(
$username )
1510 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1511 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1512 $mock->expects( $this->any() )->method(
'accountCreationType' )
1514 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
false ) );
1515 $mock->expects( $this->any() )->method(
'testUserForCreation' )
1516 ->will( $this->returnValue( StatusValue::newGood() ) );
1517 $this->primaryauthMocks = [ $mock ];
1520 $this->assertEquals(
1521 \Status::newFatal(
'noname' ),
1522 $this->manager->canCreateAccount(
$username .
'<>' )
1525 $this->assertEquals(
1526 \Status::newFatal(
'userexists' ),
1527 $this->manager->canCreateAccount(
'UTSysop' )
1530 $this->assertEquals(
1532 $this->manager->canCreateAccount(
$username )
1535 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1536 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1537 $mock->expects( $this->any() )->method(
'accountCreationType' )
1539 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
false ) );
1540 $mock->expects( $this->any() )->method(
'testUserForCreation' )
1541 ->will( $this->returnValue( StatusValue::newFatal(
'fail' ) ) );
1542 $this->primaryauthMocks = [ $mock ];
1545 $this->assertEquals(
1546 \Status::newFatal(
'fail' ),
1547 $this->manager->canCreateAccount(
$username )
1552 $creator = \User::newFromName(
'UTSysop' );
1554 $this->logger = new \TestLogger(
false,
function ( $message, $level ) {
1555 return $level === LogLevel::DEBUG ? null : $message;
1559 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
'test' );
1560 $this->
hook(
'LocalUserCreated', $this->never() );
1562 $this->manager->beginAccountCreation(
1563 $creator, [],
'http://localhost/'
1565 $this->fail(
'Expected exception not thrown' );
1566 }
catch ( \LogicException $ex ) {
1567 $this->assertEquals(
'Account creation is not possible', $ex->getMessage() );
1569 $this->
unhook(
'LocalUserCreated' );
1571 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
1574 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1575 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1576 $mock->expects( $this->any() )->method(
'accountCreationType' )
1578 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
true ) );
1579 $mock->expects( $this->any() )->method(
'testUserForCreation' )
1580 ->will( $this->returnValue( StatusValue::newGood() ) );
1581 $this->primaryauthMocks = [ $mock ];
1584 $this->
hook(
'LocalUserCreated', $this->never() );
1585 $ret = $this->manager->beginAccountCreation( $creator, [],
'http://localhost/' );
1586 $this->
unhook(
'LocalUserCreated' );
1588 $this->assertSame(
'noname',
$ret->message->getKey() );
1590 $this->
hook(
'LocalUserCreated', $this->never() );
1593 $userReq2->username = $userReq->username .
'X';
1594 $ret = $this->manager->beginAccountCreation(
1595 $creator, [ $userReq, $userReq2 ],
'http://localhost/'
1597 $this->
unhook(
'LocalUserCreated' );
1599 $this->assertSame(
'noname',
$ret->message->getKey() );
1602 $this->
hook(
'LocalUserCreated', $this->never() );
1604 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ],
'http://localhost/' );
1605 $this->
unhook(
'LocalUserCreated' );
1607 $this->assertSame(
'readonlytext',
$ret->message->getKey() );
1608 $this->assertSame( [
'Because' ],
$ret->message->getParams() );
1611 $this->
hook(
'LocalUserCreated', $this->never() );
1613 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ],
'http://localhost/' );
1614 $this->
unhook(
'LocalUserCreated' );
1616 $this->assertSame(
'userexists',
$ret->message->getKey() );
1618 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1619 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1620 $mock->expects( $this->any() )->method(
'accountCreationType' )
1622 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
false ) );
1623 $mock->expects( $this->any() )->method(
'testUserForCreation' )
1624 ->will( $this->returnValue( StatusValue::newFatal(
'fail' ) ) );
1625 $this->primaryauthMocks = [ $mock ];
1628 $this->
hook(
'LocalUserCreated', $this->never() );
1630 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ],
'http://localhost/' );
1631 $this->
unhook(
'LocalUserCreated' );
1633 $this->assertSame(
'fail',
$ret->message->getKey() );
1635 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1636 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1637 $mock->expects( $this->any() )->method(
'accountCreationType' )
1639 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
false ) );
1640 $mock->expects( $this->any() )->method(
'testUserForCreation' )
1641 ->will( $this->returnValue( StatusValue::newGood() ) );
1642 $this->primaryauthMocks = [ $mock ];
1645 $this->
hook(
'LocalUserCreated', $this->never() );
1647 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ],
'http://localhost/' );
1648 $this->
unhook(
'LocalUserCreated' );
1650 $this->assertSame(
'noname',
$ret->message->getKey() );
1652 $this->
hook(
'LocalUserCreated', $this->never() );
1653 $userReq->username = $creator->getName();
1654 $ret = $this->manager->beginAccountCreation( $creator, [ $userReq ],
'http://localhost/' );
1655 $this->
unhook(
'LocalUserCreated' );
1657 $this->assertSame(
'userexists',
$ret->message->getKey() );
1659 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1660 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1661 $mock->expects( $this->any() )->method(
'accountCreationType' )
1663 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
false ) );
1664 $mock->expects( $this->any() )->method(
'testUserForCreation' )
1665 ->will( $this->returnValue( StatusValue::newGood() ) );
1666 $mock->expects( $this->any() )->method(
'testForAccountCreation' )
1667 ->will( $this->returnValue( StatusValue::newFatal(
'fail' ) ) );
1668 $this->primaryauthMocks = [ $mock ];
1671 $req = $this->getMockBuilder( UserDataAuthenticationRequest::class )
1672 ->setMethods( [
'populateUser' ] )
1674 $req->expects( $this->any() )->method(
'populateUser' )
1675 ->willReturn( \StatusValue::newFatal(
'populatefail' ) );
1677 $ret = $this->manager->beginAccountCreation(
1678 $creator, [ $userReq,
$req ],
'http://localhost/'
1681 $this->assertSame(
'populatefail',
$ret->message->getKey() );
1686 $ret = $this->manager->beginAccountCreation(
1687 $creator, [ $userReq,
$req ],
'http://localhost/'
1690 $this->assertSame(
'fail',
$ret->message->getKey() );
1692 $this->manager->beginAccountCreation(
1693 \User::newFromName( $userReq->username ), [ $userReq,
$req ],
'http://localhost/'
1696 $this->assertSame(
'fail',
$ret->message->getKey() );
1700 $creator = \User::newFromName(
'UTSysop' );
1702 $this->logger = new \TestLogger(
false,
function ( $message, $level ) {
1703 return $level === LogLevel::DEBUG ? null : $message;
1714 'primaryResponse' =>
null,
1716 'ranPreTests' =>
true,
1719 $this->
hook(
'LocalUserCreated', $this->never() );
1721 $this->manager->continueAccountCreation( [] );
1722 $this->fail(
'Expected exception not thrown' );
1723 }
catch ( \LogicException $ex ) {
1724 $this->assertEquals(
'Account creation is not possible', $ex->getMessage() );
1726 $this->
unhook(
'LocalUserCreated' );
1728 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
1729 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
1730 $mock->expects( $this->any() )->method(
'accountCreationType' )
1732 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
false ) );
1733 $mock->expects( $this->any() )->method(
'beginPrimaryAccountCreation' )->will(
1736 $this->primaryauthMocks = [ $mock ];
1739 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
null );
1740 $this->
hook(
'LocalUserCreated', $this->never() );
1741 $ret = $this->manager->continueAccountCreation( [] );
1742 $this->
unhook(
'LocalUserCreated' );
1744 $this->assertSame(
'authmanager-create-not-in-progress',
$ret->message->getKey() );
1746 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
1747 [
'username' =>
"$username<>" ] + $session );
1748 $this->
hook(
'LocalUserCreated', $this->never() );
1749 $ret = $this->manager->continueAccountCreation( [] );
1750 $this->
unhook(
'LocalUserCreated' );
1752 $this->assertSame(
'noname',
$ret->message->getKey() );
1754 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
1757 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState', $session );
1758 $this->
hook(
'LocalUserCreated', $this->never() );
1759 $cache = \ObjectCache::getLocalClusterInstance();
1761 $ret = $this->manager->continueAccountCreation( [] );
1763 $this->
unhook(
'LocalUserCreated' );
1765 $this->assertSame(
'usernameinprogress',
$ret->message->getKey() );
1769 $session, $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
1772 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
1773 [
'username' => $creator->getName() ] + $session );
1775 $this->
hook(
'LocalUserCreated', $this->never() );
1776 $ret = $this->manager->continueAccountCreation( [] );
1777 $this->
unhook(
'LocalUserCreated' );
1779 $this->assertSame(
'readonlytext',
$ret->message->getKey() );
1780 $this->assertSame( [
'Because' ],
$ret->message->getParams() );
1783 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
1784 [
'username' => $creator->getName() ] + $session );
1785 $this->
hook(
'LocalUserCreated', $this->never() );
1786 $ret = $this->manager->continueAccountCreation( [] );
1787 $this->
unhook(
'LocalUserCreated' );
1789 $this->assertSame(
'userexists',
$ret->message->getKey() );
1791 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
1794 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
1795 [
'userid' => $creator->getId() ] + $session );
1796 $this->
hook(
'LocalUserCreated', $this->never() );
1798 $ret = $this->manager->continueAccountCreation( [] );
1799 $this->fail(
'Expected exception not thrown' );
1800 }
catch ( \UnexpectedValueException $ex ) {
1801 $this->assertEquals(
"User \"{$username}\" should exist now, but doesn't!", $ex->getMessage() );
1803 $this->
unhook(
'LocalUserCreated' );
1805 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
1808 $id = $creator->getId();
1809 $name = $creator->getName();
1810 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
1811 [
'username' =>
$name,
'userid' => $id + 1 ] + $session );
1812 $this->
hook(
'LocalUserCreated', $this->never() );
1814 $ret = $this->manager->continueAccountCreation( [] );
1815 $this->fail(
'Expected exception not thrown' );
1816 }
catch ( \UnexpectedValueException $ex ) {
1817 $this->assertEquals(
1818 "User \"{$name}\" exists, but ID $id != " . ( $id + 1 ) .
'!', $ex->getMessage()
1821 $this->
unhook(
'LocalUserCreated' );
1823 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
1826 $req = $this->getMockBuilder( UserDataAuthenticationRequest::class )
1827 ->setMethods( [
'populateUser' ] )
1829 $req->expects( $this->any() )->method(
'populateUser' )
1830 ->willReturn( \StatusValue::newFatal(
'populatefail' ) );
1831 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState',
1832 [
'reqs' => [
$req ] ] + $session );
1833 $ret = $this->manager->continueAccountCreation( [] );
1835 $this->assertSame(
'populatefail',
$ret->message->getKey() );
1837 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' )
1851 StatusValue $preTest, $primaryTest, $secondaryTest,
1852 array $primaryResponses,
array $secondaryResponses,
array $managerResponses
1854 $creator = \User::newFromName(
'UTSysop' );
1860 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
1861 $req->preTest = $preTest;
1862 $req->primaryTest = $primaryTest;
1863 $req->secondaryTest = $secondaryTest;
1864 $req->primary = $primaryResponses;
1865 $req->secondary = $secondaryResponses;
1867 foreach ( [
'pre',
'primary',
'secondary' ]
as $key ) {
1868 $class = ucfirst( $key ) .
'AuthenticationProvider';
1869 $mocks[$key] = $this->getMockForAbstractClass(
1870 "MediaWiki\\Auth\\$class", [],
"Mock$class"
1872 $mocks[$key]->expects( $this->any() )->method(
'getUniqueId' )
1873 ->will( $this->returnValue( $key ) );
1874 $mocks[$key]->expects( $this->any() )->method(
'testUserForCreation' )
1875 ->will( $this->returnValue( StatusValue::newGood() ) );
1876 $mocks[$key]->expects( $this->any() )->method(
'testForAccountCreation' )
1877 ->will( $this->returnCallback(
1878 function (
$user, $creatorIn, $reqs )
1882 $this->assertSame( $creator->getId(), $creatorIn->getId() );
1883 $this->assertSame( $creator->getName(), $creatorIn->getName() );
1885 foreach ( $reqs
as $r ) {
1886 $this->assertSame(
$username, $r->username );
1887 $foundReq = $foundReq || get_class( $r ) === get_class(
$req );
1889 $this->assertTrue( $foundReq,
'$reqs contains $req' );
1895 for ( $i = 2; $i <= 3; $i++ ) {
1896 $mocks[$key . $i] = $this->getMockForAbstractClass(
1897 "MediaWiki\\Auth\\$class", [],
"Mock$class"
1899 $mocks[$key . $i]->expects( $this->any() )->method(
'getUniqueId' )
1900 ->will( $this->returnValue( $key . $i ) );
1901 $mocks[$key . $i]->expects( $this->any() )->method(
'testUserForCreation' )
1902 ->will( $this->returnValue( StatusValue::newGood() ) );
1903 $mocks[$key . $i]->expects( $this->atMost( 1 ) )->method(
'testForAccountCreation' )
1904 ->will( $this->returnValue( StatusValue::newGood() ) );
1908 $mocks[
'primary']->expects( $this->any() )->method(
'accountCreationType' )
1910 $mocks[
'primary']->expects( $this->any() )->method(
'testUserExists' )
1911 ->will( $this->returnValue(
false ) );
1912 $ct = count(
$req->primary );
1915 $this->assertSame(
'UTSysop', $creator->getName() );
1917 foreach ( $reqs
as $r ) {
1918 $this->assertSame(
$username, $r->username );
1919 $foundReq = $foundReq || get_class( $r ) === get_class(
$req );
1921 $this->assertTrue( $foundReq,
'$reqs contains $req' );
1922 return array_shift(
$req->primary );
1924 $mocks[
'primary']->expects( $this->exactly( min( 1, $ct ) ) )
1925 ->method(
'beginPrimaryAccountCreation' )
1926 ->will( $callback );
1927 $mocks[
'primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
1928 ->method(
'continuePrimaryAccountCreation' )
1929 ->will( $callback );
1931 $ct = count(
$req->secondary );
1934 $this->assertSame(
'UTSysop', $creator->getName() );
1936 foreach ( $reqs
as $r ) {
1937 $this->assertSame(
$username, $r->username );
1938 $foundReq = $foundReq || get_class( $r ) === get_class(
$req );
1940 $this->assertTrue( $foundReq,
'$reqs contains $req' );
1941 return array_shift(
$req->secondary );
1943 $mocks[
'secondary']->expects( $this->exactly( min( 1, $ct ) ) )
1944 ->method(
'beginSecondaryAccountCreation' )
1945 ->will( $callback );
1946 $mocks[
'secondary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
1947 ->method(
'continueSecondaryAccountCreation' )
1948 ->will( $callback );
1951 $mocks[
'primary2']->expects( $this->any() )->method(
'accountCreationType' )
1953 $mocks[
'primary2']->expects( $this->any() )->method(
'testUserExists' )
1954 ->will( $this->returnValue(
false ) );
1955 $mocks[
'primary2']->expects( $this->atMost( 1 ) )->method(
'beginPrimaryAccountCreation' )
1956 ->will( $this->returnValue( $abstain ) );
1957 $mocks[
'primary2']->expects( $this->never() )->method(
'continuePrimaryAccountCreation' );
1958 $mocks[
'primary3']->expects( $this->any() )->method(
'accountCreationType' )
1960 $mocks[
'primary3']->expects( $this->any() )->method(
'testUserExists' )
1961 ->will( $this->returnValue(
false ) );
1962 $mocks[
'primary3']->expects( $this->never() )->method(
'beginPrimaryAccountCreation' );
1963 $mocks[
'primary3']->expects( $this->never() )->method(
'continuePrimaryAccountCreation' );
1964 $mocks[
'secondary2']->expects( $this->atMost( 1 ) )
1965 ->method(
'beginSecondaryAccountCreation' )
1966 ->will( $this->returnValue( $abstain ) );
1967 $mocks[
'secondary2']->expects( $this->never() )->method(
'continueSecondaryAccountCreation' );
1968 $mocks[
'secondary3']->expects( $this->atMost( 1 ) )
1969 ->method(
'beginSecondaryAccountCreation' )
1970 ->will( $this->returnValue( $abstain ) );
1971 $mocks[
'secondary3']->expects( $this->never() )->method(
'continueSecondaryAccountCreation' );
1973 $this->preauthMocks = [ $mocks[
'pre'], $mocks[
'pre2'] ];
1974 $this->primaryauthMocks = [ $mocks[
'primary3'], $mocks[
'primary'], $mocks[
'primary2'] ];
1975 $this->secondaryauthMocks = [
1976 $mocks[
'secondary3'], $mocks[
'secondary'], $mocks[
'secondary2']
1979 $this->logger = new \TestLogger(
true,
function ( $message, $level ) {
1980 return $level === LogLevel::DEBUG ? null : $message;
1985 $constraint = \PHPUnit_Framework_Assert::logicalOr(
1989 $providers = array_merge(
1990 $this->preauthMocks, $this->primaryauthMocks, $this->secondaryauthMocks
1992 foreach ( $providers
as $p ) {
1993 $p->postCalled =
false;
1994 $p->expects( $this->atMost( 1 ) )->method(
'postAccountCreation' )
1998 $this->assertInstanceOf(
'User',
$user );
2000 $this->assertSame(
'UTSysop', $creator->getName() );
2001 $this->assertInstanceOf( AuthenticationResponse::class,
$response );
2002 $this->assertThat(
$response->status, $constraint );
2009 $maxLogId = $dbw->selectField(
'logging',
'MAX(log_id)', [
'log_type' =>
'newusers' ] );
2013 foreach ( $managerResponses
as $i =>
$response ) {
2016 if ( $i ===
'created' ) {
2018 $this->
hook(
'LocalUserCreated', $this->once() )
2023 $this->equalTo(
false )
2025 $expectLog[] = [ LogLevel::INFO,
"Creating user {user} during account creation" ];
2027 $this->
hook(
'LocalUserCreated', $this->never() );
2035 $ret = $this->manager->beginAccountCreation(
2036 $creator, [ $userReq,
$req ],
'http://localhost/'
2039 $ret = $this->manager->continueAccountCreation( [
$req ] );
2041 if (
$response instanceof \Exception ) {
2042 $this->fail(
'Expected exception not thrown',
"Response $i" );
2044 }
catch ( \Exception $ex ) {
2045 if ( !
$response instanceof \Exception ) {
2048 $this->assertEquals(
$response->getMessage(), $ex->getMessage(),
"Response $i, exception" );
2050 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' ),
2051 "Response $i, exception, session state"
2053 $this->
unhook(
'LocalUserCreated' );
2057 $this->
unhook(
'LocalUserCreated' );
2059 $this->assertSame(
'http://localhost/',
$req->returnToUrl );
2062 $this->assertNotNull(
$ret->loginRequest,
"Response $i, login marker" );
2063 $this->assertContains(
2064 $ret->loginRequest, $this->managerPriv->createdAccountAuthenticationRequests,
2065 "Response $i, login marker"
2070 "MediaWiki\Auth\AuthManager::continueAccountCreation: Account creation succeeded for {user}"
2078 $this->assertNull(
$ret->loginRequest,
"Response $i, login marker" );
2079 $this->assertSame( [], $this->managerPriv->createdAccountAuthenticationRequests,
2080 "Response $i, login marker" );
2083 $this->assertEquals(
$response,
$ret,
"Response $i, response" );
2086 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' ),
2087 "Response $i, session state"
2089 foreach ( $providers
as $p ) {
2090 $this->assertSame(
$response->status, $p->postCalled,
2091 "Response $i, post-auth callback called" );
2094 $this->assertNotNull(
2095 $this->
request->getSession()->getSecret(
'AuthManager::accountCreationState' ),
2096 "Response $i, session state"
2098 foreach (
$ret->neededRequests
as $neededReq ) {
2100 "Response $i, neededRequest action" );
2102 $this->assertEquals(
2103 $ret->neededRequests,
2105 "Response $i, continuation check"
2107 foreach ( $providers
as $p ) {
2108 $this->assertFalse( $p->postCalled,
"Response $i, post-auth callback not called" );
2113 $this->assertNotEquals( 0, \User::idFromName(
$username ) );
2115 $this->assertEquals( 0, \User::idFromName(
$username ) );
2121 $this->assertSame( $expectLog, $this->logger->getBuffer() );
2125 $dbw->selectField(
'logging',
'MAX(log_id)', [
'log_type' =>
'newusers' ] )
2130 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
2131 $good = StatusValue::newGood();
2134 'Pre-creation test fail in pre' => [
2135 StatusValue::newFatal(
'fail-from-pre' ), $good, $good,
2142 'Pre-creation test fail in primary' => [
2143 $good, StatusValue::newFatal(
'fail-from-primary' ), $good,
2150 'Pre-creation test fail in secondary' => [
2151 $good, $good, StatusValue::newFatal(
'fail-from-secondary' ),
2158 'Failure in primary' => [
2159 $good, $good, $good,
2166 'All primary abstain' => [
2167 $good, $good, $good,
2176 'Primary UI, then redirect, then fail' => [
2177 $good, $good, $good,
2186 'Primary redirect, then abstain' => [
2187 $good, $good, $good,
2190 [
$req ],
'/foo.html', [
'foo' =>
'bar' ]
2197 new \DomainException(
2198 'MockPrimaryAuthenticationProvider::continuePrimaryAccountCreation() returned ABSTAIN'
2202 'Primary UI, then pass; secondary abstain' => [
2203 $good, $good, $good,
2216 'Primary pass; secondary UI then pass' => [
2217 $good, $good, $good,
2230 'Primary pass; secondary fail' => [
2231 $good, $good, $good,
2239 'created' => new \DomainException(
2240 'MockSecondaryAuthenticationProvider::beginSecondaryAccountCreation() returned FAIL. ' .
2241 'Secondary providers are not allowed to fail account creation, ' .
2242 'that should have been done via testForAccountCreation().'
2255 $creator = $isAnon ? new \User : \User::newFromName(
'UTSysop' );
2261 $mock = $this->getMockForAbstractClass(
2262 "MediaWiki\\Auth\\PrimaryAuthenticationProvider", []
2264 $mock->expects( $this->any() )->method(
'getUniqueId' )
2265 ->will( $this->returnValue(
'primary' ) );
2266 $mock->expects( $this->any() )->method(
'testUserForCreation' )
2267 ->will( $this->returnValue( StatusValue::newGood() ) );
2268 $mock->expects( $this->any() )->method(
'testForAccountCreation' )
2269 ->will( $this->returnValue( StatusValue::newGood() ) );
2270 $mock->expects( $this->any() )->method(
'accountCreationType' )
2272 $mock->expects( $this->any() )->method(
'testUserExists' )
2273 ->will( $this->returnValue(
false ) );
2274 $mock->expects( $this->any() )->method(
'beginPrimaryAccountCreation' )
2276 $mock->expects( $this->any() )->method(
'finishAccountCreation' )
2277 ->will( $this->returnValue( $logSubtype ) );
2279 $this->primaryauthMocks = [ $mock ];
2281 $this->logger->setCollect(
true );
2283 $this->config->set(
'NewUserLog',
true );
2286 $maxLogId = $dbw->selectField(
'logging',
'MAX(log_id)', [
'log_type' =>
'newusers' ] );
2291 $reasonReq->reason = $this->toString();
2292 $ret = $this->manager->beginAccountCreation(
2293 $creator, [ $userReq, $reasonReq ],
'http://localhost/'
2299 $this->assertNotEquals( 0,
$user->getId(),
'sanity check' );
2300 $this->assertNotEquals( $creator->getId(),
$user->getId(),
'sanity check' );
2302 $data = \DatabaseLogEntry::getSelectQueryData();
2303 $rows = iterator_to_array( $dbw->select(
2307 'log_id > ' . (
int)$maxLogId,
2308 'log_type' =>
'newusers'
2314 $this->assertCount( 1, $rows );
2315 $entry = \DatabaseLogEntry::newFromRow( reset( $rows ) );
2317 $this->assertSame( $logSubtype ?: ( $isAnon ?
'create' :
'create2' ), $entry->getSubtype() );
2319 $isAnon ?
$user->getId() : $creator->getId(),
2320 $entry->getPerformer()->getId()
2323 $isAnon ?
$user->getName() : $creator->getName(),
2324 $entry->getPerformer()->getName()
2326 $this->assertSame(
$user->getUserPage()->getFullText(), $entry->getTarget()->getFullText() );
2327 $this->assertSame( [
'4::userid' =>
$user->getId() ], $entry->getParameters() );
2328 $this->assertSame( $this->toString(), $entry->getComment() );
2336 [
false,
'byemail' ],
2347 $workaroundPHPUnitBug =
false;
2353 $wgGroupPermissions[
'*'][
'createaccount'] =
true;
2357 $this->
setMwGlobals( [
'wgMainCacheType' => __METHOD__ ] );
2361 foreach ( [
'pre',
'primary',
'secondary' ]
as $key ) {
2362 $class = ucfirst( $key ) .
'AuthenticationProvider';
2363 $mocks[$key] = $this->getMockForAbstractClass(
2364 "MediaWiki\\Auth\\$class", [],
"Mock$class"
2366 $mocks[$key]->expects( $this->any() )->method(
'getUniqueId' )
2367 ->will( $this->returnValue( $key ) );
2370 $good = StatusValue::newGood();
2371 $callback = $this->callback(
function (
$user )
use ( &
$username, &$workaroundPHPUnitBug ) {
2375 $mocks[
'pre']->expects( $this->exactly( 12 ) )->method(
'testUserForCreation' )
2377 ->will( $this->onConsecutiveCalls(
2378 StatusValue::newFatal(
'ok' ), StatusValue::newFatal(
'ok' ),
2379 StatusValue::newFatal(
'fail-in-pre' ), $good, $good,
2387 $mocks[
'primary']->expects( $this->any() )->method(
'accountCreationType' )
2389 $mocks[
'primary']->expects( $this->any() )->method(
'testUserExists' )
2390 ->will( $this->returnValue(
true ) );
2391 $mocks[
'primary']->expects( $this->exactly( 9 ) )->method(
'testUserForCreation' )
2393 ->will( $this->onConsecutiveCalls(
2394 StatusValue::newFatal(
'fail-in-primary' ), $good,
2401 $mocks[
'primary']->expects( $this->exactly( 3 ) )->method(
'autoCreatedAccount' )
2404 $mocks[
'secondary']->expects( $this->exactly( 8 ) )->method(
'testUserForCreation' )
2406 ->will( $this->onConsecutiveCalls(
2407 StatusValue::newFatal(
'fail-in-secondary' ),
2414 $mocks[
'secondary']->expects( $this->exactly( 3 ) )->method(
'autoCreatedAccount' )
2417 $this->preauthMocks = [ $mocks[
'pre'] ];
2418 $this->primaryauthMocks = [ $mocks[
'primary'] ];
2419 $this->secondaryauthMocks = [ $mocks[
'secondary'] ];
2421 $session = $this->
request->getSession();
2423 $logger = new \TestLogger(
true,
function ( $m ) {
2424 $m = str_replace(
'MediaWiki\\Auth\\AuthManager::autoCreateUser: ',
'', $m );
2427 $this->manager->setLogger(
$logger );
2430 $user = \User::newFromName(
'UTSysop' );
2431 $this->manager->autoCreateUser(
$user,
'InvalidSource',
true );
2432 $this->fail(
'Expected exception not thrown' );
2433 }
catch ( \InvalidArgumentException $ex ) {
2434 $this->assertSame(
'Unknown auto-creation source: InvalidSource', $ex->getMessage() );
2439 $user = \User::newFromName(
'UTSysop' );
2440 $this->
hook(
'LocalUserCreated', $this->never() );
2442 $this->
unhook(
'LocalUserCreated' );
2443 $expect = \Status::newGood();
2444 $expect->warning(
'userexists' );
2445 $this->assertEquals( $expect,
$ret );
2446 $this->assertNotEquals( 0,
$user->getId() );
2447 $this->assertSame(
'UTSysop',
$user->getName() );
2448 $this->assertEquals(
$user->getId(), $session->getUser()->getId() );
2449 $this->assertSame( [
2450 [ LogLevel::DEBUG,
'{username} already exists locally' ],
2455 $user = \User::newFromName(
'UTSysop' );
2456 $this->
hook(
'LocalUserCreated', $this->never() );
2458 $this->
unhook(
'LocalUserCreated' );
2459 $expect = \Status::newGood();
2460 $expect->warning(
'userexists' );
2461 $this->assertEquals( $expect,
$ret );
2462 $this->assertNotEquals( 0,
$user->getId() );
2463 $this->assertSame(
'UTSysop',
$user->getName() );
2464 $this->assertEquals( 0, $session->getUser()->getId() );
2465 $this->assertSame( [
2466 [ LogLevel::DEBUG,
'{username} already exists locally' ],
2474 $this->
hook(
'LocalUserCreated', $this->never() );
2476 $this->
unhook(
'LocalUserCreated' );
2477 $this->assertEquals( \Status::newFatal(
'readonlytext',
'Because' ),
$ret );
2478 $this->assertEquals( 0,
$user->getId() );
2480 $this->assertEquals( 0, $session->getUser()->getId() );
2481 $this->assertSame( [
2482 [ LogLevel::DEBUG,
'denied by wfReadOnly(): {reason}' ],
2489 $session->set(
'AuthManager::AutoCreateBlacklist',
'test' );
2491 $this->
hook(
'LocalUserCreated', $this->never() );
2493 $this->
unhook(
'LocalUserCreated' );
2494 $this->assertEquals( \Status::newFatal(
'test' ),
$ret );
2495 $this->assertEquals( 0,
$user->getId() );
2497 $this->assertEquals( 0, $session->getUser()->getId() );
2498 $this->assertSame( [
2499 [ LogLevel::DEBUG,
'blacklisted in session {sessionid}' ],
2504 $session->set(
'AuthManager::AutoCreateBlacklist', StatusValue::newFatal(
'test2' ) );
2506 $this->
hook(
'LocalUserCreated', $this->never() );
2508 $this->
unhook(
'LocalUserCreated' );
2509 $this->assertEquals( \Status::newFatal(
'test2' ),
$ret );
2510 $this->assertEquals( 0,
$user->getId() );
2512 $this->assertEquals( 0, $session->getUser()->getId() );
2513 $this->assertSame( [
2514 [ LogLevel::DEBUG,
'blacklisted in session {sessionid}' ],
2521 $this->
hook(
'LocalUserCreated', $this->never() );
2523 $this->
unhook(
'LocalUserCreated' );
2524 $this->assertEquals( \Status::newFatal(
'noname' ),
$ret );
2525 $this->assertEquals( 0,
$user->getId() );
2527 $this->assertEquals( 0, $session->getUser()->getId() );
2528 $this->assertSame( [
2529 [ LogLevel::DEBUG,
'name "{username}" is not creatable' ],
2532 $this->assertSame(
'noname', $session->get(
'AuthManager::AutoCreateBlacklist' ) );
2539 $this->
hook(
'LocalUserCreated', $this->never() );
2541 $this->
unhook(
'LocalUserCreated' );
2542 $this->assertEquals( \Status::newFatal(
'authmanager-autocreate-noperm' ),
$ret );
2543 $this->assertEquals( 0,
$user->getId() );
2545 $this->assertEquals( 0, $session->getUser()->getId() );
2546 $this->assertSame( [
2547 [ LogLevel::DEBUG,
'IP lacks the ability to create or autocreate accounts' ],
2551 'authmanager-autocreate-noperm', $session->get(
'AuthManager::AutoCreateBlacklist' )
2560 $this->
hook(
'LocalUserCreated', $this->never() );
2562 $this->
unhook(
'LocalUserCreated' );
2563 $this->assertEquals( \Status::newFatal(
'ok' ),
$ret );
2569 $this->
hook(
'LocalUserCreated', $this->never() );
2571 $this->
unhook(
'LocalUserCreated' );
2572 $this->assertEquals( \Status::newFatal(
'ok' ),
$ret );
2578 $this->
hook(
'LocalUserCreated', $this->never() );
2579 $cache = \ObjectCache::getLocalClusterInstance();
2583 $this->
unhook(
'LocalUserCreated' );
2584 $this->assertEquals( \Status::newFatal(
'usernameinprogress' ),
$ret );
2585 $this->assertEquals( 0,
$user->getId() );
2587 $this->assertEquals( 0, $session->getUser()->getId() );
2588 $this->assertSame( [
2589 [ LogLevel::DEBUG,
'Could not acquire account creation lock' ],
2596 $this->
hook(
'LocalUserCreated', $this->never() );
2598 $this->
unhook(
'LocalUserCreated' );
2599 $this->assertEquals( \Status::newFatal(
'fail-in-pre' ),
$ret );
2600 $this->assertEquals( 0,
$user->getId() );
2602 $this->assertEquals( 0, $session->getUser()->getId() );
2603 $this->assertSame( [
2604 [ LogLevel::DEBUG,
'Provider denied creation of {username}: {reason}' ],
2607 $this->assertEquals(
2608 StatusValue::newFatal(
'fail-in-pre' ), $session->get(
'AuthManager::AutoCreateBlacklist' )
2613 $this->
hook(
'LocalUserCreated', $this->never() );
2615 $this->
unhook(
'LocalUserCreated' );
2616 $this->assertEquals( \Status::newFatal(
'fail-in-primary' ),
$ret );
2617 $this->assertEquals( 0,
$user->getId() );
2619 $this->assertEquals( 0, $session->getUser()->getId() );
2620 $this->assertSame( [
2621 [ LogLevel::DEBUG,
'Provider denied creation of {username}: {reason}' ],
2624 $this->assertEquals(
2625 StatusValue::newFatal(
'fail-in-primary' ), $session->get(
'AuthManager::AutoCreateBlacklist' )
2630 $this->
hook(
'LocalUserCreated', $this->never() );
2632 $this->
unhook(
'LocalUserCreated' );
2633 $this->assertEquals( \Status::newFatal(
'fail-in-secondary' ),
$ret );
2634 $this->assertEquals( 0,
$user->getId() );
2636 $this->assertEquals( 0, $session->getUser()->getId() );
2637 $this->assertSame( [
2638 [ LogLevel::DEBUG,
'Provider denied creation of {username}: {reason}' ],
2641 $this->assertEquals(
2642 StatusValue::newFatal(
'fail-in-secondary' ), $session->get(
'AuthManager::AutoCreateBlacklist' )
2646 $cache = \ObjectCache::getLocalClusterInstance();
2648 $cache->set( $backoffKey,
true );
2651 $this->
hook(
'LocalUserCreated', $this->never() );
2653 $this->
unhook(
'LocalUserCreated' );
2654 $this->assertEquals( \Status::newFatal(
'authmanager-autocreate-exception' ),
$ret );
2655 $this->assertEquals( 0,
$user->getId() );
2657 $this->assertEquals( 0, $session->getUser()->getId() );
2658 $this->assertSame( [
2659 [ LogLevel::DEBUG,
'{username} denied by prior creation attempt failures' ],
2662 $this->assertSame(
null, $session->get(
'AuthManager::AutoCreateBlacklist' ) );
2663 $cache->delete( $backoffKey );
2667 $user = $this->getMock(
'User', [
'addToDatabase' ] );
2668 $user->expects( $this->once() )->method(
'addToDatabase' )
2669 ->will( $this->returnValue( \Status::newFatal(
'because' ) ) );
2672 $this->assertEquals( \Status::newFatal(
'because' ),
$ret );
2673 $this->assertEquals( 0,
$user->getId() );
2675 $this->assertEquals( 0, $session->getUser()->getId() );
2676 $this->assertSame( [
2677 [ LogLevel::INFO,
'creating new user ({username}) - from: {from}' ],
2678 [ LogLevel::ERROR,
'{username} failed with message {msg}' ],
2681 $this->assertSame(
null, $session->get(
'AuthManager::AutoCreateBlacklist' ) );
2684 $cache = \ObjectCache::getLocalClusterInstance();
2686 $this->assertFalse(
$cache->get( $backoffKey ),
'sanity check' );
2688 $user = $this->getMock(
'User', [
'addToDatabase' ] );
2689 $user->expects( $this->once() )->method(
'addToDatabase' )
2690 ->will( $this->throwException(
new \Exception(
'Excepted' ) ) );
2694 $this->fail(
'Expected exception not thrown' );
2695 }
catch ( \Exception $ex ) {
2696 $this->assertSame(
'Excepted', $ex->getMessage() );
2698 $this->assertEquals( 0,
$user->getId() );
2699 $this->assertEquals( 0, $session->getUser()->getId() );
2700 $this->assertSame( [
2701 [ LogLevel::INFO,
'creating new user ({username}) - from: {from}' ],
2702 [ LogLevel::ERROR,
'{username} failed with exception {exception}' ],
2705 $this->assertSame(
null, $session->get(
'AuthManager::AutoCreateBlacklist' ) );
2706 $this->assertNotEquals(
false,
$cache->get( $backoffKey ) );
2707 $cache->delete( $backoffKey );
2711 $user = $this->getMock(
'User', [
'addToDatabase' ] );
2712 $user->expects( $this->once() )->method(
'addToDatabase' )
2714 $oldUser = \User::newFromName(
$username );
2715 $status = $oldUser->addToDatabase();
2716 $this->assertTrue(
$status->isOK(),
'sanity check' );
2717 $user->setId( $oldUser->getId() );
2718 return \Status::newFatal(
'userexists' );
2722 $expect = \Status::newGood();
2723 $expect->warning(
'userexists' );
2724 $this->assertEquals( $expect,
$ret );
2725 $this->assertNotEquals( 0,
$user->getId() );
2727 $this->assertEquals(
$user->getId(), $session->getUser()->getId() );
2728 $this->assertSame( [
2729 [ LogLevel::INFO,
'creating new user ({username}) - from: {from}' ],
2730 [ LogLevel::INFO,
'{username} already exists locally (race)' ],
2733 $this->assertSame(
null, $session->get(
'AuthManager::AutoCreateBlacklist' ) );
2739 $this->
hook(
'AuthPluginAutoCreate', $this->once() )
2740 ->with( $callback );
2742 get_class(
$wgHooks[
'AuthPluginAutoCreate'][0] ) .
'::onAuthPluginAutoCreate)' );
2743 $this->
hook(
'LocalUserCreated', $this->once() )
2744 ->with( $callback, $this->equalTo(
true ) );
2746 $this->
unhook(
'LocalUserCreated' );
2747 $this->
unhook(
'AuthPluginAutoCreate' );
2748 $this->assertEquals( \Status::newGood(),
$ret );
2749 $this->assertNotEquals( 0,
$user->getId() );
2751 $this->assertEquals(
$user->getId(), $session->getUser()->getId() );
2752 $this->assertSame( [
2753 [ LogLevel::INFO,
'creating new user ({username}) - from: {from}' ],
2758 $maxLogId = $dbw->selectField(
'logging',
'MAX(log_id)', [
'log_type' =>
'newusers' ] );
2762 $this->
hook(
'LocalUserCreated', $this->once() )
2763 ->with( $callback, $this->equalTo(
true ) );
2765 $this->
unhook(
'LocalUserCreated' );
2766 $this->assertEquals( \Status::newGood(),
$ret );
2767 $this->assertNotEquals( 0,
$user->getId() );
2769 $this->assertEquals( 0, $session->getUser()->getId() );
2770 $this->assertSame( [
2771 [ LogLevel::INFO,
'creating new user ({username}) - from: {from}' ],
2776 $dbw->selectField(
'logging',
'MAX(log_id)', [
'log_type' =>
'newusers' ] )
2779 $this->config->set(
'NewUserLog',
true );
2784 $this->assertEquals( \Status::newGood(),
$ret );
2787 $data = \DatabaseLogEntry::getSelectQueryData();
2788 $rows = iterator_to_array( $dbw->select(
2792 'log_id > ' . (
int)$maxLogId,
2793 'log_type' =>
'newusers'
2799 $this->assertCount( 1, $rows );
2800 $entry = \DatabaseLogEntry::newFromRow( reset( $rows ) );
2802 $this->assertSame(
'autocreate', $entry->getSubtype() );
2803 $this->assertSame(
$user->getId(), $entry->getPerformer()->getId() );
2804 $this->assertSame(
$user->getName(), $entry->getPerformer()->getName() );
2805 $this->assertSame(
$user->getUserPage()->getFullText(), $entry->getTarget()->getFullText() );
2806 $this->assertSame( [
'4::userid' =>
$user->getId() ], $entry->getParameters() );
2808 $workaroundPHPUnitBug =
true;
2818 $makeReq =
function ( $key )
use ( $action ) {
2819 $req = $this->getMock( AuthenticationRequest::class );
2820 $req->expects( $this->any() )->method(
'getUniqueId' )
2821 ->will( $this->returnValue( $key ) );
2826 $cmpReqs =
function ( $a, $b ) {
2827 $ret = strcmp( get_class( $a ), get_class( $b ) );
2829 $ret = strcmp( $a->key, $b->key );
2834 $good = StatusValue::newGood();
2837 foreach ( [
'pre',
'primary',
'secondary' ]
as $key ) {
2838 $class = ucfirst( $key ) .
'AuthenticationProvider';
2839 $mocks[$key] = $this->getMockForAbstractClass(
2840 "MediaWiki\\Auth\\$class", [],
"Mock$class"
2842 $mocks[$key]->expects( $this->any() )->method(
'getUniqueId' )
2843 ->will( $this->returnValue( $key ) );
2844 $mocks[$key]->expects( $this->any() )->method(
'getAuthenticationRequests' )
2845 ->will( $this->returnCallback(
function ( $action )
use ( $key, $makeReq ) {
2846 return [ $makeReq(
"$key-$action" ), $makeReq(
'generic' ) ];
2848 $mocks[$key]->expects( $this->any() )->method(
'providerAllowsAuthenticationDataChange' )
2849 ->will( $this->returnValue( $good ) );
2858 $class =
'PrimaryAuthenticationProvider';
2859 $mocks[
"primary-$type"] = $this->getMockForAbstractClass(
2860 "MediaWiki\\Auth\\$class", [],
"Mock$class"
2862 $mocks[
"primary-$type"]->expects( $this->any() )->method(
'getUniqueId' )
2863 ->will( $this->returnValue(
"primary-$type" ) );
2864 $mocks[
"primary-$type"]->expects( $this->any() )->method(
'accountCreationType' )
2865 ->will( $this->returnValue(
$type ) );
2866 $mocks[
"primary-$type"]->expects( $this->any() )->method(
'getAuthenticationRequests' )
2867 ->will( $this->returnCallback(
function ( $action )
use (
$type, $makeReq ) {
2868 return [ $makeReq(
"primary-$type-$action" ), $makeReq(
'generic' ) ];
2870 $mocks[
"primary-$type"]->expects( $this->any() )
2871 ->method(
'providerAllowsAuthenticationDataChange' )
2872 ->will( $this->returnValue( $good ) );
2873 $this->primaryauthMocks[] = $mocks[
"primary-$type"];
2876 $mocks[
'primary2'] = $this->getMockForAbstractClass(
2877 PrimaryAuthenticationProvider::class, [],
"MockPrimaryAuthenticationProvider"
2879 $mocks[
'primary2']->expects( $this->any() )->method(
'getUniqueId' )
2880 ->will( $this->returnValue(
'primary2' ) );
2881 $mocks[
'primary2']->expects( $this->any() )->method(
'accountCreationType' )
2883 $mocks[
'primary2']->expects( $this->any() )->method(
'getAuthenticationRequests' )
2884 ->will( $this->returnValue( [] ) );
2885 $mocks[
'primary2']->expects( $this->any() )
2886 ->method(
'providerAllowsAuthenticationDataChange' )
2887 ->will( $this->returnCallback(
function (
$req )
use ( $good ) {
2888 return $req->key ===
'generic' ? StatusValue::newFatal(
'no' ) : $good;
2890 $this->primaryauthMocks[] = $mocks[
'primary2'];
2892 $this->preauthMocks = [ $mocks[
'pre'] ];
2893 $this->secondaryauthMocks = [ $mocks[
'secondary'] ];
2897 if ( isset( $state[
'continueRequests'] ) ) {
2898 $state[
'continueRequests'] = array_map( $makeReq, $state[
'continueRequests'] );
2901 $this->
request->getSession()->setSecret(
'AuthManager::authnState', $state );
2903 $this->
request->getSession()->setSecret(
'AuthManager::accountCreationState', $state );
2905 $this->
request->getSession()->setSecret(
'AuthManager::accountLinkState', $state );
2909 $expectReqs = array_map( $makeReq, $expect );
2912 $req->action = $action;
2914 $expectReqs[] =
$req;
2917 $req->action = $action;
2918 $expectReqs[] =
$req;
2920 $req->action = $action;
2922 $expectReqs[] =
$req;
2924 usort( $expectReqs, $cmpReqs );
2926 $actual = $this->manager->getAuthenticationRequests( $action );
2927 foreach ( $actual
as $req ) {
2931 usort( $actual, $cmpReqs );
2933 $this->assertEquals( $expectReqs, $actual );
2938 $req->action = $action;
2940 $expectReqs[] =
$req;
2941 usort( $expectReqs, $cmpReqs );
2943 $actual = $this->manager->getAuthenticationRequests( $action, \User::newFromName(
'UTSysop' ) );
2944 foreach ( $actual
as $req ) {
2948 usort( $actual, $cmpReqs );
2950 $this->assertEquals( $expectReqs, $actual );
2958 [
'pre-login',
'primary-none-login',
'primary-create-login',
2959 'primary-link-login',
'secondary-login',
'generic' ],
2963 [
'pre-create',
'primary-none-create',
'primary-create-create',
2964 'primary-link-create',
'secondary-create',
'generic' ],
2968 [
'primary-link-link',
'generic' ],
2972 [
'primary-none-change',
'primary-create-change',
'primary-link-change',
2973 'secondary-change' ],
2977 [
'primary-none-remove',
'primary-create-remove',
'primary-link-remove',
2978 'secondary-remove' ],
2982 [
'primary-link-remove' ],
2990 $reqs = [
'continue-login',
'foo',
'bar' ],
2992 'continueRequests' => $reqs,
3001 $reqs = [
'continue-create',
'foo',
'bar' ],
3003 'continueRequests' => $reqs,
3012 $reqs = [
'continue-link',
'foo',
'bar' ],
3014 'continueRequests' => $reqs,
3021 $makeReq =
function ( $key, $required ) {
3022 $req = $this->getMock( AuthenticationRequest::class );
3023 $req->expects( $this->any() )->method(
'getUniqueId' )
3024 ->will( $this->returnValue( $key ) );
3027 $req->required = $required;
3030 $cmpReqs =
function ( $a, $b ) {
3031 $ret = strcmp( get_class( $a ), get_class( $b ) );
3033 $ret = strcmp( $a->key, $b->key );
3038 $good = StatusValue::newGood();
3040 $primary1 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3041 $primary1->expects( $this->any() )->method(
'getUniqueId' )
3042 ->will( $this->returnValue(
'primary1' ) );
3043 $primary1->expects( $this->any() )->method(
'accountCreationType' )
3045 $primary1->expects( $this->any() )->method(
'getAuthenticationRequests' )
3046 ->will( $this->returnCallback(
function ( $action )
use ( $makeReq ) {
3057 $primary2 = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3058 $primary2->expects( $this->any() )->method(
'getUniqueId' )
3059 ->will( $this->returnValue(
'primary2' ) );
3060 $primary2->expects( $this->any() )->method(
'accountCreationType' )
3062 $primary2->expects( $this->any() )->method(
'getAuthenticationRequests' )
3063 ->will( $this->returnCallback(
function ( $action )
use ( $makeReq ) {
3071 $secondary = $this->getMockForAbstractClass( SecondaryAuthenticationProvider::class );
3072 $secondary->expects( $this->any() )->method(
'getUniqueId' )
3073 ->will( $this->returnValue(
'secondary' ) );
3074 $secondary->expects( $this->any() )->method(
'getAuthenticationRequests' )
3075 ->will( $this->returnCallback(
function ( $action )
use ( $makeReq ) {
3086 $this->primaryauthMocks = [ $primary1, $primary2 ];
3087 $this->secondaryauthMocks = [ $secondary ];
3102 usort( $actual, $cmpReqs );
3103 usort( $expected, $cmpReqs );
3104 $this->assertEquals( $expected, $actual );
3106 $this->primaryauthMocks = [ $primary1 ];
3107 $this->secondaryauthMocks = [ $secondary ];
3120 usort( $actual, $cmpReqs );
3121 usort( $expected, $cmpReqs );
3122 $this->assertEquals( $expected, $actual );
3127 foreach ( [
'primary',
'secondary' ]
as $key ) {
3128 $class = ucfirst( $key ) .
'AuthenticationProvider';
3129 $mocks[$key] = $this->getMockForAbstractClass(
3130 "MediaWiki\\Auth\\$class", [],
"Mock$class"
3132 $mocks[$key]->expects( $this->any() )->method(
'getUniqueId' )
3133 ->will( $this->returnValue( $key ) );
3134 $mocks[$key]->expects( $this->any() )->method(
'providerAllowsPropertyChange' )
3135 ->will( $this->returnCallback(
function ( $prop )
use ( $key ) {
3136 return $prop !== $key;
3140 $this->primaryauthMocks = [ $mocks[
'primary'] ];
3141 $this->secondaryauthMocks = [ $mocks[
'secondary'] ];
3144 $this->assertTrue( $this->manager->allowsPropertyChange(
'foo' ) );
3145 $this->assertFalse( $this->manager->allowsPropertyChange(
'primary' ) );
3146 $this->assertFalse( $this->manager->allowsPropertyChange(
'secondary' ) );
3152 $req = $this->getMock( AuthenticationRequest::class );
3154 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3155 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'primary' ) );
3156 $mock->expects( $this->any() )->method(
'beginPrimaryAuthentication' )
3158 $mock->expects( $this->any() )->method(
'accountCreationType' )
3160 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
true ) );
3161 $mock->expects( $this->any() )->method(
'testUserForCreation' )
3162 ->will( $this->returnValue( StatusValue::newGood() ) );
3164 $mock2 = $this->getMockForAbstractClass( SecondaryAuthenticationProvider::class );
3165 $mock2->expects( $this->any() )->method(
'getUniqueId' )
3166 ->will( $this->returnValue(
'secondary' ) );
3167 $mock2->expects( $this->any() )->method(
'beginSecondaryAuthentication' )->will(
3172 $mock2->expects( $this->any() )->method(
'continueSecondaryAuthentication' )
3174 $mock2->expects( $this->any() )->method(
'testUserForCreation' )
3175 ->will( $this->returnValue( StatusValue::newGood() ) );
3177 $this->primaryauthMocks = [ $mock ];
3178 $this->secondaryauthMocks = [ $mock2 ];
3180 $this->manager->setLogger(
new \Psr\Log\NullLogger() );
3181 $session = $this->
request->getSession();
3184 $this->assertSame( 0, \User::newFromName(
$username )->getId(),
3191 $this->
hook(
'UserLoggedIn', $this->never() );
3192 $this->hook(
'LocalUserCreated', $this->once() )->with( $callback, $this->equalTo(
true ) );
3193 $ret = $this->manager->beginAuthentication( [],
'http://localhost/' );
3194 $this->
unhook(
'LocalUserCreated' );
3195 $this->
unhook(
'UserLoggedIn' );
3198 $id = (int)\User::newFromName(
$username )->getId();
3199 $this->assertNotSame( 0, \User::newFromName(
$username )->getId() );
3200 $this->assertSame( 0, $session->getUser()->getId() );
3202 $this->hook(
'UserLoggedIn', $this->once() )->with( $callback );
3203 $this->hook(
'LocalUserCreated', $this->never() );
3204 $ret = $this->manager->continueAuthentication( [] );
3205 $this->
unhook(
'LocalUserCreated' );
3206 $this->
unhook(
'UserLoggedIn' );
3209 $this->assertSame( $id, $session->getUser()->getId() );
3215 $mock = $this->getMockForAbstractClass(
3216 PrimaryAuthenticationProvider::class, [],
"MockPrimaryAuthenticationProvider" );
3217 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'primary' ) );
3218 $mock->expects( $this->any() )->method(
'beginPrimaryAuthentication' )
3220 $mock->expects( $this->any() )->method(
'accountCreationType' )
3222 $mock->expects( $this->any() )->method(
'testUserExists' )->will( $this->returnValue(
true ) );
3223 $mock->expects( $this->any() )->method(
'testUserForCreation' )
3224 ->will( $this->returnValue( StatusValue::newFatal(
'fail-from-primary' ) ) );
3226 $this->primaryauthMocks = [ $mock ];
3228 $this->manager->setLogger(
new \Psr\Log\NullLogger() );
3229 $session = $this->
request->getSession();
3232 $this->assertSame( 0, $session->getUser()->getId(),
3234 $this->assertSame( 0, \User::newFromName(
$username )->getId(),
3237 $this->
hook(
'UserLoggedIn', $this->never() );
3238 $this->
hook(
'LocalUserCreated', $this->never() );
3239 $ret = $this->manager->beginAuthentication( [],
'http://localhost/' );
3240 $this->
unhook(
'LocalUserCreated' );
3241 $this->
unhook(
'UserLoggedIn' );
3243 $this->assertSame(
'authmanager-authn-autocreate-failed',
$ret->message->getKey() );
3245 $this->assertSame( 0, \User::newFromName(
$username )->getId() );
3246 $this->assertSame( 0, $session->getUser()->getId() );
3252 $this->assertNull( $this->manager->getAuthenticationSessionData(
'foo' ) );
3253 $this->manager->setAuthenticationSessionData(
'foo',
'foo!' );
3254 $this->manager->setAuthenticationSessionData(
'bar',
'bar!' );
3255 $this->assertSame(
'foo!', $this->manager->getAuthenticationSessionData(
'foo' ) );
3256 $this->assertSame(
'bar!', $this->manager->getAuthenticationSessionData(
'bar' ) );
3257 $this->manager->removeAuthenticationSessionData(
'foo' );
3258 $this->assertNull( $this->manager->getAuthenticationSessionData(
'foo' ) );
3259 $this->assertSame(
'bar!', $this->manager->getAuthenticationSessionData(
'bar' ) );
3260 $this->manager->removeAuthenticationSessionData(
'bar' );
3261 $this->assertNull( $this->manager->getAuthenticationSessionData(
'bar' ) );
3263 $this->manager->setAuthenticationSessionData(
'foo',
'foo!' );
3264 $this->manager->setAuthenticationSessionData(
'bar',
'bar!' );
3265 $this->manager->removeAuthenticationSessionData(
null );
3266 $this->assertNull( $this->manager->getAuthenticationSessionData(
'foo' ) );
3267 $this->assertNull( $this->manager->getAuthenticationSessionData(
'bar' ) );
3278 foreach ( $types
as $type => $can ) {
3279 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3280 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
$type ) );
3281 $mock->expects( $this->any() )->method(
'accountCreationType' )
3282 ->will( $this->returnValue(
$type ) );
3283 $this->primaryauthMocks = [ $mock ];
3285 $this->assertSame( $can, $this->manager->canCreateAccounts(),
$type );
3290 $user = \User::newFromName(
'UTSysop' );
3293 $this->
request->getSession()->setSecret(
'AuthManager::accountLinkState',
'test' );
3295 $this->manager->beginAccountLink(
$user, [],
'http://localhost/' );
3296 $this->fail(
'Expected exception not thrown' );
3297 }
catch ( \LogicException $ex ) {
3298 $this->assertEquals(
'Account linking is not possible', $ex->getMessage() );
3300 $this->assertNull( $this->
request->getSession()->getSecret(
'AuthManager::accountLinkState' ) );
3302 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3303 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
3304 $mock->expects( $this->any() )->method(
'accountCreationType' )
3306 $this->primaryauthMocks = [ $mock ];
3309 $ret = $this->manager->beginAccountLink(
new \
User, [],
'http://localhost/' );
3311 $this->assertSame(
'noname',
$ret->message->getKey() );
3313 $ret = $this->manager->beginAccountLink(
3314 \User::newFromName(
'UTDoesNotExist' ), [],
'http://localhost/'
3317 $this->assertSame(
'authmanager-userdoesnotexist',
$ret->message->getKey() );
3321 $user = \User::newFromName(
'UTSysop' );
3325 'userid' =>
$user->getId(),
3326 'username' =>
$user->getName(),
3331 $this->manager->continueAccountLink( [] );
3332 $this->fail(
'Expected exception not thrown' );
3333 }
catch ( \LogicException $ex ) {
3334 $this->assertEquals(
'Account linking is not possible', $ex->getMessage() );
3337 $mock = $this->getMockForAbstractClass( PrimaryAuthenticationProvider::class );
3338 $mock->expects( $this->any() )->method(
'getUniqueId' )->will( $this->returnValue(
'X' ) );
3339 $mock->expects( $this->any() )->method(
'accountCreationType' )
3341 $mock->expects( $this->any() )->method(
'beginPrimaryAccountLink' )->will(
3344 $this->primaryauthMocks = [ $mock ];
3347 $this->
request->getSession()->setSecret(
'AuthManager::accountLinkState',
null );
3348 $ret = $this->manager->continueAccountLink( [] );
3350 $this->assertSame(
'authmanager-link-not-in-progress',
$ret->message->getKey() );
3352 $this->
request->getSession()->setSecret(
'AuthManager::accountLinkState',
3353 [
'username' =>
$user->getName() .
'<>' ] + $session );
3354 $ret = $this->manager->continueAccountLink( [] );
3356 $this->assertSame(
'noname',
$ret->message->getKey() );
3357 $this->assertNull( $this->
request->getSession()->getSecret(
'AuthManager::accountLinkState' ) );
3359 $id =
$user->getId();
3360 $this->
request->getSession()->setSecret(
'AuthManager::accountLinkState',
3361 [
'userid' => $id + 1 ] + $session );
3363 $ret = $this->manager->continueAccountLink( [] );
3364 $this->fail(
'Expected exception not thrown' );
3365 }
catch ( \UnexpectedValueException $ex ) {
3366 $this->assertEquals(
3367 "User \"{$user->getName()}\" is valid, but ID $id != " . ( $id + 1 ) .
'!',
3371 $this->assertNull( $this->
request->getSession()->getSecret(
'AuthManager::accountLinkState' ) );
3383 $user = \User::newFromName(
'UTSysop' );
3388 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
3389 $req->primary = $primaryResponses;
3392 foreach ( [
'pre',
'primary' ]
as $key ) {
3393 $class = ucfirst( $key ) .
'AuthenticationProvider';
3394 $mocks[$key] = $this->getMockForAbstractClass(
3395 "MediaWiki\\Auth\\$class", [],
"Mock$class"
3397 $mocks[$key]->expects( $this->any() )->method(
'getUniqueId' )
3398 ->will( $this->returnValue( $key ) );
3400 for ( $i = 2; $i <= 3; $i++ ) {
3401 $mocks[$key . $i] = $this->getMockForAbstractClass(
3402 "MediaWiki\\Auth\\$class", [],
"Mock$class"
3404 $mocks[$key . $i]->expects( $this->any() )->method(
'getUniqueId' )
3405 ->will( $this->returnValue( $key . $i ) );
3409 $mocks[
'pre']->expects( $this->any() )->method(
'testForAccountLink' )
3410 ->will( $this->returnCallback(
3414 $this->assertSame(
$user->getId(), $u->getId() );
3415 $this->assertSame(
$user->getName(), $u->getName() );
3420 $mocks[
'pre2']->expects( $this->atMost( 1 ) )->method(
'testForAccountLink' )
3421 ->will( $this->returnValue( StatusValue::newGood() ) );
3423 $mocks[
'primary']->expects( $this->any() )->method(
'accountCreationType' )
3425 $ct = count(
$req->primary );
3426 $callback = $this->returnCallback(
function ( $u, $reqs )
use (
$user,
$req ) {
3427 $this->assertSame(
$user->getId(), $u->getId() );
3428 $this->assertSame(
$user->getName(), $u->getName() );
3430 foreach ( $reqs
as $r ) {
3431 $this->assertSame(
$user->getName(), $r->username );
3432 $foundReq = $foundReq || get_class( $r ) === get_class(
$req );
3434 $this->assertTrue( $foundReq,
'$reqs contains $req' );
3435 return array_shift(
$req->primary );
3437 $mocks[
'primary']->expects( $this->exactly( min( 1, $ct ) ) )
3438 ->method(
'beginPrimaryAccountLink' )
3439 ->will( $callback );
3440 $mocks[
'primary']->expects( $this->exactly( max( 0, $ct - 1 ) ) )
3441 ->method(
'continuePrimaryAccountLink' )
3442 ->will( $callback );
3445 $mocks[
'primary2']->expects( $this->any() )->method(
'accountCreationType' )
3447 $mocks[
'primary2']->expects( $this->atMost( 1 ) )->method(
'beginPrimaryAccountLink' )
3448 ->will( $this->returnValue( $abstain ) );
3449 $mocks[
'primary2']->expects( $this->never() )->method(
'continuePrimaryAccountLink' );
3450 $mocks[
'primary3']->expects( $this->any() )->method(
'accountCreationType' )
3452 $mocks[
'primary3']->expects( $this->never() )->method(
'beginPrimaryAccountLink' );
3453 $mocks[
'primary3']->expects( $this->never() )->method(
'continuePrimaryAccountLink' );
3455 $this->preauthMocks = [ $mocks[
'pre'], $mocks[
'pre2'] ];
3456 $this->primaryauthMocks = [ $mocks[
'primary3'], $mocks[
'primary2'], $mocks[
'primary'] ];
3457 $this->logger = new \TestLogger(
true,
function ( $message, $level ) {
3458 return $level === LogLevel::DEBUG ? null : $message;
3462 $constraint = \PHPUnit_Framework_Assert::logicalOr(
3466 $providers = array_merge( $this->preauthMocks, $this->primaryauthMocks );
3467 foreach ( $providers
as $p ) {
3468 $p->postCalled =
false;
3469 $p->expects( $this->atMost( 1 ) )->method(
'postAccountLink' )
3471 $this->assertInstanceOf(
'User',
$user );
3472 $this->assertSame(
'UTSysop',
$user->getName() );
3473 $this->assertInstanceOf( AuthenticationResponse::class,
$response );
3474 $this->assertThat(
$response->status, $constraint );
3482 foreach ( $managerResponses
as $i =>
$response ) {
3486 $expectLog[] = [ LogLevel::INFO,
'Account linked to {user} by primary' ];
3492 $ret = $this->manager->beginAccountLink(
$user, [
$req ],
'http://localhost/' );
3494 $ret = $this->manager->continueAccountLink( [
$req ] );
3496 if (
$response instanceof \Exception ) {
3497 $this->fail(
'Expected exception not thrown',
"Response $i" );
3499 }
catch ( \Exception $ex ) {
3500 if ( !
$response instanceof \Exception ) {
3503 $this->assertEquals(
$response->getMessage(), $ex->getMessage(),
"Response $i, exception" );
3504 $this->assertNull( $this->
request->getSession()->getSecret(
'AuthManager::accountLinkState' ),
3505 "Response $i, exception, session state" );
3509 $this->assertSame(
'http://localhost/',
$req->returnToUrl );
3512 $this->assertEquals(
$response,
$ret,
"Response $i, response" );
3516 $this->assertNull( $this->
request->getSession()->getSecret(
'AuthManager::accountLinkState' ),
3517 "Response $i, session state" );
3518 foreach ( $providers
as $p ) {
3519 $this->assertSame(
$response->status, $p->postCalled,
3520 "Response $i, post-auth callback called" );
3523 $this->assertNotNull(
3524 $this->
request->getSession()->getSecret(
'AuthManager::accountLinkState' ),
3525 "Response $i, session state"
3527 foreach (
$ret->neededRequests
as $neededReq ) {
3529 "Response $i, neededRequest action" );
3531 $this->assertEquals(
3532 $ret->neededRequests,
3534 "Response $i, continuation check"
3536 foreach ( $providers
as $p ) {
3537 $this->assertFalse( $p->postCalled,
"Response $i, post-auth callback not called" );
3544 $this->assertSame( $expectLog, $this->logger->getBuffer() );
3548 $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
3549 $good = StatusValue::newGood();
3552 'Pre-link test fail in pre' => [
3553 StatusValue::newFatal(
'fail-from-pre' ),
3559 'Failure in primary' => [
3566 'All primary abstain' => [
3575 'Primary UI, then redirect, then fail' => [
3584 'Primary redirect, then abstain' => [
3588 [
$req ],
'/foo.html', [
'foo' =>
'bar' ]
3594 new \DomainException(
3595 'MockPrimaryAuthenticationProvider::continuePrimaryAccountLink() returned ABSTAIN'
3599 'Primary UI, then pass' => [
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
</td >< td > &</td >< td > t want your writing to be edited mercilessly and redistributed at will
$wgGroupPermissions
Permission keys given to users in each group.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfMemcKey()
Make a cache key for the local wiki.
Simple store for keeping values in an associative array for the current process.
static BagOStuff[] $instances
Map of (id => BagOStuff)
static getMain()
Static methods.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Circumvent access restrictions on object internals.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
when a variable name is used in a it is silently declared as a new local masking the global
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such and we might be restricted by PHP settings such as safe mode or open_basedir We cannot assume that the software even has read access anywhere useful Many shared hosts run all users web applications under the same so they can t rely on Unix and must forbid reads to even standard directories like tmp lest users read each others files We cannot assume that the user has the ability to install or run any programs not written as web accessible PHP scripts Since anything that works on cheap shared hosting will work if you have shell or root access MediaWiki s design is based around catering to the lowest common denominator Although we support higher end setups as the way many things work by default is tailored toward shared hosting These defaults are unconventional from the point of view of and they certainly aren t ideal for someone who s installing MediaWiki as MediaWiki does not conform to normal Unix filesystem layout Hopefully we ll offer direct support for standard layouts in the but for now *any change to the location of files is unsupported *Moving things and leaving symlinks will *probably *not break anything
this hook is for auditing only $req
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
namespace are movable Hooks may change this value to override the return value of MWNamespace::isMovable(). 'NewDifferenceEngine' do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached one of or reset my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
see documentation in includes Linker php for Linker::makeImageLink & $time
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
returning false will NOT prevent logging a wrapping ErrorException instead of letting the login form give the generic error message that the account does not exist For when the account has been renamed or deleted or an array to pass a message key and parameters create2 Corresponds to logging log_action database field and which is displayed in the UI similar to $comment this hook should only be used to add variables that depend on the current page request
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
usually copyright or history_copyright This message must be in HTML not wikitext & $link
$wgHooks['ArticleShow'][]
this hook is for auditing only or null if authentication failed before getting that far $username
this hook is for auditing only $response
Allows to change the fields on the form that will be generated $name
processing should stop and the error should be shown to the user * false
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Interface for configuration instances.
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".