Search in sources :

Example 21 with SecurityContext

use of org.neo4j.internal.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class TransactionEventsIT method shouldGetSpecifiedUsernameAndMetaDataInTXData.

@Test
void shouldGetSpecifiedUsernameAndMetaDataInTXData() {
    final AtomicReference<String> usernameRef = new AtomicReference<>();
    final AtomicReference<Map<String, Object>> metaDataRef = new AtomicReference<>();
    dbms.registerTransactionEventListener(DEFAULT_DATABASE_NAME, getBeforeCommitListener(txData -> {
        usernameRef.set(txData.username());
        metaDataRef.set(txData.metaData());
    }));
    AuthSubject subject = mock(AuthSubject.class);
    when(subject.username()).thenReturn("Christof");
    LoginContext loginContext = new LoginContext(subject, EMBEDDED_CONNECTION) {

        @Override
        public SecurityContext authorize(IdLookup idLookup, String dbName, AbstractSecurityLog securityLog) {
            return new SecurityContext(subject, AccessMode.Static.WRITE, EMBEDDED_CONNECTION, dbName);
        }
    };
    Map<String, Object> metadata = genericMap("username", "joe");
    runTransaction(loginContext, metadata);
    assertThat(usernameRef.get()).as("Should have specified username").isEqualTo("Christof");
    assertThat(metaDataRef.get()).as("Should have metadata with specified username").isEqualTo(metadata);
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Label(org.neo4j.graphdb.Label) AnonymousContext(org.neo4j.kernel.api.security.AnonymousContext) RandomExtension(org.neo4j.test.extension.RandomExtension) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) LoginContext(org.neo4j.internal.kernel.api.security.LoginContext) TransactionFailureException(org.neo4j.graphdb.TransactionFailureException) TransactionData(org.neo4j.graphdb.event.TransactionData) AuthSubject(org.neo4j.internal.kernel.api.security.AuthSubject) Iterators.count(org.neo4j.internal.helpers.collection.Iterators.count) AtomicReference(java.util.concurrent.atomic.AtomicReference) Node(org.neo4j.graphdb.Node) ArrayList(java.util.ArrayList) ImpermanentDbmsExtension(org.neo4j.test.extension.ImpermanentDbmsExtension) DEFAULT_DATABASE_NAME(org.neo4j.configuration.GraphDatabaseSettings.DEFAULT_DATABASE_NAME) Future(java.util.concurrent.Future) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) GraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService) Inject(org.neo4j.test.extension.Inject) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RandomRule(org.neo4j.test.rule.RandomRule) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) TransactionEventListenerAdapter(org.neo4j.graphdb.event.TransactionEventListenerAdapter) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) MapUtil.genericMap(org.neo4j.internal.helpers.collection.MapUtil.genericMap) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Transaction(org.neo4j.graphdb.Transaction) BinaryLatch(org.neo4j.util.concurrent.BinaryLatch) ExecutorService(java.util.concurrent.ExecutorService) EMBEDDED_CONNECTION(org.neo4j.internal.kernel.api.connectioninfo.ClientConnectionInfo.EMBEDDED_CONNECTION) AbstractSecurityLog(org.neo4j.internal.kernel.api.security.AbstractSecurityLog) ExceptionUtils.getRootCause(org.apache.commons.lang3.exception.ExceptionUtils.getRootCause) Mockito.when(org.mockito.Mockito.when) Executors(java.util.concurrent.Executors) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) Test(org.junit.jupiter.api.Test) Consumer(java.util.function.Consumer) TransactionEventListener(org.neo4j.graphdb.event.TransactionEventListener) AccessMode(org.neo4j.internal.kernel.api.security.AccessMode) List(java.util.List) Relationship(org.neo4j.graphdb.Relationship) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) RelationshipType(org.neo4j.graphdb.RelationshipType) DatabaseManagementService(org.neo4j.dbms.api.DatabaseManagementService) Collections(java.util.Collections) Mockito.mock(org.mockito.Mockito.mock) AuthSubject(org.neo4j.internal.kernel.api.security.AuthSubject) AtomicReference(java.util.concurrent.atomic.AtomicReference) LoginContext(org.neo4j.internal.kernel.api.security.LoginContext) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) AbstractSecurityLog(org.neo4j.internal.kernel.api.security.AbstractSecurityLog) Map(java.util.Map) MapUtil.genericMap(org.neo4j.internal.helpers.collection.MapUtil.genericMap) Test(org.junit.jupiter.api.Test)

