Skip to content

Commit

Permalink
Refactor how AuthManager is intitialized
Browse files Browse the repository at this point in the history
  • Loading branch information
pontusmelke committed Feb 21, 2016
1 parent 5b6168c commit 85a29bf
Show file tree
Hide file tree
Showing 19 changed files with 94 additions and 85 deletions.
Expand Up @@ -88,8 +88,7 @@ public static class Settings
public static final Function<ConfigValues,List<Configuration>> connector_group = Config.groups( "dbms.connector" );

@Description( "Enable Neo4j Bolt" )
public static final Setting<Boolean> enabled =
setting( "enabled", BOOLEAN, "false" );
public static final Setting<Boolean> enabled = setting( "enabled", BOOLEAN, "false" );

@Description( "Set the encryption level for Neo4j Bolt protocol ports" )
public static final Setting<EncryptionLevel> tls_level =
Expand Down
Expand Up @@ -257,7 +257,7 @@ public abstract class GraphDatabaseSettings
@Description("Size of buffer used by index sampling")
public static final Setting<Long> index_sampling_buffer_size =
setting("index_sampling_buffer_size", BYTES, "64m",
min( /* 1m */ 1048576l ), max( (long) Integer.MAX_VALUE ) );
min( /* 1m */ 1048576L ), max( (long) Integer.MAX_VALUE ) );

@Description("Percentage of index updates of total index size required before sampling of a given index is triggered")
public static final Setting<Integer> index_sampling_update_percentage =
Expand Down Expand Up @@ -426,4 +426,11 @@ private static String defaultPageCacheMemory()
@Internal
public static final Setting<Integer> batch_inserter_batch_size = setting( "batch_inserter_batch_size", INTEGER,
"10000" );

@Description("Enable auth requirement to access Neo4j.")
public static final Setting<Boolean> auth_enabled = setting( "dbms.security.auth_enabled", BOOLEAN, "true" );

@Internal
public static final Setting<File> auth_store = setting("dbms.security.auth_store.location", PATH, "data/dbms/auth");

}
Expand Up @@ -31,7 +31,6 @@
import org.neo4j.kernel.KernelData;
import org.neo4j.kernel.NeoStoreDataSource;
import org.neo4j.kernel.Version;
import org.neo4j.kernel.api.exceptions.InvalidTransactionTypeKernelException;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.kernel.impl.api.SchemaWriteGuard;
import org.neo4j.kernel.impl.api.index.RemoveOrphanConstraintIndexesOnStartup;
Expand All @@ -56,10 +55,14 @@
import org.neo4j.kernel.impl.transaction.state.DataSourceManager;
import org.neo4j.kernel.lifecycle.LifeSupport;
import org.neo4j.kernel.lifecycle.Lifecycle;
import org.neo4j.kernel.lifecycle.LifecycleListener;
import org.neo4j.kernel.lifecycle.LifecycleStatus;
import org.neo4j.logging.LogProvider;
import org.neo4j.server.security.auth.AuthManager;
import org.neo4j.server.security.auth.FileUserRepository;
import org.neo4j.udc.UsageData;

import static java.time.Clock.systemUTC;


