Fixing test execution for rest services

This commit is contained in:
Martin Stockhammer 2020-07-13 13:43:04 +02:00
parent 1b25737459
commit 7dca6a23be
10 changed files with 171 additions and 84 deletions

View File

@ -511,6 +511,7 @@ public class DefaultUserService
{ {
if ( isAdminUserExists().isExists() ) if ( isAdminUserExists().isExists() )
{ {
log.warn( "Admin user exists already" );
return ActionStatus.FAIL; return ActionStatus.FAIL;
} }
log.debug("Creating admin admin user '{}'", adminUser.getUsername()); log.debug("Creating admin admin user '{}'", adminUser.getUsername());

View File

@ -38,6 +38,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import javax.annotation.Priority;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@ -59,6 +60,7 @@ import javax.ws.rs.ext.Provider;
*/ */
@Service("authenticationInterceptor#rest") @Service("authenticationInterceptor#rest")
@Provider @Provider
@Priority( Priorities.AUTHENTICATION )
public class AuthenticationInterceptor public class AuthenticationInterceptor
extends AbstractInterceptor extends AbstractInterceptor
implements ContainerRequestFilter implements ContainerRequestFilter

View File

@ -118,12 +118,7 @@ public abstract class AbstractRestServicesTest
public static String getAdminAuthzHeader() public static String getAdminAuthzHeader()
{ {
String adminPwdSysProps = System.getProperty( "rest.admin.pwd" ); return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, BaseSetup.getAdminPwd() );
if ( StringUtils.isBlank( adminPwdSysProps ) )
{
return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, FakeCreateAdminService.ADMIN_TEST_PWD );
}
return encode( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, adminPwdSysProps );
} }
protected String getSpringConfigLocation() protected String getSpringConfigLocation()
@ -169,10 +164,12 @@ public abstract class AbstractRestServicesTest
User adminUser = new User(); User adminUser = new User();
adminUser.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME ); adminUser.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
adminUser.setPassword( FakeCreateAdminServiceImpl.ADMIN_TEST_PWD ); adminUser.setPassword( BaseSetup.getAdminPwd() );
adminUser.setFullName( "the admin user" ); adminUser.setFullName( "the admin user" );
adminUser.setEmail( "toto@toto.fr" ); adminUser.setEmail( "toto@toto.fr" );
Boolean res = userService.createAdminUser( adminUser ).isSuccess(); if( !userService.createAdminUser( adminUser ).isSuccess( ) ) {
log.info( "Could not create admin user." );
}
FakeCreateAdminService fakeCreateAdminService = getFakeCreateAdminService(); FakeCreateAdminService fakeCreateAdminService = getFakeCreateAdminService();
//assertTrue( res.booleanValue() ); //assertTrue( res.booleanValue() );

View File

@ -0,0 +1,52 @@
package org.apache.archiva.redback.rest.services;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.atomic.AtomicReference;
public class BaseSetup
{
public static final String SYSPROP_START_SERVER = "archiva.rest.start.server";
public static final String SYSPROP_SERVER_PORT = "archiva.rest.server.port";
public static final String SYSPROP_SERVER_BASE_URI = "archiva.rest.server.baseuri";
public static final String SYSPROP_SERVER_ADMIN_PWD = "rest.admin.pwd";
public static String DEFAULT_ADMIN_PWD = "Ackd245aer9sdfan";
public static AtomicReference<String> adminPwd = new AtomicReference<>( null );
public static String getAdminPwd() {
final String result = adminPwd.get( );
if (StringUtils.isEmpty(result)) {
String pwd = System.getProperty( SYSPROP_SERVER_ADMIN_PWD, DEFAULT_ADMIN_PWD );
if ( StringUtils.isEmpty( pwd ) )
{
pwd = DEFAULT_ADMIN_PWD;
}
adminPwd.compareAndSet(null, pwd );
return pwd;
} else {
return result;
}
}
}

View File

@ -32,8 +32,6 @@ import javax.ws.rs.core.MediaType;
public interface FakeCreateAdminService public interface FakeCreateAdminService
{ {
public static final String ADMIN_TEST_PWD = "rose210208";
@Path( "/testAuthzWithoutKarmasNeeded" ) @Path( "/testAuthzWithoutKarmasNeeded" )
@GET @GET
@Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML} ) @Produces( { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML} )