Example 22 with SecurityContext

use of org.neo4j.internal.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class KernelTransactionTestBase method newTransaction.

public KernelTransactionImplementation newTransaction(long lastTransactionIdWhenStarted, LoginContext loginContext, Locks.Client locks, long transactionTimeout) {
    KernelTransactionImplementation tx = newNotInitializedTransaction();
    SecurityContext securityContext = loginContext.authorize(LoginContext.IdLookup.EMPTY, DEFAULT_DATABASE_NAME, CommunitySecurityLog.NULL_LOG);
    tx.initialize(lastTransactionIdWhenStarted, BASE_TX_COMMIT_TIMESTAMP, locks, KernelTransaction.Type.EXPLICIT, securityContext, transactionTimeout, 1L, EMBEDDED_CONNECTION);
    return tx;
}
Also used : SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext)

Example 23 with SecurityContext

use of org.neo4j.internal.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class DatabaseManagementServiceFactory method setupProcedures.

/**
 * Creates and registers the systems procedures, including those which belong to a particular edition.
 * N.B. This method takes a {@link DatabaseManager} as an unused parameter *intentionally*, in
 * order to enforce that the databaseManager must be constructed first.
 */
@SuppressWarnings("unused")
private static void setupProcedures(GlobalModule globalModule, AbstractEditionModule editionModule, DatabaseManager<?> databaseManager) {
    Supplier<GlobalProcedures> procedureInitializer = () -> {
        Config globalConfig = globalModule.getGlobalConfig();
        Path proceduresDirectory = globalConfig.get(GraphDatabaseSettings.plugin_dir);
        LogService logService = globalModule.getLogService();
        Log internalLog = logService.getInternalLog(GlobalProcedures.class);
        Log proceduresLog = logService.getUserLog(GlobalProcedures.class);
        ProcedureConfig procedureConfig = new ProcedureConfig(globalConfig);
        Edition neo4jEdition = globalModule.getDbmsInfo().edition;
        SpecialBuiltInProcedures builtInProcedures = new SpecialBuiltInProcedures(Version.getNeo4jVersion(), neo4jEdition.toString());
        GlobalProceduresRegistry globalProcedures = new GlobalProceduresRegistry(builtInProcedures, proceduresDirectory, internalLog, procedureConfig);
        globalProcedures.registerType(Node.class, NTNode);
        globalProcedures.registerType(NodeValue.class, NTNode);
        globalProcedures.registerType(Relationship.class, NTRelationship);
        globalProcedures.registerType(RelationshipValue.class, NTRelationship);
        globalProcedures.registerType(org.neo4j.graphdb.Path.class, NTPath);
        globalProcedures.registerType(PathValue.class, NTPath);
        globalProcedures.registerType(Geometry.class, NTGeometry);
        globalProcedures.registerType(Point.class, NTPoint);
        globalProcedures.registerType(PointValue.class, NTPoint);
        // Below components are not public API, but are made available for internal
        // procedures to call, and to provide temporary workarounds for the following
        // patterns:
        // - Batch-transaction imports (GDAPI, needs to be real and passed to background processing threads)
        // - Group-transaction writes (same pattern as above, but rather than splitting large transactions,
        // combine lots of small ones)
        // - Bleeding-edge performance (KernelTransaction, to bypass overhead of working with Core API)
        globalProcedures.registerComponent(DependencyResolver.class, Context::dependencyResolver, false);
        globalProcedures.registerComponent(KernelTransaction.class, ctx -> ctx.internalTransaction().kernelTransaction(), false);
        globalProcedures.registerComponent(GraphDatabaseAPI.class, Context::graphDatabaseAPI, false);
        globalProcedures.registerComponent(SystemGraphComponents.class, ctx -> globalModule.getSystemGraphComponents(), false);
        globalProcedures.registerComponent(ValueMapper.class, Context::valueMapper, true);
        // Register injected public API components
        globalProcedures.registerComponent(Log.class, ctx -> proceduresLog, true);
        globalProcedures.registerComponent(Transaction.class, new ProcedureTransactionProvider(), true);
        globalProcedures.registerComponent(org.neo4j.procedure.TerminationGuard.class, new TerminationGuardProvider(), true);
        globalProcedures.registerComponent(SecurityContext.class, Context::securityContext, true);
        globalProcedures.registerComponent(ProcedureCallContext.class, Context::procedureCallContext, true);
        globalProcedures.registerComponent(FulltextAdapter.class, ctx -> ctx.dependencyResolver().resolveDependency(FulltextAdapter.class), true);
        globalProcedures.registerComponent(GraphDatabaseService.class, ctx -> new GraphDatabaseFacade((GraphDatabaseFacade) ctx.graphDatabaseAPI(), new ProcedureLoginContextTransformer(ctx)), true);
        globalProcedures.registerComponent(DataCollector.class, ctx -> ctx.dependencyResolver().resolveDependency(DataCollector.class), false);
        // Edition procedures
        try {
            editionModule.registerProcedures(globalProcedures, procedureConfig, globalModule, databaseManager);
        } catch (KernelException e) {
            internalLog.error("Failed to register built-in edition procedures at start up: " + e.getMessage());
        }
        globalModule.getGlobalLife().add(globalProcedures);
        return globalProcedures;
    };
    GlobalProcedures procedures = tryResolveOrCreate(GlobalProcedures.class, globalModule.getExternalDependencyResolver(), procedureInitializer);
    if (procedures instanceof Consumer) {
        ((Consumer) procedures).accept(procedureInitializer);
    }
    globalModule.getGlobalDependencies().satisfyDependency(procedures);
}
Also used : Log(org.neo4j.logging.Log) NodeValue(org.neo4j.values.virtual.NodeValue) Config(org.neo4j.configuration.Config) LifeSupport(org.neo4j.kernel.lifecycle.LifeSupport) DisabledNeoWebServer(org.neo4j.server.web.DisabledNeoWebServer) HttpConnector(org.neo4j.configuration.connectors.HttpConnector) SpecialBuiltInProcedures(org.neo4j.procedure.builtin.SpecialBuiltInProcedures) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) HttpsConnector(org.neo4j.configuration.connectors.HttpsConnector) ProcedureTransactionProvider(org.neo4j.procedure.impl.ProcedureTransactionProvider) Transaction(org.neo4j.graphdb.Transaction) Path(java.nio.file.Path) DatabaseIdRepository(org.neo4j.kernel.database.DatabaseIdRepository) NAMED_SYSTEM_DATABASE_ID(org.neo4j.kernel.database.DatabaseIdRepository.NAMED_SYSTEM_DATABASE_ID) ProcedureConfig(org.neo4j.procedure.impl.ProcedureConfig) RelationshipValue(org.neo4j.values.virtual.RelationshipValue) Dependencies(org.neo4j.collection.Dependencies) Geometry(org.neo4j.graphdb.spatial.Geometry) PointValue(org.neo4j.values.storable.PointValue) DatabaseContext(org.neo4j.dbms.database.DatabaseContext) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) DatabaseStateService(org.neo4j.dbms.DatabaseStateService) Optional(java.util.Optional) PathValue(org.neo4j.values.virtual.PathValue) BoltServer(org.neo4j.bolt.BoltServer) DatabaseManagementService(org.neo4j.dbms.api.DatabaseManagementService) DatabaseManager(org.neo4j.dbms.database.DatabaseManager) ValueMapper(org.neo4j.values.ValueMapper) GraphDatabaseSettings(org.neo4j.configuration.GraphDatabaseSettings) ServerSettings(org.neo4j.server.configuration.ServerSettings) LogProvider(org.neo4j.logging.LogProvider) DbmsRuntimeSystemGraphComponent(org.neo4j.dbms.database.DbmsRuntimeSystemGraphComponent) ProcedureLoginContextTransformer(org.neo4j.procedure.impl.ProcedureLoginContextTransformer) NTNode(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTNode) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Node(org.neo4j.graphdb.Node) SYSTEM_DATABASE_NAME(org.neo4j.configuration.GraphDatabaseSettings.SYSTEM_DATABASE_NAME) GlobalProcedures(org.neo4j.kernel.api.procedure.GlobalProcedures) DefaultDatabaseInitializer(org.neo4j.dbms.database.DefaultDatabaseInitializer) GraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService) BoltGraphDatabaseManagementServiceSPI(org.neo4j.bolt.dbapi.BoltGraphDatabaseManagementServiceSPI) SystemGraphComponents(org.neo4j.dbms.database.SystemGraphComponents) Point(org.neo4j.graphdb.spatial.Point) DbmsInfo(org.neo4j.kernel.impl.factory.DbmsInfo) DataCollector(org.neo4j.internal.collector.DataCollector) DependencyResolver(org.neo4j.common.DependencyResolver) Lifecycle(org.neo4j.kernel.lifecycle.Lifecycle) NTGeometry(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTGeometry) SecurityProvider(org.neo4j.kernel.api.security.provider.SecurityProvider) TerminationGuardProvider(org.neo4j.procedure.impl.TerminationGuardProvider) Edition(org.neo4j.common.Edition) Version(org.neo4j.kernel.internal.Version) NTPoint(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTPoint) DatabaseManagementServiceImpl(org.neo4j.dbms.database.DatabaseManagementServiceImpl) FulltextAdapter(org.neo4j.kernel.api.impl.fulltext.FulltextAdapter) Context(org.neo4j.kernel.api.procedure.Context) AbstractEditionModule(org.neo4j.graphdb.factory.module.edition.AbstractEditionModule) NTPath(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTPath) Consumer(java.util.function.Consumer) LogService(org.neo4j.logging.internal.LogService) GlobalProceduresRegistry(org.neo4j.procedure.impl.GlobalProceduresRegistry) ProcedureCallContext(org.neo4j.internal.kernel.api.procs.ProcedureCallContext) Relationship(org.neo4j.graphdb.Relationship) KernelException(org.neo4j.exceptions.KernelException) CommunityEditionModule.tryResolveOrCreate(org.neo4j.graphdb.factory.module.edition.CommunityEditionModule.tryResolveOrCreate) NTRelationship(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTRelationship) UnableToStartDatabaseException(org.neo4j.dbms.database.UnableToStartDatabaseException) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) GraphDatabaseFacade(org.neo4j.kernel.impl.factory.GraphDatabaseFacade) GlobalModule(org.neo4j.graphdb.factory.module.GlobalModule) NodeValue(org.neo4j.values.virtual.NodeValue) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) ProcedureLoginContextTransformer(org.neo4j.procedure.impl.ProcedureLoginContextTransformer) ValueMapper(org.neo4j.values.ValueMapper) PathValue(org.neo4j.values.virtual.PathValue) Config(org.neo4j.configuration.Config) ProcedureConfig(org.neo4j.procedure.impl.ProcedureConfig) NTNode(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTNode) Node(org.neo4j.graphdb.Node) RelationshipValue(org.neo4j.values.virtual.RelationshipValue) TerminationGuardProvider(org.neo4j.procedure.impl.TerminationGuardProvider) SystemGraphComponents(org.neo4j.dbms.database.SystemGraphComponents) ProcedureCallContext(org.neo4j.internal.kernel.api.procs.ProcedureCallContext) GlobalProceduresRegistry(org.neo4j.procedure.impl.GlobalProceduresRegistry) GraphDatabaseAPI(org.neo4j.kernel.internal.GraphDatabaseAPI) Consumer(java.util.function.Consumer) ProcedureTransactionProvider(org.neo4j.procedure.impl.ProcedureTransactionProvider) KernelException(org.neo4j.exceptions.KernelException) ProcedureConfig(org.neo4j.procedure.impl.ProcedureConfig) SpecialBuiltInProcedures(org.neo4j.procedure.builtin.SpecialBuiltInProcedures) Path(java.nio.file.Path) NTPath(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTPath) GraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService) FulltextAdapter(org.neo4j.kernel.api.impl.fulltext.FulltextAdapter) Log(org.neo4j.logging.Log) PointValue(org.neo4j.values.storable.PointValue) Point(org.neo4j.graphdb.spatial.Point) NTPoint(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTPoint) DataCollector(org.neo4j.internal.collector.DataCollector) GlobalProcedures(org.neo4j.kernel.api.procedure.GlobalProcedures) Edition(org.neo4j.common.Edition) DependencyResolver(org.neo4j.common.DependencyResolver) Geometry(org.neo4j.graphdb.spatial.Geometry) NTGeometry(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTGeometry) Transaction(org.neo4j.graphdb.Transaction) KernelTransaction(org.neo4j.kernel.api.KernelTransaction) Relationship(org.neo4j.graphdb.Relationship) NTRelationship(org.neo4j.internal.kernel.api.procs.Neo4jTypes.NTRelationship) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) GraphDatabaseFacade(org.neo4j.kernel.impl.factory.GraphDatabaseFacade) LogService(org.neo4j.logging.internal.LogService)