/**
* This implementation of {@link org.neo4j.kernel.impl.factory.EditionModule} creates the implementations of services
Expand Down Expand Up @@ -96,6 +99,7 @@ public CommunityEditionModule( PlatformModule platformModule )
dependencies.satisfyDependency(
createKernelData( fileSystem, pageCache, storeDir, config, graphDatabaseFacade, life ) );

dependencies.satisfyDependencies( createAuthManager(config, life, logging.getUserLogProvider()) );
commitProcessFactory = new CommunityCommitProcessFactory();

headerInformationFactory = createHeaderInformationFactory();
Expand All @@ -120,12 +124,7 @@ protected ConstraintSemantics createSchemaRuleVerifier()

protected SchemaWriteGuard createSchemaWriteGuard()
{
return new SchemaWriteGuard()
{
@Override
public void assertSchemaWritesAllowed() throws InvalidTransactionTypeKernelException
{
}
return () -> {
};
}

Expand Down Expand Up @@ -174,6 +173,14 @@ protected KernelData createKernelData( FileSystemAbstraction fileSystem, PageCac
return life.add( new DefaultKernelData( fileSystem, pageCache, storeDir, config, graphAPI ) );
}

private AuthManager createAuthManager(Config config, LifeSupport life, LogProvider logProvider)
{
FileUserRepository users = life.add( new FileUserRepository( config.get( GraphDatabaseSettings.auth_store ).toPath(), logProvider ) );

return life.add(new AuthManager( users, systemUTC(), config.get( GraphDatabaseSettings.auth_enabled )));

}

protected IdGeneratorFactory createIdGeneratorFactory( FileSystemAbstraction fs )
{
return new DefaultIdGeneratorFactory( fs );
Expand Down Expand Up @@ -219,15 +226,10 @@ protected TransactionHeaderInformationFactory createHeaderInformationFactory()
protected void registerRecovery( final DatabaseInfo databaseInfo, LifeSupport life,
final DependencyResolver dependencyResolver )
{
life.addLifecycleListener( new LifecycleListener()
{
@Override
public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to )
life.addLifecycleListener( ( instance, from, to ) -> {
if ( instance instanceof DatabaseAvailability && to.equals( LifecycleStatus.STARTED ) )
{
if ( instance instanceof DatabaseAvailability && to.equals( LifecycleStatus.STARTED ) )
{
doAfterRecoveryAndStartup( databaseInfo, dependencyResolver );
}
doAfterRecoveryAndStartup( databaseInfo, dependencyResolver );
}
} );
}
Expand Down
Expand Up @@ -74,7 +74,7 @@ public AbstractInProcessServerBuilder( File workingDir )
private void init( File workingDir )
{
setDirectory( workingDir );
withConfig( ServerSettings.auth_enabled, "false" );
withConfig( GraphDatabaseSettings.auth_enabled, "false" );
withConfig( GraphDatabaseSettings.pagecache_memory, "8m" );
withConfig( ServerSettings.webserver_port.name(), Integer.toString( freePort(7474, 10000) ) );

Expand Down
Expand Up @@ -19,6 +19,7 @@
*/
package org.neo4j.server;

import com.sun.jersey.api.core.HttpContext;
import org.apache.commons.configuration.Configuration;
import org.bouncycastle.operator.OperatorCreationException;

Expand Down Expand Up @@ -75,14 +76,12 @@
import org.neo4j.server.rest.transactional.TransitionalPeriodTransactionMessContainer;
import org.neo4j.server.rest.web.DatabaseActions;
import org.neo4j.server.security.auth.AuthManager;
import org.neo4j.server.security.auth.FileUserRepository;
import org.neo4j.server.web.SimpleUriBuilder;
import org.neo4j.server.web.WebServer;
import org.neo4j.server.web.WebServerProvider;

import static java.lang.Math.round;
import static java.lang.String.format;
import static java.time.Clock.systemUTC;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.neo4j.helpers.Clock.SYSTEM_CLOCK;
import static org.neo4j.helpers.collection.Iterables.map;
Expand Down Expand Up @@ -127,7 +126,7 @@ public abstract class AbstractNeoServer implements NeoServer
protected CypherExecutor cypherExecutor;
protected WebServer webServer;

protected AuthManager authManager;
protected Supplier<AuthManager> authManagerSupplier;
protected KeyStoreInformation keyStoreInfo;

private DatabaseActions databaseActions;
Expand Down Expand Up @@ -161,16 +160,7 @@ public void init()

this.database = life.add( dependencyResolver.satisfyDependency(dbFactory.newDatabase( config, dependencies)) );

FileUserRepository users = life.add( new FileUserRepository( config.get( ServerSettings.auth_store ).toPath(), logProvider ) );

// Since we are not (yet) using the AuthManager anywhere but here, we still
// instantiate it here. As we refactor, this should probably become an interface,
// with appropriate implementations created in CommunityModule and EnterpriseModule,
// respectively. To get a hold of AuthManager here, we're likely best of using
// DependencyResolver or similar, until the unfortunate problem of both this class
// and GraphDatabaseFacadeFactory implementing two different schemes of application
// assembly has been resolved.
this.authManager = life.add(new AuthManager( users, systemUTC(), config.get( ServerSettings.auth_enabled )));
this.authManagerSupplier = dependencyResolver.provideDependency( AuthManager.class );
this.webServer = createWebServer();

this.keyStoreInfo = createKeyStore();
Expand Down Expand Up @@ -543,14 +533,30 @@ protected Collection<InjectableProvider<?>> createDefaultInjectables()
singletons.add( new CypherExecutorProvider( cypherExecutor ) );

singletons.add( providerForSingleton( transactionFacade, TransactionFacade.class ) );
singletons.add( providerForSingleton( authManager, AuthManager.class ) );
singletons.add( new AuthManagerProvider(authManagerSupplier ) );
singletons.add( new TransactionFilter( database ) );
singletons.add( new LoggingProvider( logProvider ) );
singletons.add( providerForSingleton( logProvider.getLog( NeoServer.class ), Log.class ) );