View File

@ -22,6 +22,8 @@ import org.apache.archiva.components.apacheds.ApacheDs;
import org.apache.archiva.redback.rest.api.model.LdapGroupMapping; import org.apache.archiva.redback.rest.api.model.LdapGroupMapping;
import org.apache.archiva.redback.rest.api.services.LdapGroupMappingService; import org.apache.archiva.redback.rest.api.services.LdapGroupMappingService;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext;
@ -68,6 +70,7 @@ public class LdapGroupMappingServiceTest
return "classpath*:spring-context.xml,classpath*:META-INF/spring-context.xml,classpath:/ldap-spring-test.xml"; return "classpath*:spring-context.xml,classpath*:META-INF/spring-context.xml,classpath:/ldap-spring-test.xml";
} }
@Before
@Override @Override
public void startServer() public void startServer()
throws Exception throws Exception
@ -97,6 +100,7 @@ public class LdapGroupMappingServiceTest
createGroups(); createGroups();
} }
@After
@Override @Override
public void stopServer() public void stopServer()
throws Exception throws Exception

View File

@ -41,7 +41,7 @@ public class LoginServiceTest
throws Exception throws Exception
{ {
assertNotNull( getLoginService( null ).logIn( new LoginRequest( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, assertNotNull( getLoginService( null ).logIn( new LoginRequest( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME,
FakeCreateAdminService.ADMIN_TEST_PWD ) ) ); BaseSetup.getAdminPwd() ) ) );
} }
@Test @Test

View File