Example 24 with SecurityContext

use of org.neo4j.internal.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class NodeTransactionStateTestBase method shouldNotCountRemovedNodesFromTxStateRestrictedUser.

@Test
void shouldNotCountRemovedNodesFromTxStateRestrictedUser() throws Exception {
    // Given
    Node node1 = createNode("label");
    Node node2 = createNode("label");
    SecurityContext loginContext = new SecurityContext(AuthSubject.AUTH_DISABLED, new TestAccessMode(true, false, true, false), EMBEDDED_CONNECTION, null);
    try (KernelTransaction tx = beginTransaction(loginContext)) {
        // when
        tx.dataWrite().nodeDelete(node2.node);
        long countTxState = tx.dataRead().countsForNode(node1.labels[0]);
        long countNoTxState = tx.dataRead().countsForNodeWithoutTxState(node1.labels[0]);
        // then
        assertEquals(1, countTxState);
        assertEquals(2, countNoTxState);
    }
}
Also used : KernelTransaction(org.neo4j.kernel.api.KernelTransaction) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) TestAccessMode(org.neo4j.internal.kernel.api.security.TestAccessMode) Test(org.junit.jupiter.api.Test)

Example 25 with SecurityContext

use of org.neo4j.internal.kernel.api.security.SecurityContext in project neo4j by neo4j.