return singletons;
}

private static class AuthManagerProvider extends InjectableProvider<AuthManager>
{
private final Supplier<AuthManager> authManagerSupplier;
private AuthManagerProvider( Supplier<AuthManager> authManagerSupplier )
{
super(AuthManager.class);
this.authManagerSupplier = authManagerSupplier;
}

@Override
public AuthManager getValue( HttpContext httpContext )
{
return authManagerSupplier.get();
}
}

private boolean hasModule( Class<? extends ServerModule> clazz )
{
for ( ServerModule sm : serverModules )
Expand Down
Expand Up @@ -39,6 +39,7 @@
import org.neo4j.server.logging.JULBridge;
import org.neo4j.server.logging.JettyLogBridge;
import org.neo4j.server.logging.Netty4LogBridge;

import static java.lang.String.format;
import static org.neo4j.server.configuration.ServerSettings.SERVER_CONFIG_FILE;
import static org.neo4j.server.configuration.ServerSettings.SERVER_CONFIG_FILE_KEY;
Expand Down Expand Up @@ -88,7 +89,6 @@ public int start( File configFile, Pair<String, String> ... configOverrides )
config = createConfig( log, configFile, configOverrides );
serverPort = String.valueOf( config.get( ServerSettings.webserver_port ) );
dependencies = dependencies.userLogProvider( userLogProvider );

life.start();

checkCompatibility();
Expand Down
Expand Up @@ -82,7 +82,7 @@ protected Iterable<ServerModule> createServerModules()
new ThirdPartyJAXRSModule( webServer, getConfig(), logProvider, this ),
new WebAdminModule( webServer, getConfig() ),
new Neo4jBrowserModule( webServer ),
new AuthorizationModule( webServer, authManager, logProvider, getConfig(), getUriWhitelist() ),
new AuthorizationModule( webServer, authManagerSupplier, logProvider, getConfig(), getUriWhitelist() ),
new SecurityRulesModule( webServer, getConfig(), logProvider ) );
}