@ -22,6 +22,7 @@ import io.restassured.RestAssured;
import io.restassured.builder.RequestSpecBuilder; import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.RequestSpecification; import io.restassured.specification.RequestSpecification;
import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants; import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
import org.apache.archiva.redback.rest.services.BaseSetup;
import org.apache.archiva.redback.rest.services.FakeCreateAdminServiceImpl; import org.apache.archiva.redback.rest.services.FakeCreateAdminServiceImpl;
import org.apache.archiva.redback.role.RoleManager; import org.apache.archiva.redback.role.RoleManager;
import org.apache.archiva.redback.role.RoleManagerException; import org.apache.archiva.redback.role.RoleManagerException;
@ -49,55 +50,53 @@ import java.util.concurrent.atomic.AtomicReference;
import static io.restassured.RestAssured.baseURI; import static io.restassured.RestAssured.baseURI;
import static io.restassured.RestAssured.port; import static io.restassured.RestAssured.port;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.apache.archiva.redback.rest.services.BaseSetup.*;
/** /**
*
* Native REST tests do not use the JAX-RS client and can be used with a remote * Native REST tests do not use the JAX-RS client and can be used with a remote
* REST API service. The tests * REST API service. The tests
* *
* @author Martin Stockhammer <martin_s@apache.org> * @author Martin Stockhammer <martin_s@apache.org>
*/ */
@Tag("rest-native") @Tag( "rest-native" )
public abstract class AbstractNativeRestServices public abstract class AbstractNativeRestServices
{ {
public static final String SYSPROP_START_SERVER = "archiva.rest.start.server";
public static final String SYSPROP_SERVER_PORT = "archiva.rest.server.port";
public static final String SYSPROP_SERVER_BASE_URI = "archiva.rest.server.baseuri";
public static final String SYSPROP_SERVER_ADMIN_PWD = "archiva.rest.server.admin_pwd";
public static final int STOPPED = 0; public static final int STOPPED = 0;
public static final int STOPPING = 1; public static final int STOPPING = 1;
public static final int STARTING = 2; public static final int STARTING = 2;
public static final int STARTED = 3; public static final int STARTED = 3;
public static final int ERROR = 4; public static final int ERROR = 4;
public static final String DEFAULT_ADMIN_PWD = "Ackd245_aer9sdfa#sjDfn";
private RequestSpecification requestSpec; private RequestSpecification requestSpec;
protected Logger log = LoggerFactory.getLogger( getClass() ); protected Logger log = LoggerFactory.getLogger( getClass( ) );
private static AtomicReference<Server> server = new AtomicReference<>(); private static AtomicReference<Server> server = new AtomicReference<>( );
private static AtomicReference<ServerConnector> serverConnector = new AtomicReference<>(); private static AtomicReference<ServerConnector> serverConnector = new AtomicReference<>( );
private static AtomicInteger serverStarted = new AtomicInteger( STOPPED ); private static AtomicInteger serverStarted = new AtomicInteger( STOPPED );
private UserManager userManager; private UserManager userManager;
private RoleManager roleManager; private RoleManager roleManager;
private String adminPwd; private String adminPwd;
public AbstractNativeRestServices( ) public AbstractNativeRestServices( )
{ {
this.adminPwd = System.getProperty( SYSPROP_SERVER_ADMIN_PWD, DEFAULT_ADMIN_PWD ); this.adminPwd = BaseSetup.getAdminPwd( );
} }
protected abstract String getServicePath(); protected abstract String getServicePath( );
protected String getSpringConfigLocation() protected String getSpringConfigLocation( )
{ {
return "classpath*:spring-context.xml,classpath*:META-INF/spring-context.xml"; return "classpath*:spring-context.xml,classpath*:META-INF/spring-context.xml";
} }
protected RequestSpecification getRequestSpec() { protected RequestSpecification getRequestSpec( )
{
return this.requestSpec; return this.requestSpec;
} }
protected String getContextRoot() protected String getContextRoot( )
{ {
return "/api"; return "/api";
} }
@ -110,39 +109,49 @@ public abstract class AbstractNativeRestServices
protected String getBasePath( ) protected String getBasePath( )
{ {
return new StringBuilder( ) return new StringBuilder( )
.append(getContextRoot( )) .append( getContextRoot( ) )
.append(getServiceBasePath( )) .append( getServiceBasePath( ) )
.append(getServicePath( )).toString(); .append( getServicePath( ) ).toString( );
} }
/** /**
* Returns the server that was started, or null if not initialized before. * Returns the server that was started, or null if not initialized before.
*
* @return * @return
*/ */
public Server getServer() { public Server getServer( )
return this.server.get(); {
return this.server.get( );
} }
public int getServerPort() { public int getServerPort( )
ServerConnector connector = serverConnector.get(); {
if (connector!=null) { ServerConnector connector = serverConnector.get( );
return connector.getLocalPort(); if ( connector != null )
} else { {
return connector.getLocalPort( );
}
else
{
return 0; return 0;
} }
} }
/** /**
* Returns true, if the server does exist and is running. * Returns true, if the server does exist and is running.
*
* @return true, if server does exist and is running. * @return true, if server does exist and is running.
*/ */
public boolean isServerRunning() { public boolean isServerRunning( )
return serverStarted.get()==STARTED && this.server.get() != null && this.server.get().isRunning(); {
return serverStarted.get( ) == STARTED && this.server.get( ) != null && this.server.get( ).isRunning( );
} }
private UserManager getUserManager() { private UserManager getUserManager( )
if (this.userManager==null) { {
if ( this.userManager == null )
{
UserManager userManager = ContextLoaderListener.getCurrentWebApplicationContext( ) UserManager userManager = ContextLoaderListener.getCurrentWebApplicationContext( )
.getBean( "userManager#default", UserManager.class ); .getBean( "userManager#default", UserManager.class );
assertNotNull( userManager ); assertNotNull( userManager );
@ -151,8 +160,10 @@ public abstract class AbstractNativeRestServices
return this.userManager; return this.userManager;
} }
private RoleManager getRoleManager() { private RoleManager getRoleManager( )
if (this.roleManager==null) { {
if ( this.roleManager == null )
{
RoleManager roleManager = ContextLoaderListener.getCurrentWebApplicationContext( ) RoleManager roleManager = ContextLoaderListener.getCurrentWebApplicationContext( )
.getBean( "roleManager", RoleManager.class ); .getBean( "roleManager", RoleManager.class );
assertNotNull( roleManager ); assertNotNull( roleManager );
@ -161,15 +172,17 @@ public abstract class AbstractNativeRestServices
return this.roleManager; return this.roleManager;
} }
protected String getAdminPwd() { protected String getAdminPwd( )
return this.adminPwd; {
return BaseSetup.getAdminPwd( );
} }
protected String getAdminUser() { protected String getAdminUser( )
{
return RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME; return RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME;
} }
private void setupAdminUser() throws UserManagerException, RoleManagerException private void setupAdminUser( ) throws UserManagerException, RoleManagerException
{ {
UserManager um = getUserManager( ); UserManager um = getUserManager( );
@ -177,31 +190,36 @@ public abstract class AbstractNativeRestServices
User adminUser = null; User adminUser = null;
try try
{ {
adminUser = um.findUser( getAdminUser() ); adminUser = um.findUser( getAdminUser( ) );
} catch ( UserNotFoundException e ) { }
catch ( UserNotFoundException e )
{
// ignore // ignore
} }
if (adminUser==null) adminUser = um.createUser( getAdminUser( ), "Administrator", "admin@local.home" );
adminUser.setUsername( getAdminUser( ) );
adminUser.setPassword( getAdminPwd( ) );
adminUser.setFullName( "the admin user" );
adminUser.setEmail( "toto@toto.fr" );
adminUser.setPermanent( true );
adminUser.setValidated( true );
adminUser.setLocked( false );
adminUser.setPasswordChangeRequired( false );
if ( adminUser == null )
{ {
adminUser = um.createUser( getAdminUser(), "Administrator", "admin@local.home" );
adminUser.setUsername( getAdminUser() );
adminUser.setPassword( getAdminPwd() );
adminUser.setFullName( "the admin user" );
adminUser.setEmail( "toto@toto.fr" );
adminUser.setPermanent( true );
adminUser.setValidated( true );
adminUser.setLocked( false );
adminUser.setPasswordChangeRequired( false );
um.addUser( adminUser ); um.addUser( adminUser );
getRoleManager( ).assignRole( "system-administrator", adminUser.getUsername( ) );
} }
else
{
um.updateUser( adminUser, false);
}
getRoleManager( ).assignRole( "system-administrator", adminUser.getUsername( ) );
} }
public void startServer() public void startServer( )
throws Exception throws Exception
{ {
if (serverStarted.compareAndSet( STOPPED, STARTING )) if ( serverStarted.compareAndSet( STOPPED, STARTING ) )
{ {
try try
{ {
@ -227,10 +245,12 @@ public abstract class AbstractNativeRestServices
log.debug( "Jetty dump: {}", getServer( ).dump( ) ); log.debug( "Jetty dump: {}", getServer( ).dump( ) );
} }
setupAdminUser(); setupAdminUser( );
log.info( "Started server on port {}", getServerPort( ) ); log.info( "Started server on port {}", getServerPort( ) );
serverStarted.set( STARTED ); serverStarted.set( STARTED );
} finally { }
finally
{
// In case, if the last statement was not reached // In case, if the last statement was not reached
serverStarted.compareAndSet( STARTING, ERROR ); serverStarted.compareAndSet( STARTING, ERROR );
} }
@ -238,7 +258,7 @@ public abstract class AbstractNativeRestServices
} }
public void stopServer() public void stopServer( )
throws Exception throws Exception
{ {
if ( this.serverStarted.compareAndSet( STARTED, STOPPING ) ) if ( this.serverStarted.compareAndSet( STARTED, STOPPING ) )
@ -248,14 +268,18 @@ public abstract class AbstractNativeRestServices
final Server myServer = getServer( ); final Server myServer = getServer( );
if ( myServer != null ) if ( myServer != null )
{ {
log.info("Stopping server"); log.info( "Stopping server" );
myServer.stop(); myServer.stop( );
} }
serverStarted.set( STOPPED ); serverStarted.set( STOPPED );
} finally { }
finally
{
serverStarted.compareAndSet( STOPPING, ERROR ); serverStarted.compareAndSet( STOPPING, ERROR );
} }
} else { }
else
{
log.error( "Serer is not in STARTED state!" ); log.error( "Serer is not in STARTED state!" );
} }
} }
@ -298,8 +322,8 @@ public abstract class AbstractNativeRestServices
RestAssured.basePath = basePath; RestAssured.basePath = basePath;
} }
protected void shutdownNative() throws Exception protected void shutdownNative( ) throws Exception
{ {
stopServer(); stopServer( );
} }
} }