the class NodeTransactionStateTestBase method shouldNotCountRemovedLabelsFromTxStateRestrictedUser.

@Test
void shouldNotCountRemovedLabelsFromTxStateRestrictedUser() throws Exception {
    // Given
    Node node1 = createNode("label");
    Node node2 = createNode("label");
    SecurityContext loginContext = new SecurityContext(AuthSubject.AUTH_DISABLED, new TestAccessMode(true, false, true, false), EMBEDDED_CONNECTION, null);
    try (KernelTransaction tx = beginTransaction(loginContext)) {
        // when
        tx.dataWrite().nodeRemoveLabel(node2.node, node2.labels[0]);
        long countTxState = tx.dataRead().countsForNode(node1.labels[0]);
        long countNoTxState = tx.dataRead().countsForNodeWithoutTxState(node1.labels[0]);
        // then
        assertEquals(1, countTxState);
        assertEquals(2, countNoTxState);
    }
}
Also used : KernelTransaction(org.neo4j.kernel.api.KernelTransaction) SecurityContext(org.neo4j.internal.kernel.api.security.SecurityContext) TestAccessMode(org.neo4j.internal.kernel.api.security.TestAccessMode) Test(org.junit.jupiter.api.Test)

Aggregations

SecurityContext (org.neo4j.internal.kernel.api.security.SecurityContext)25 Test (org.junit.jupiter.api.Test)17 KernelTransaction (org.neo4j.kernel.api.KernelTransaction)15 TestAccessMode (org.neo4j.internal.kernel.api.security.TestAccessMode)7 RestrictedAccessMode (org.neo4j.kernel.impl.api.security.RestrictedAccessMode)5 AccessMode (org.neo4j.internal.kernel.api.security.AccessMode)4 OverriddenAccessMode (org.neo4j.kernel.impl.api.security.OverriddenAccessMode)3 InternalTransaction (org.neo4j.kernel.impl.coreapi.InternalTransaction)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Map (java.util.Map)2 Consumer (java.util.function.Consumer)2 MutableObject (org.apache.commons.lang3.mutable.MutableObject)2 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)2 Assertions.assertThrows (org.junit.jupiter.api.Assertions.assertThrows)2 InOrder (org.mockito.InOrder)2 Mockito.mock (org.mockito.Mockito.mock)2 Mockito.when (org.mockito.Mockito.when)2 ReturnsDeepStubs (org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs)2 DependencyResolver (org.neo4j.common.DependencyResolver)2