wiki.techinc.nl/tests/phpunit/includes/session/SessionProviderTest.php

229 lines
7.3 KiB
PHP
Raw Normal View History

<?php
namespace MediaWiki\Session;
use MediaWiki\MediaWikiServices;
use MediaWiki\User\UserNameUtils;
use MediaWikiIntegrationTestCase;
use TestLogger;
use Wikimedia\TestingAccessWrapper;
/**
* @group Session
* @group Database
* @covers MediaWiki\Session\SessionProvider
*/
class SessionProviderTest extends MediaWikiIntegrationTestCase {
use SessionProviderTestTrait;
public function testBasics() {
$this->hideDeprecated( 'MediaWiki\Session\SessionProvider::setConfig' );
$this->hideDeprecated( 'MediaWiki\Session\SessionProvider::setLogger' );
$this->hideDeprecated( 'MediaWiki\Session\SessionProvider::setManager' );
$this->hideDeprecated( 'MediaWiki\Session\SessionProvider::setHookContainer' );
$manager = new SessionManager();
$logger = new TestLogger();
$config = new \HashConfig();
Hooks::run() call site migration Migrate all callers of Hooks::run() to use the new HookContainer/HookRunner system. General principles: * Use DI if it is already used. We're not changing the way state is managed in this patch. * HookContainer is always injected, not HookRunner. HookContainer is a service, it's a more generic interface, it is the only thing that provides isRegistered() which is needed in some cases, and a HookRunner can be efficiently constructed from it (confirmed by benchmark). Because HookContainer is needed for object construction, it is also needed by all factories. * "Ask your friendly local base class". Big hierarchies like SpecialPage and ApiBase have getHookContainer() and getHookRunner() methods in the base class, and classes that extend that base class are not expected to know or care where the base class gets its HookContainer from. * ProtectedHookAccessorTrait provides protected getHookContainer() and getHookRunner() methods, getting them from the global service container. The point of this is to ease migration to DI by ensuring that call sites ask their local friendly base class rather than getting a HookRunner from the service container directly. * Private $this->hookRunner. In some smaller classes where accessor methods did not seem warranted, there is a private HookRunner property which is accessed directly. Very rarely (two cases), there is a protected property, for consistency with code that conventionally assumes protected=private, but in cases where the class might actually be overridden, a protected accessor is preferred over a protected property. * The last resort: Hooks::runner(). Mostly for static, file-scope and global code. In a few cases it was used for objects with broken construction schemes, out of horror or laziness. Constructors with new required arguments: * AuthManager * BadFileLookup * BlockManager * ClassicInterwikiLookup * ContentHandlerFactory * ContentSecurityPolicy * DefaultOptionsManager * DerivedPageDataUpdater * FullSearchResultWidget * HtmlCacheUpdater * LanguageFactory * LanguageNameUtils * LinkRenderer * LinkRendererFactory * LocalisationCache * MagicWordFactory * MessageCache * NamespaceInfo * PageEditStash * PageHandlerFactory * PageUpdater * ParserFactory * PermissionManager * RevisionStore * RevisionStoreFactory * SearchEngineConfig * SearchEngineFactory * SearchFormWidget * SearchNearMatcher * SessionBackend * SpecialPageFactory * UserNameUtils * UserOptionsManager * WatchedItemQueryService * WatchedItemStore Constructors with new optional arguments: * DefaultPreferencesFactory * Language * LinkHolderArray * MovePage * Parser * ParserCache * PasswordReset * Router setHookContainer() now required after construction: * AuthenticationProvider * ResourceLoaderModule * SearchEngine Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
$hookContainer = $this->createHookContainer();
$userNameUtils = $this->createNoOpMock( UserNameUtils::class );
$provider = $this->getMockForAbstractClass( SessionProvider::class );
$priv = TestingAccessWrapper::newFromObject( $provider );
$this->initProvider( $provider, $logger, $config, $manager, $hookContainer, $userNameUtils );
$this->assertSame( $logger, $priv->logger );
$this->assertSame( $config, $priv->getConfig() );
$this->assertSame( $manager, $priv->manager );
$this->assertSame( $manager, $provider->getManager() );
$this->assertSame( $hookContainer, $priv->getHookContainer() );
$this->assertSame( $userNameUtils, $priv->userNameUtils );
$provider->setConfig( $config );
$this->assertSame( $config, $priv->getConfig() );
$provider->setLogger( $logger );
$this->assertSame( $logger, $priv->logger );
$provider->setManager( $manager );
$this->assertSame( $manager, $priv->manager );
$this->assertSame( $manager, $provider->getManager() );
Hooks::run() call site migration Migrate all callers of Hooks::run() to use the new HookContainer/HookRunner system. General principles: * Use DI if it is already used. We're not changing the way state is managed in this patch. * HookContainer is always injected, not HookRunner. HookContainer is a service, it's a more generic interface, it is the only thing that provides isRegistered() which is needed in some cases, and a HookRunner can be efficiently constructed from it (confirmed by benchmark). Because HookContainer is needed for object construction, it is also needed by all factories. * "Ask your friendly local base class". Big hierarchies like SpecialPage and ApiBase have getHookContainer() and getHookRunner() methods in the base class, and classes that extend that base class are not expected to know or care where the base class gets its HookContainer from. * ProtectedHookAccessorTrait provides protected getHookContainer() and getHookRunner() methods, getting them from the global service container. The point of this is to ease migration to DI by ensuring that call sites ask their local friendly base class rather than getting a HookRunner from the service container directly. * Private $this->hookRunner. In some smaller classes where accessor methods did not seem warranted, there is a private HookRunner property which is accessed directly. Very rarely (two cases), there is a protected property, for consistency with code that conventionally assumes protected=private, but in cases where the class might actually be overridden, a protected accessor is preferred over a protected property. * The last resort: Hooks::runner(). Mostly for static, file-scope and global code. In a few cases it was used for objects with broken construction schemes, out of horror or laziness. Constructors with new required arguments: * AuthManager * BadFileLookup * BlockManager * ClassicInterwikiLookup * ContentHandlerFactory * ContentSecurityPolicy * DefaultOptionsManager * DerivedPageDataUpdater * FullSearchResultWidget * HtmlCacheUpdater * LanguageFactory * LanguageNameUtils * LinkRenderer * LinkRendererFactory * LocalisationCache * MagicWordFactory * MessageCache * NamespaceInfo * PageEditStash * PageHandlerFactory * PageUpdater * ParserFactory * PermissionManager * RevisionStore * RevisionStoreFactory * SearchEngineConfig * SearchEngineFactory * SearchFormWidget * SearchNearMatcher * SessionBackend * SpecialPageFactory * UserNameUtils * UserOptionsManager * WatchedItemQueryService * WatchedItemStore Constructors with new optional arguments: * DefaultPreferencesFactory * Language * LinkHolderArray * MovePage * Parser * ParserCache * PasswordReset * Router setHookContainer() now required after construction: * AuthenticationProvider * ResourceLoaderModule * SearchEngine Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
$provider->setHookContainer( $hookContainer );
$this->assertSame( $hookContainer, $priv->getHookContainer() );
$provider->invalidateSessionsForUser( new \User );
$this->assertSame( [], $provider->getVaryHeaders() );
$this->assertSame( [], $provider->getVaryCookies() );
$this->assertSame( null, $provider->suggestLoginUsername( new \FauxRequest ) );
$this->assertSame( get_class( $provider ), (string)$provider );
$this->assertNull( $provider->getRememberUserDuration() );
$this->assertNull( $provider->whyNoSession() );
$this->assertFalse( $provider->safeAgainstCsrf() );
$info = new SessionInfo( SessionInfo::MIN_PRIORITY, [
'id' => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
'provider' => $provider,
] );
$metadata = [ 'foo' ];
$this->assertTrue( $provider->refreshSessionInfo( $info, new \FauxRequest, $metadata ) );
$this->assertSame( [ 'foo' ], $metadata );
}
/**
* @dataProvider provideNewSessionInfo
* @param bool $persistId Return value for ->persistsSessionId()
* @param bool $persistUser Return value for ->persistsSessionUser()
* @param bool $ok Whether a SessionInfo is provided
*/
public function testNewSessionInfo( $persistId, $persistUser, $ok ) {
$manager = new SessionManager();
$provider = $this->getMockBuilder( SessionProvider::class )
->onlyMethods( [ 'canChangeUser', 'persistsSessionId' ] )
->getMockForAbstractClass();
$provider->method( 'persistsSessionId' )
->willReturn( $persistId );
$provider->method( 'canChangeUser' )
->willReturn( $persistUser );
$this->initProvider( $provider, null, null, $manager );
if ( $ok ) {
$info = $provider->newSessionInfo();
$this->assertNotNull( $info );
$this->assertFalse( $info->wasPersisted() );
$this->assertTrue( $info->isIdSafe() );
$id = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
$info = $provider->newSessionInfo( $id );
$this->assertNotNull( $info );
$this->assertSame( $id, $info->getId() );
$this->assertFalse( $info->wasPersisted() );
$this->assertTrue( $info->isIdSafe() );
} else {
$this->assertNull( $provider->newSessionInfo() );
}
}
public function testMergeMetadata() {
$provider = $this->getMockBuilder( SessionProvider::class )
->getMockForAbstractClass();
try {
$provider->mergeMetadata(
[ 'foo' => 1, 'baz' => 3 ],
[ 'bar' => 2, 'baz' => '3' ]
);
$this->fail( 'Expected exception not thrown' );
} catch ( MetadataMergeException $ex ) {
$this->assertSame( 'Key "baz" changed', $ex->getMessage() );
$this->assertSame(
[ 'old_value' => 3, 'new_value' => '3' ], $ex->getContext() );
}
$res = $provider->mergeMetadata(
[ 'foo' => 1, 'baz' => 3 ],
[ 'bar' => 2, 'baz' => 3 ]
);
$this->assertSame( [ 'bar' => 2, 'baz' => 3 ], $res );
}
public static function provideNewSessionInfo() {
return [
[ false, false, false ],
[ true, false, false ],
[ false, true, false ],
[ true, true, true ],
];
}
public function testImmutableSessions() {
$provider = $this->getMockBuilder( SessionProvider::class )
->onlyMethods( [ 'canChangeUser', 'persistsSessionId' ] )
->getMockForAbstractClass();
$provider->method( 'canChangeUser' )
->willReturn( true );
$provider->preventSessionsForUser( 'Foo' );
$provider = $this->getMockBuilder( SessionProvider::class )
->onlyMethods( [ 'canChangeUser', 'persistsSessionId' ] )
->getMockForAbstractClass();
$provider->method( 'canChangeUser' )
->willReturn( false );
try {
$provider->preventSessionsForUser( 'Foo' );
$this->fail( 'Expected exception not thrown' );
} catch ( \BadMethodCallException $ex ) {
$this->assertSame(
'MediaWiki\\Session\\SessionProvider::preventSessionsForUser must be implemented ' .
'when canChangeUser() is false',
$ex->getMessage()
);
}
}
public function testHashToSessionId() {
$config = new \HashConfig( [
'SecretKey' => 'Shhh!',
] );
$provider = $this->getMockForAbstractClass( SessionProvider::class,
[], 'MockSessionProvider' );
$this->initProvider( $provider, null, $config );
$priv = TestingAccessWrapper::newFromObject( $provider );
$this->assertSame( 'eoq8cb1mg7j30ui5qolafps4hg29k5bb', $priv->hashToSessionId( 'foobar' ) );
$this->assertSame( '4do8j7tfld1g8tte9jqp3csfgmulaun9',
$priv->hashToSessionId( 'foobar', 'secret' ) );
try {
$priv->hashToSessionId( [] );
$this->fail( 'Expected exception not thrown' );
} catch ( \InvalidArgumentException $ex ) {
$this->assertSame(
'$data must be a string, array was passed',
$ex->getMessage()
);
}
try {
$priv->hashToSessionId( '', false );
$this->fail( 'Expected exception not thrown' );
} catch ( \InvalidArgumentException $ex ) {
$this->assertSame(
'$key must be a string or null, boolean was passed',
$ex->getMessage()
);
}
}
public function testDescribe() {
$provider = $this->getMockForAbstractClass( SessionProvider::class,
[], 'MockSessionProvider' );
$this->assertSame(
'MockSessionProvider sessions',
$provider->describe(
MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'en' ) )
);
}
public function testGetAllowedUserRights() {
$provider = $this->getMockForAbstractClass( SessionProvider::class );
$backend = TestUtils::getDummySessionBackend();
try {
$provider->getAllowedUserRights( $backend );
$this->fail( 'Expected exception not thrown' );
} catch ( \InvalidArgumentException $ex ) {
$this->assertSame(
'Backend\'s provider isn\'t $this',
$ex->getMessage()
);
}
TestingAccessWrapper::newFromObject( $backend )->provider = $provider;
$this->assertNull( $provider->getAllowedUserRights( $backend ) );
}
}