View File

@ -27,6 +27,7 @@ import org.apache.archiva.redback.authentication.Token;
import org.apache.archiva.redback.authentication.jwt.JwtAuthenticator; import org.apache.archiva.redback.authentication.jwt.JwtAuthenticator;
import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants; import org.apache.archiva.redback.integration.security.role.RedbackRoleConstants;
import org.apache.archiva.redback.rest.api.services.v2.AuthenticationService; import org.apache.archiva.redback.rest.api.services.v2.AuthenticationService;
import org.apache.archiva.redback.rest.services.BaseSetup;
import org.apache.archiva.redback.rest.services.FakeCreateAdminService; import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
import org.apache.archiva.redback.rest.services.FakeCreateAdminServiceImpl; import org.apache.archiva.redback.rest.services.FakeCreateAdminServiceImpl;
import org.apache.archiva.redback.role.RoleManager; import org.apache.archiva.redback.role.RoleManager;
@ -269,19 +270,21 @@ public abstract class AbstractRestServicesTestV2
} catch ( UserNotFoundException e ) { } catch ( UserNotFoundException e ) {
// ignore // ignore
} }
adminUser = um.createUser( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, "Administrator", "admin@local.home" );
adminUser.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
adminUser.setPassword( BaseSetup.getAdminPwd() );
adminUser.setFullName( "the admin user" );
adminUser.setEmail( "toto@toto.fr" );
adminUser.setPermanent( true );
adminUser.setValidated( true );
adminUser.setLocked( false );
adminUser.setPasswordChangeRequired( false );
if (adminUser==null) if (adminUser==null)
{ {
adminUser = um.createUser( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, "Administrator", "admin@local.home" );
adminUser.setUsername( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME );
adminUser.setPassword( FakeCreateAdminServiceImpl.ADMIN_TEST_PWD );
adminUser.setFullName( "the admin user" );
adminUser.setEmail( "toto@toto.fr" );
adminUser.setPermanent( true );
adminUser.setValidated( true );
adminUser.setLocked( false );
adminUser.setPasswordChangeRequired( false );
um.addUser( adminUser ); um.addUser( adminUser );
getRoleManager( ).assignRole( "system-administrator", adminUser.getUsername( ) );
} else {
um.updateUser( adminUser, false );
getRoleManager( ).assignRole( "system-administrator", adminUser.getUsername( ) ); getRoleManager( ).assignRole( "system-administrator", adminUser.getUsername( ) );
} }