Expand Down
Expand Up @@ -163,9 +163,6 @@ private ThirdPartyJaxRsPackage createThirdPartyJaxRsPackage( String packageAndMo
@Description("Timeout for idle transactions.")
Setting<Long> transaction_timeout = setting( "org.neo4j.server.transaction.timeout", DURATION, "60s" );

@Description("Enable auth requirement to access Neo4j.")
Setting<Boolean> auth_enabled = setting( "dbms.security.auth_enabled", BOOLEAN, TRUE );

@Description("Enable the Bolt protocol")
Setting<Boolean> bolt_enabled = BoltKernelExtension.Settings.enabled;

Expand Down Expand Up @@ -200,9 +197,6 @@ private ThirdPartyJaxRsPackage createThirdPartyJaxRsPackage( String packageAndMo
Setting<Boolean> wadl_enabled = setting( "unsupported_wadl_generation_enabled", BOOLEAN,
FALSE );

@Internal
Setting<File> auth_store = setting("dbms.security.auth_store.location", PATH, "data/dbms/auth");

@Internal
Setting<File> legacy_db_location = setting( "org.neo4j.server.database.location", PATH, "data/graph.db" );

Expand Down
Expand Up @@ -19,11 +19,12 @@
*/
package org.neo4j.server.modules;

import java.util.function.Supplier;
import java.util.regex.Pattern;

import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.logging.LogProvider;
import org.neo4j.server.configuration.ServerSettings;
import org.neo4j.server.rest.dbms.AuthorizationFilter;
import org.neo4j.server.security.auth.AuthManager;
import org.neo4j.server.web.WebServer;
Expand All @@ -32,25 +33,25 @@ public class AuthorizationModule implements ServerModule
{
private final WebServer webServer;
private final Config config;
private final AuthManager authManager;
private final Supplier<AuthManager> authManagerSupplier;
private final LogProvider logProvider;
private final Pattern[] uriWhitelist;

public AuthorizationModule( WebServer webServer, AuthManager authManager, LogProvider logProvider, Config config, Pattern[] uriWhitelist )
public AuthorizationModule( WebServer webServer, Supplier<AuthManager> authManager, LogProvider logProvider, Config config, Pattern[] uriWhitelist )
{
this.webServer = webServer;
this.config = config;
this.authManager = authManager;
this.authManagerSupplier = authManager;
this.logProvider = logProvider;
this.uriWhitelist = uriWhitelist;
}

@Override
public void start()
{
if ( config.get( ServerSettings.auth_enabled ) )
if ( config.get( GraphDatabaseSettings.auth_enabled ) )
{
final AuthorizationFilter authorizationFilter = new AuthorizationFilter( authManager, logProvider, uriWhitelist );
final AuthorizationFilter authorizationFilter = new AuthorizationFilter( authManagerSupplier, logProvider, uriWhitelist );
webServer.addFilter( authorizationFilter, "/*" );
}
}
Expand Down
Expand Up @@ -22,6 +22,7 @@
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
Expand Down Expand Up @@ -53,13 +54,13 @@ public class AuthorizationFilter implements Filter
{
private static final Pattern PASSWORD_CHANGE_WHITELIST = Pattern.compile( "/user/.*" );

private final AuthManager authManager;
private final Supplier<AuthManager> authManagerSupplier;
private final Log log;
private final Pattern[] uriWhitelist;

public AuthorizationFilter( AuthManager authManager, LogProvider logProvider, Pattern... uriWhitelist )
public AuthorizationFilter( Supplier<AuthManager> authManager, LogProvider logProvider, Pattern... uriWhitelist )
{
this.authManager = authManager;
this.authManagerSupplier = authManager;
this.log = logProvider.getLog( getClass() );
this.uriWhitelist = uriWhitelist;
}
Expand Down Expand Up @@ -103,6 +104,7 @@ public void doFilter( ServletRequest servletRequest, ServletResponse servletResp
final String username = usernameAndPassword[0];
final String password = usernameAndPassword[1];

AuthManager authManager = authManagerSupplier.get();
switch ( authManager.authenticate( username, password ) )
{
case PASSWORD_CHANGE_REQUIRED:
Expand All @@ -121,7 +123,6 @@ public void doFilter( ServletRequest servletRequest, ServletResponse servletResp
default:
log.warn( "Failed authentication attempt for '%s' from %s", username, request.getRemoteAddr() );
requestAuthentication( request, invalidCredential ).accept( response );
return;
}
}

Expand Down
Expand Up @@ -28,6 +28,7 @@
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

Expand All @@ -54,10 +55,7 @@ protected String[] commandLineConfig( String... params )
{
ArrayList<String> config = new ArrayList<>();

for ( String param : params )
{
config.add( param );
}
Collections.addAll( config, params );

return config.toArray( new String[config.size()] );
}
Expand Down
Expand Up @@ -34,6 +34,7 @@
import java.util.Random;

import org.neo4j.graphdb.config.Setting;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.server.configuration.ServerSettings;

public class ServerTestUtils
Expand Down Expand Up @@ -85,7 +86,7 @@ public static Map<String,String> getDefaultRelativeProperties() throws IOExcepti
public static void addDefaultRelativeProperties( Map<String,String> properties, File temporaryFolder )
{
addRelativeProperty( temporaryFolder, properties, ServerSettings.legacy_db_location );
addRelativeProperty( temporaryFolder, properties, ServerSettings.auth_store );
addRelativeProperty( temporaryFolder, properties, GraphDatabaseSettings.auth_store );
addRelativeProperty( temporaryFolder, properties, ServerSettings.tls_certificate_file );
addRelativeProperty( temporaryFolder, properties, ServerSettings.tls_key_file );
}
Expand All @@ -112,7 +113,7 @@ public static String asOneLine( Map<String, String> properties )
for ( Map.Entry<String, String> property : properties.entrySet() )
{
builder.append( ( builder.length() > 0 ? "," : "" ) );
builder.append( property.getKey() + "=" + property.getValue() );
builder.append( property.getKey() ).append( "=" ).append( property.getValue() );
}
return builder.toString();
}
Expand Down
Expand Up @@ -51,7 +51,6 @@

import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;

import static org.neo4j.helpers.Clock.SYSTEM_CLOCK;
import static org.neo4j.helpers.collection.MapUtil.stringMap;
import static org.neo4j.server.ServerTestUtils.asOneLine;
Expand Down Expand Up @@ -194,7 +193,7 @@ private Map<String, String> createConfiguration( File temporaryFolder )
}
}

properties.put( ServerSettings.auth_enabled.name(), "false" );
properties.put( GraphDatabaseSettings.auth_enabled.name(), "false" );
properties.put( GraphDatabaseSettings.pagecache_memory.name(), "8m" );

for ( Object key : arbitraryProperties.keySet() )
Expand Down

0 comments on commit 85a29bf

Please sign in to comment.