@Override public boolean credentialsExpired() { return loginContext.subject().getAuthenticationResult() == org.neo4j.internal.kernel.api.security.AuthenticationResult.PASSWORD_CHANGE_REQUIRED; } }
@Test public void shouldNotLeakTransactionOnSecurityContextFreezeFailure() throws Throwable { KernelTransactions kernelTransactions = newKernelTransactions(); LoginContext loginContext = mock( LoginContext.class ); when( loginContext.authorize( any(), any() ) ).thenThrow( new AuthorizationExpiredException( "Freeze failed." ) ); assertException(() -> kernelTransactions.newInstance(KernelTransaction.Type.explicit, loginContext, 0L), AuthorizationExpiredException.class, "Freeze failed."); assertThat("We should not have any transaction", kernelTransactions.activeTransactions(), is(empty())); }
@GET @Path( "/{username}" ) public Response getUser( @PathParam( "username" ) String username, @Context HttpServletRequest req ) { Principal principal = req.getUserPrincipal(); if ( principal == null || !principal.getName().equals( username ) ) { return output.notFound(); } LoginContext loginContext = getLoginContextFromUserPrincipal( principal ); UserManager userManager = userManagerSupplier.getUserManager( loginContext.subject(), false ); try { User user = userManager.getUser( username ); return output.ok( new AuthorizationRepresentation( user ) ); } catch ( InvalidArgumentsException e ) { return output.notFound(); } }
when( statement.queryRegistration() ).thenReturn( registryOperations ); when( statementBridge.get() ).thenReturn( statement ); when( kernelTransaction.securityContext() ).thenReturn( loginContext.authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ) ); when( kernelTransaction.transactionType() ).thenReturn( type ); when( database.getGraph() ).thenReturn( databaseFacade );
switch ( loginContext.subject().getAuthenticationResult() ) userManagerSupplier.getUserManager( loginContext.subject(), false ) .setUserPassword( username, newPassword, false ); // NOTE: This will overwrite newPassword with zeroes loginContext.subject().setPasswordChangeNoLongerRequired(); break; default:
public KernelTransactionImplementation newTransaction( long lastTransactionIdWhenStarted, LoginContext loginContext, Locks.Client locks, long transactionTimeout ) { KernelTransactionImplementation tx = newNotInitializedTransaction(); StatementLocks statementLocks = new SimpleStatementLocks( locks ); SecurityContext securityContext = loginContext.authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ); tx.initialize( lastTransactionIdWhenStarted, BASE_TX_COMMIT_TIMESTAMP,statementLocks, Type.implicit, securityContext, transactionTimeout, 1L ); return tx; }
@Override public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) throws IOException, ServletException { validateRequestType( servletRequest ); validateResponseType( servletResponse ); final HttpServletRequest request = (HttpServletRequest) servletRequest; final HttpServletResponse response = (HttpServletResponse) servletResponse; try { LoginContext loginContext = getAuthDisabledLoginContext(); String userAgent = request.getHeader( HttpHeaders.USER_AGENT ); JettyHttpConnection.updateUserForCurrentConnection( loginContext.subject().username(), userAgent ); filterChain.doFilter( new AuthorizedRequestWrapper( BASIC_AUTH, "neo4j", request, loginContext ), servletResponse ); } catch ( AuthorizationViolationException e ) { unauthorizedAccess( e.getMessage() ).accept( response ); } }
public KernelTransaction newInstance( KernelTransaction.Type type, LoginContext loginContext, long timeout ) SecurityContext securityContext = loginContext.authorize( tokenHolders.propertyKeyTokens()::getOrCreateId, currentDatabaseName ); try
private void assertLoginGivesResult( String username, String password, AuthenticationResult expectedResult ) throws InvalidAuthTokenException { LoginContext securityContext = manager.login( authToken( username, password ) ); assertThat( securityContext.subject().getAuthenticationResult(), equalTo( expectedResult ) ); }
static Instances kernelTransactionWithInternals( LoginContext loginContext ) { TransactionHeaderInformation headerInformation = new TransactionHeaderInformation( -1, -1, new byte[0] ); TransactionHeaderInformationFactory headerInformationFactory = mock( TransactionHeaderInformationFactory.class ); when( headerInformationFactory.create() ).thenReturn( headerInformation ); StorageEngine storageEngine = mock( StorageEngine.class ); StorageReader storageReader = mock( StorageReader.class ); when( storageEngine.newReader() ).thenReturn( storageReader ); KernelTransactionImplementation transaction = new KernelTransactionImplementation( Config.defaults(), mock( StatementOperationParts.class ), mock( SchemaWriteGuard.class ), new TransactionHooks(), mock( ConstraintIndexCreator.class ), new Procedures(), headerInformationFactory, mock( TransactionRepresentationCommitProcess.class ), mock( TransactionMonitor.class ), mock( AuxiliaryTransactionStateManager.class ), mock( Pool.class ), Clocks.systemClock(), new AtomicReference<>( CpuClock.NOT_AVAILABLE ), new AtomicReference<>( HeapAllocation.NOT_AVAILABLE ), NULL, LockTracer.NONE, PageCursorTracerSupplier.NULL, storageEngine, new CanWrite(), AutoIndexing.UNSUPPORTED, mock( ExplicitIndexStore.class ), EmptyVersionContextSupplier.EMPTY, ON_HEAP, new StandardConstraintSemantics(), mock( SchemaState.class ), mock( IndexingService.class ), mockedTokenHolders(), new Dependencies() ); StatementLocks statementLocks = new SimpleStatementLocks( new NoOpClient() ); transaction.initialize( 0, 0, statementLocks, KernelTransaction.Type.implicit, loginContext.authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ), 0L, 1L ); return new Instances( transaction ); }
@Test public void shouldNotDoAnythingOnSuccess() throws Exception { // When AuthenticationResult result = authentication.authenticate( map( "scheme", "basic", "principal", "mike", "credentials", UTF8.encode( "secret2" ) ) ); // Then assertThat( result.getLoginContext().subject().username(), equalTo( "mike" ) ); }
@Test public void markForTerminationWithIncorrectReuseCount() throws Exception { int reuseCount = 13; int nextReuseCount = reuseCount + 2; Status.Transaction terminationReason = Status.Transaction.Terminated; KernelTransactionImplementation tx = newNotInitializedTransaction( ); initializeAndClose( tx, reuseCount ); Locks.Client locksClient = mock( Locks.Client.class ); SimpleStatementLocks statementLocks = new SimpleStatementLocks( locksClient ); tx.initialize( 42, 42, statementLocks, KernelTransaction.Type.implicit, loginContext().authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ), 0L, 0L ); assertFalse( tx.markForTermination( nextReuseCount, terminationReason ) ); assertFalse( tx.getReasonIfTerminated().isPresent() ); verify( locksClient, never() ).stop(); }
switch ( securityContext.subject().getAuthenticationResult() )
private void initializeAndClose( KernelTransactionImplementation tx, int times ) throws Exception { for ( int i = 0; i < times; i++ ) { SimpleStatementLocks statementLocks = new SimpleStatementLocks( new NoOpClient() ); tx.initialize( i + 10, i + 10, statementLocks, KernelTransaction.Type.implicit, loginContext().authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ), 0L, 0L ); tx.close(); } }
UserManager userManager = userManagerSupplier.getUserManager( loginContext.subject(), false ); userManager.setUserPassword( username, UTF8.encode( newPassword ), false );
@Test public void markForTerminationWithCorrectReuseCount() throws Exception { int reuseCount = 10; Status.Transaction terminationReason = Status.Transaction.Terminated; KernelTransactionImplementation tx = newNotInitializedTransaction( ); initializeAndClose( tx, reuseCount ); Locks.Client locksClient = mock( Locks.Client.class ); SimpleStatementLocks statementLocks = new SimpleStatementLocks( locksClient ); tx.initialize( 42, 42, statementLocks, KernelTransaction.Type.implicit, loginContext().authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ), 0L, 0L ); assertTrue( tx.markForTermination( reuseCount, terminationReason ) ); assertEquals( terminationReason, tx.getReasonIfTerminated().get() ); verify( locksClient ).stop(); }
private AuthenticationResult doAuthenticate( Map<String,Object> authToken ) throws AuthenticationException { try { LoginContext loginContext = authManager.login( authToken ); switch ( loginContext.subject().getAuthenticationResult() ) { case SUCCESS: case PASSWORD_CHANGE_REQUIRED: break; case TOO_MANY_ATTEMPTS: throw new AuthenticationException( Status.Security.AuthenticationRateLimit ); default: throw new AuthenticationException( Status.Security.Unauthorized ); } return new BasicAuthenticationResult( loginContext ); } catch ( InvalidAuthTokenException e ) { throw new AuthenticationException( e.status(), e.getMessage() ); } }
@Test public void shouldIncrementReuseCounterOnReuse() throws Exception { // GIVEN KernelTransactionImplementation transaction = newTransaction( loginContext() ); int reuseCount = transaction.getReuseCount(); // WHEN transaction.close(); SimpleStatementLocks statementLocks = new SimpleStatementLocks( new NoOpClient() ); transaction.initialize( 1, BASE_TX_COMMIT_TIMESTAMP, statementLocks, KernelTransaction.Type.implicit, loginContext().authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ), 0L, 1L ); // THEN assertEquals( reuseCount + 1, transaction.getReuseCount() ); }
@Before public void setup() throws InvalidAuthTokenException, IOException { fs = new EphemeralFileSystemAbstraction(); db = (GraphDatabaseAPI) createGraphDatabase( fs ); authManager = db.getDependencyResolver().resolveDependency( BasicAuthManager.class ); admin = login( "neo4j", "neo4j" ); admin.subject().setPasswordChangeNoLongerRequired(); }
@Before public void setup() throws Throwable { manager = new BasicAuthManager( new InMemoryUserRepository(), new BasicPasswordPolicy(), Clocks.systemClock(), new InMemoryUserRepository(), Config.defaults() ); manager.init(); manager.start(); manager.newUser( "johan", password( "bar" ), false ); context = manager.login( authToken( "johan", "bar" ) ).authorize( s -> -1, GraphDatabaseSettings.DEFAULT_DATABASE_NAME ); }