View File

@ -25,6 +25,7 @@ import org.apache.archiva.redback.rest.api.model.Token;
import org.apache.archiva.redback.rest.api.model.TokenResponse; import org.apache.archiva.redback.rest.api.model.TokenResponse;
import org.apache.archiva.redback.rest.api.services.RedbackServiceException; import org.apache.archiva.redback.rest.api.services.RedbackServiceException;
import org.apache.archiva.redback.rest.api.services.UserService; import org.apache.archiva.redback.rest.api.services.UserService;
import org.apache.archiva.redback.rest.services.BaseSetup;
import org.apache.archiva.redback.rest.services.FakeCreateAdminService; import org.apache.archiva.redback.rest.services.FakeCreateAdminService;
import org.apache.archiva.redback.users.User; import org.apache.archiva.redback.users.User;
import org.apache.archiva.redback.users.UserManager; import org.apache.archiva.redback.users.UserManager;
@ -66,8 +67,12 @@ public class AuthenticationServiceTest
public void loginAdmin() public void loginAdmin()
throws Exception throws Exception
{ {
assertNotNull( getLoginServiceV2( null ).logIn( new RequestTokenRequest( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME, RequestTokenRequest request = new RequestTokenRequest( RedbackRoleConstants.ADMINISTRATOR_ACCOUNT_NAME,
FakeCreateAdminService.ADMIN_TEST_PWD ) ) ); BaseSetup.getAdminPwd() );
request.setGrantType( "authorization_code" );
assertNotNull( getLoginServiceV2( null ).logIn( request ) );
} }
@Test @Test
@ -120,6 +125,7 @@ public class AuthenticationServiceTest
um.updateUser( user ); um.updateUser( user );
// END SNIPPET: create-user // END SNIPPET: create-user
RequestTokenRequest request = new RequestTokenRequest( "toto", "foo123" ); RequestTokenRequest request = new RequestTokenRequest( "toto", "foo123" );
request.setGrantType( "authorization_code" );
TokenResponse result = getLoginServiceV2( "" ).logIn( request ); TokenResponse result = getLoginServiceV2( "" ).logIn( request );
// assertNotNull( result ); // assertNotNull( result );
// assertEquals( "toto", result.getUsername( ) ); // assertEquals( "toto", result.getUsername( ) );