diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/CredentialROToDBCredentialConverter.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/CredentialROToDBCredentialConverter.java index 2774ac1d8c8e62c80625c73c0c33e831152651df..a9cf0e51dde8aed25bbaefd3e78730a83c913c95 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/CredentialROToDBCredentialConverter.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/CredentialROToDBCredentialConverter.java @@ -22,6 +22,7 @@ public class CredentialROToDBCredentialConverter implements Converter<Credential target.setId(SessionSecurityUtils.decryptEntityId(source.getCredentialId())); } target.setName(source.getName()); + target.setCredentialType(source.getCredentialType()); target.setActive(source.isActive()); target.setDescription(source.getDescription()); target.setSequentialLoginFailureCount(source.getSequentialLoginFailureCount()); diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBCredentialToCredentialROConverter.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBCredentialToCredentialROConverter.java index 2786afad971f887bfff77857e8893d1331066fb0..aab6577eb020ce9206653b91ce563ad9fa4b9243 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBCredentialToCredentialROConverter.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/conversion/DBCredentialToCredentialROConverter.java @@ -31,6 +31,7 @@ public class DBCredentialToCredentialROConverter implements Converter<DBCredenti target.setCredentialId(SessionSecurityUtils.encryptedEntityId(source.getId())); target.setName(source.getName()); target.setActive(source.isActive()); + target.setCredentialType(source.getCredentialType()); target.setDescription(source.getDescription()); target.setSequentialLoginFailureCount(source.getSequentialLoginFailureCount()); target.setLastFailedLoginAttempt(source.getLastFailedLoginAttempt()); diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/CRLVerifierService.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/CRLVerifierService.java index 0aec603989ff87b1d94ba897510ca51323dba40d..0fcdc3558951529d82eade5bb82245bbf2c5ee1e 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/CRLVerifierService.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/CRLVerifierService.java @@ -39,7 +39,6 @@ import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.security.auth.x500.X500Principal; @@ -66,9 +65,12 @@ public class CRLVerifierService implements ICRLVerifierService { private static final X500Principal NULL_ISSUER = new X500Principal(""); private static final CRLReason NULL_CRL_REASON = CRLReason.UNSPECIFIED; - @Autowired - ConfigurationService configurationService; + protected final ConfigurationService configurationService; + + public CRLVerifierService(ConfigurationService configurationService) { + this.configurationService = configurationService; + } @Override public void verifyCertificateCRLs(X509Certificate cert) throws CertificateRevokedException, CertificateParsingException { @@ -156,13 +158,13 @@ public class CRLVerifierService implements ICRLVerifierService { crl = (X509CRL) cf.generateCRL(crlStream); } } catch (IOException e) { - exception = new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "Can not download CRL '" + crlURL+"'" + exception = new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "Can not download CRL '" + crlURL + "'" , ExceptionUtils.getRootCauseMessage(e), e); } catch (CertificateException e) { - exception = new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "CRL list is not supported '" + crlURL+"'" + exception = new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "CRL list is not supported '" + crlURL + "'" , ExceptionUtils.getRootCauseMessage(e), e); } catch (CRLException e) { - exception = new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "CRL can not be read: '" + crlURL+"'" + exception = new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "CRL can not be read: '" + crlURL + "'" , ExceptionUtils.getRootCauseMessage(e), e); } catch (SMPRuntimeException exc) { exception = exc; @@ -201,7 +203,7 @@ public class CRLVerifierService implements ICRLVerifierService { } return inputStream; } catch (Exception exc) { - throw new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "Error occurred while downloading CRL:'" + crlURL+"'", ExceptionUtils.getRootCauseMessage(exc) ); + throw new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "Error occurred while downloading CRL:'" + crlURL + "'", ExceptionUtils.getRootCauseMessage(exc)); } } @@ -235,7 +237,7 @@ public class CRLVerifierService implements ICRLVerifierService { return execute(HttpClients.createDefault(), new HttpGet(url)); } - private InputStream execute(CloseableHttpClient httpclient, HttpGet httpget) throws IOException { + protected InputStream execute(CloseableHttpClient httpclient, HttpGet httpget) throws IOException { try (CloseableHttpResponse response = httpclient.execute(httpget)) { return IOUtils.loadIntoBAIS(response.getEntity().getContent()); } @@ -250,14 +252,14 @@ public class CRLVerifierService implements ICRLVerifierService { return true; } - private boolean isValidParameter(String... parameters) { + protected boolean isValidParameter(String... parameters) { if (parameters == null || parameters.length == 0) { return false; } for (String parameter : Arrays.asList(parameters)) { - if (StringUtils.isEmpty(parameter)) { + if (StringUtils.isBlank(parameter)) { return false; } } diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIDomainService.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIDomainService.java index 1ffceef42929acde004e4714f735a533b2ef82e7..a64af55725d027271146489f2fb2ded8de5a6235 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIDomainService.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIDomainService.java @@ -100,6 +100,9 @@ public class UIDomainService extends UIServiceBase<DBDomain, DomainRO> { @Transactional public void createDomainData(DomainRO data) { + if (StringUtils.isBlank(data.getDomainCode())){ + throw new SMPRuntimeException(ErrorCode.INVALID_DOMAIN_DATA, "Domain code must not be empty!"); + }; if (domainDao.getDomainByCode(data.getDomainCode()).isPresent()){ throw new SMPRuntimeException(ErrorCode.INVALID_DOMAIN_DATA, "Domain with code ["+data.getDomainCode()+"] already exists!"); diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceService.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceService.java index 5f2a03cf70781b053a3e0bfba733a3717ce783f4..b2c4e3e1ddb6ba501ecb234da308e04c78b29d3a 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceService.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceService.java @@ -191,7 +191,7 @@ public class UIResourceService { Optional<DBResource> existResource = resourceDao.getResource(resourceIdentifier.getValue(),resourceIdentifier.getScheme(), optRedef.get(), group.getDomain()); if (existResource.isPresent()) { - throw new SMPRuntimeException(ErrorCode.INVALID_REQUEST, ACTION_RESOURCE_CREATE, "Resource definition [val:" + resourceRO.getIdentifierValue() + " scheme:" + resourceRO.getIdentifierScheme() + "] already exists for domain!"); + throw new SMPRuntimeException(ErrorCode.INVALID_REQUEST, ACTION_RESOURCE_CREATE, "Resource [val:" + resourceRO.getIdentifierValue() + " scheme:" + resourceRO.getIdentifierScheme() + "] already exists for domain!"); } diff --git a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java index 9eff4c771001f60e6cd06bfd1350939288a92a61..2ec17d2b745cb7d66fc575d8c1c09c475b92b622 100644 --- a/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java +++ b/smp-server-library/src/main/java/eu/europa/ec/edelivery/smp/services/ui/UIUserService.java @@ -368,7 +368,6 @@ public class UIUserService extends UIServiceBase<DBUser, UserRO> { UserRO result = convertToRo(user); return result; - } public List<CredentialRO> getUserCredentials(Long userId, diff --git a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/CRLVerifierServiceTest.java b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/CRLVerifierServiceTest.java index c4df3e45dc75fcd86ee48e04d3df99187c3f63e7..b9d4cd886adfac062d282bbb6326905bd314e5a5 100644 --- a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/CRLVerifierServiceTest.java +++ b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/CRLVerifierServiceTest.java @@ -2,46 +2,36 @@ package eu.europa.ec.edelivery.smp.services; import eu.europa.ec.edelivery.smp.exceptions.ErrorCode; import eu.europa.ec.edelivery.smp.exceptions.SMPRuntimeException; -import org.junit.*; -import org.junit.rules.ExpectedException; +import org.apache.commons.lang3.StringUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.util.ReflectionTestUtils; import java.io.IOException; -import java.security.Security; +import java.io.InputStream; import java.security.cert.*; -import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertThrows; +import static org.hamcrest.Matchers.startsWith; +import static org.junit.jupiter.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; -public class CRLVerifierServiceTest extends AbstractServiceIntegrationTest { +public class CRLVerifierServiceTest { - @Rule - public ExpectedException expectedEx = ExpectedException.none(); + ConfigurationService mockConfigurationService = Mockito.mock(ConfigurationService.class); - @Autowired - private CRLVerifierService crlVerifierServiceInstance; + private CRLVerifierService testInstance = new CRLVerifierService(mockConfigurationService); - @Autowired - private ConfigurationService configurationService; - - - @BeforeClass - public static void beforeClass() throws Exception { - Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); - } - - @Before + @BeforeEach public void beforeMethods() { - crlVerifierServiceInstance = Mockito.spy(crlVerifierServiceInstance); - configurationService = Mockito.spy(configurationService); - ReflectionTestUtils.setField(crlVerifierServiceInstance, "configurationService", configurationService); + doReturn(true).when(mockConfigurationService).forceCRLValidation(); // force verification - Mockito.doReturn(true).when(configurationService).forceCRLValidation(); + testInstance = Mockito.spy(testInstance); } @@ -53,25 +43,25 @@ public class CRLVerifierServiceTest extends AbstractServiceIntegrationTest { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CRL crl = (X509CRL) cf.generateCRL(getClass().getResourceAsStream("/certificates/smp-crl-test.crl")); - Mockito.doReturn(crl).when(crlVerifierServiceInstance).getCRLByURL("https://localhost/clr"); + doReturn(crl).when(testInstance).getCRLByURL("https://localhost/clr"); // when-then - crlVerifierServiceInstance.verifyCertificateCRLs(certificate); + testInstance.verifyCertificateCRLs(certificate); // must not throw exception } @Test - public void verifyCertificateCRLRevokedTest() throws CertificateException, CRLException, IOException { + public void verifyCertificateCRLRevokedTest() throws CertificateException, CRLException { // given X509Certificate certificate = loadCertificate("smp-crl-revoked.pem"); - CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CRL crl = (X509CRL) cf.generateCRL(getClass().getResourceAsStream("/certificates/smp-crl-test.crl")); - Mockito.doReturn(crl).when(crlVerifierServiceInstance).getCRLByURL("https://localhost/crl"); + doReturn(crl).when(testInstance).getCRLByURL("https://localhost/crl"); - CertificateRevokedException result = assertThrows(CertificateRevokedException.class, () -> crlVerifierServiceInstance.verifyCertificateCRLs(certificate)); + CertificateRevokedException result = assertThrows(CertificateRevokedException.class, + () -> testInstance.verifyCertificateCRLs(certificate)); assertThat(result.getMessage(), startsWith("Certificate has been revoked, reason: UNSPECIFIED")); } @@ -79,59 +69,91 @@ public class CRLVerifierServiceTest extends AbstractServiceIntegrationTest { public void verifyCertificateCRLsX509FailsToConnectTest() throws CertificateException { // given X509Certificate certificate = loadCertificate("smp-crl-test-all.pem"); - - expectedEx.expect(SMPRuntimeException.class); - expectedEx.expectMessage("Certificate error [Error occurred while downloading CRL:'https://localhost/clr']. Error: ConnectException: Connection refused (Connection refused)!"); - - // when-then - crlVerifierServiceInstance.verifyCertificateCRLs(certificate); + // when + SMPRuntimeException result = assertThrows(SMPRuntimeException.class, () -> + testInstance.verifyCertificateCRLs(certificate)); + // then + assertThat(result.getMessage(), + startsWith("Certificate error [Error occurred while downloading CRL:'https://localhost/clr']. Error: ConnectException: Connection refused (Connection refused)!")); } @Test - public void downloadCRLWrongUrlSchemeTest() throws CertificateException, CRLException, IOException { + public void downloadCRLWrongUrlSchemeTest() { - X509CRL crl = crlVerifierServiceInstance.downloadCRL("wrong://localhost/crl", true); + X509CRL crl = testInstance.downloadCRL("wrong://localhost/crl", true); assertNull(crl); } @Test - public void downloadCRLUrlSchemeLdapTest() throws CertificateException, CRLException, IOException { + public void downloadCRLUrlSchemeLdapTest() { - X509CRL crl = crlVerifierServiceInstance.downloadCRL("ldap://localhost/crl", true); + X509CRL crl = testInstance.downloadCRL("ldap://localhost/crl", true); assertNull(crl); } @Test - public void verifyCertificateCRLsRevokedSerialTest() throws CertificateException, CRLException, IOException { + public void verifyCertificateCRLsRevokedSerialTest() throws CertificateException, CRLException { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509CRL crl = (X509CRL) cf.generateCRL(getClass().getResourceAsStream("/certificates/smp-crl-test.crl")); - Mockito.doReturn(crl).when(crlVerifierServiceInstance).downloadCRL("https://localhost/crl", true); + doReturn(crl).when(testInstance).getCRLByURL("https://localhost/crl"); - CertificateRevokedException result = assertThrows(CertificateRevokedException.class, () ->crlVerifierServiceInstance.verifyCertificateCRLs("11", "https://localhost/crl")); + CertificateRevokedException result = assertThrows(CertificateRevokedException.class, () -> testInstance.verifyCertificateCRLs("11", "https://localhost/crl")); assertThat(result.getMessage(), startsWith("Certificate has been revoked, reason: UNSPECIFIED")); } @Test - public void verifyCertificateCRLsRevokedSerialTestThrowIOExceptionHttps() throws CertificateException, IOException, CRLException { + public void verifyCertificateCRLsRevokedSerialTestThrowIOExceptionHttps() { String crlURL = "https://localhost/crl"; - Mockito.doThrow(new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "Can not download CRL '" + crlURL + "'", "IOException: Can not access URL")).when(crlVerifierServiceInstance).downloadCRL("https://localhost/crl", true); + doThrow(new SMPRuntimeException(ErrorCode.CERTIFICATE_ERROR, "Can not download CRL '" + crlURL + "'", "IOException: Can not access URL")) + .when(testInstance).getCRLByURL("https://localhost/crl"); + // when + SMPRuntimeException result = assertThrows(SMPRuntimeException.class, () -> testInstance.verifyCertificateCRLs("11", "https://localhost/crl")); + // then + assertThat(result.getMessage(), startsWith("Certificate error [Can not download CRL 'https://localhost/crl']. Error: IOException: Can not access URL")); + } - expectedEx.expect(SMPRuntimeException.class); - expectedEx.expectMessage("Certificate error [Can not download CRL 'https://localhost/crl']. Error: IOException: Can not access URL!"); + @ParameterizedTest + @CsvSource({ + "param1, true", + "param1|param2, true", + ", false", + "'', false", + "' |test', false", + "test| |test, false", + }) + public void testIsValidParameter(String values, boolean expectedResult) { + //given + String[] parameters = StringUtils.split(values, '|'); + //when + boolean result = testInstance.isValidParameter(parameters); + //then + assertEquals(expectedResult, result); + } - // when-then - crlVerifierServiceInstance.verifyCertificateCRLs("11", "https://localhost/crl"); + @Test + public void testDownloadURLViaProxy() throws IOException { + //given + String url = "https://localhost/crl"; + String proxy = "localhost"; + int proxyPort = 8080; + String proxyUser = "user"; + String proxyPassword = "password"; + InputStream inputStream = Mockito.mock(InputStream.class); + doReturn(inputStream).when(testInstance).execute(any(), any()); + //when + InputStream result = testInstance.downloadURLViaProxy(url, proxy, proxyPort, proxyUser, proxyPassword); + //then + assertEquals(inputStream, result); } private X509Certificate loadCertificate(String filename) throws CertificateException { CertificateFactory fact = CertificateFactory.getInstance("X.509"); - X509Certificate cer = (X509Certificate) + return (X509Certificate) fact.generateCertificate(getClass().getResourceAsStream("/certificates/" + filename)); - return cer; } } diff --git a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ConfigurationServiceAllGetMethodsTest.java b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ConfigurationServiceAllGetMethodsTest.java index 69e363642d310d8c902cfe3377c06e45ed2e4733..fd918d2874e3885ec1e9d3ac9b8d37010378afba 100644 --- a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ConfigurationServiceAllGetMethodsTest.java +++ b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ConfigurationServiceAllGetMethodsTest.java @@ -2,6 +2,7 @@ package eu.europa.ec.edelivery.smp.services; import eu.europa.ec.edelivery.smp.data.dao.ConfigurationDao; import eu.europa.ec.edelivery.smp.config.enums.SMPPropertyEnum; +import eu.europa.ec.edelivery.smp.data.ui.enums.AlertLevelEnum; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.reflect.MethodUtils; import org.junit.Test; @@ -20,15 +21,16 @@ import static org.mockito.Mockito.*; @RunWith(Parameterized.class) public class ConfigurationServiceAllGetMethodsTest { - private static String TEST_STRING = "TestString"; - private static List<String> TEST_STRING_LIST = Arrays.asList("TestString1","TestString2","TestString3"); - private static Map<String, String> TEST_MAP = new HashMap<>(); - private static Pattern TEST_REXEXP= Pattern.compile(".*"); - private static File TEST_FILE= new File("/tmp/file"); + private static final String TEST_STRING = "TestString"; + private static final List<String> TEST_STRING_LIST = Arrays.asList("TestString1", "TestString2", "TestString3"); + private static final Map<String, String> TEST_MAP = new HashMap<>(); + private static final Pattern TEST_REXEXP = Pattern.compile(".*"); + private static final File TEST_FILE = new File("/tmp/file"); private static URL TEST_URL; + static { try { - TEST_URL= new URL("http://test:123/path"); + TEST_URL = new URL("http://test:123/path"); } catch (Exception e) { fail("Fail to generated test data" + ExceptionUtils.getRootCauseMessage(e)); } @@ -40,19 +42,19 @@ public class ConfigurationServiceAllGetMethodsTest { @Parameterized.Parameters(name = "{index}: {0}") public static Collection<Object[]> data() { // set property values for property, set value, method name, value or property, value (true) or property (false) - return Arrays.asList(new Object[][] { + return Arrays.asList(new Object[][]{ {EXTERNAL_TLS_AUTHENTICATION_CLIENT_CERT_HEADER_ENABLED, Boolean.TRUE, "isExternalTLSAuthenticationWithClientCertHeaderEnabled", true}, {EXTERNAL_TLS_AUTHENTICATION_CERTIFICATE_HEADER_ENABLED, Boolean.TRUE, "isExternalTLSAuthenticationWithSSLClientCertHeaderEnabled", true}, {OUTPUT_CONTEXT_PATH, Boolean.FALSE, "isUrlContextEnabled", true}, //{HTTP_FORWARDED_HEADERS_ENABLED, Boolean.TRUE, "", true}, {HTTP_HSTS_MAX_AGE, 1234, "getHttpHeaderHstsMaxAge", true}, {HTTP_HEADER_SEC_POLICY, TEST_STRING, "getHttpHeaderContentSecurityPolicy", true}, - {HTTP_NO_PROXY_HOSTS,TEST_STRING, "getHttpNoProxyHosts", false}, + {HTTP_NO_PROXY_HOSTS, TEST_STRING, "getHttpNoProxyHosts", false}, {HTTP_PROXY_HOST, TEST_STRING, "getHttpProxyHost", false}, {HTTP_PROXY_PASSWORD, TEST_STRING, "getProxyCredentialToken", true}, {HTTP_PROXY_PORT, 8800, "getHttpProxyPort", true}, {HTTP_PROXY_USER, TEST_STRING, "getProxyUsername", true}, - {PARTC_SCH_VALIDATION_REGEXP, TEST_REXEXP,"getParticipantIdentifierSchemeRexExp", true}, + {PARTC_SCH_VALIDATION_REGEXP, TEST_REXEXP, "getParticipantIdentifierSchemeRexExp", true}, {PARTC_SCH_VALIDATION_REGEXP, TEST_STRING, "getParticipantIdentifierSchemeRexExpPattern", false}, {PARTC_SCH_REGEXP_MSG, TEST_STRING, "getParticipantIdentifierSchemeRexExpMessage", true}, //{PARTC_EBCOREPARTYID_CONCATENATE, Boolean.FALSE, "getForceConcatenateEBCorePartyId", true}, @@ -60,10 +62,10 @@ public class ConfigurationServiceAllGetMethodsTest { {CS_PARTICIPANTS, TEST_STRING_LIST, "getCaseSensitiveParticipantScheme", true}, {CS_DOCUMENTS, TEST_STRING_LIST, "getCaseSensitiveDocumentScheme", true}, {SML_ENABLED, Boolean.FALSE, "isSMLIntegrationEnabled", true}, - {SML_URL,TEST_URL, "getSMLIntegrationUrl", true}, + {SML_URL, TEST_URL, "getSMLIntegrationUrl", true}, {SML_TLS_DISABLE_CN_CHECK, Boolean.FALSE, "smlDisableCNCheck", true}, {SML_TLS_SERVER_CERT_SUBJECT_REGEXP, TEST_REXEXP, "getSMLIntegrationServerCertSubjectRegExp", true}, - {SML_LOGICAL_ADDRESS, TEST_STRING,"getSMLIntegrationSMPLogicalAddress", false}, + {SML_LOGICAL_ADDRESS, TEST_STRING, "getSMLIntegrationSMPLogicalAddress", false}, {SML_PHYSICAL_ADDRESS, TEST_STRING, "getSMLIntegrationSMPPhysicalAddress", false}, {KEYSTORE_PASSWORD, TEST_STRING, "getKeystoreCredentialToken", true}, {KEYSTORE_FILENAME, TEST_FILE, "getKeystoreFile", true}, @@ -76,7 +78,7 @@ public class ConfigurationServiceAllGetMethodsTest { {CERTIFICATE_ALLOWED_CERTIFICATEPOLICY_OIDS, TEST_STRING_LIST, "getAllowedCertificatePolicies", true}, {CERTIFICATE_SUBJECT_REGULAR_EXPRESSION, TEST_REXEXP, "getCertificateSubjectRegularExpression", true}, //{SMP_PROPERTY_REFRESH_CRON, TEST_STRING, "", true}, - {UI_COOKIE_SESSION_SECURE, Boolean.FALSE, "getSessionCookieSecure", true}, + {UI_COOKIE_SESSION_SECURE, Boolean.FALSE, "getSessionCookieSecure", true}, {UI_COOKIE_SESSION_MAX_AGE, 1111, "getSessionCookieMaxAge", true}, {UI_COOKIE_SESSION_SITE, TEST_STRING, "getSessionCookieSameSite", true}, {UI_COOKIE_SESSION_PATH, TEST_STRING, "getSessionCookiePath", true}, @@ -88,8 +90,8 @@ public class ConfigurationServiceAllGetMethodsTest { {PASSWORD_POLICY_REGULAR_EXPRESSION, TEST_STRING, "getPasswordPolicyRexExpPattern", false}, {PASSWORD_POLICY_WARNING_DAYS_BEFORE_EXPIRE, 10, "getPasswordPolicyUIWarningDaysBeforeExpire", true}, {PASSWORD_POLICY_FORCE_CHANGE_EXPIRED, Boolean.TRUE, "getPasswordPolicyForceChangeIfExpired", true}, - {USER_LOGIN_FAIL_DELAY,1000, "getLoginFailDelayInMilliSeconds", true}, - {ACCESS_TOKEN_FAIL_DELAY,1000, "getAccessTokenLoginFailDelayInMilliSeconds", true}, + {USER_LOGIN_FAIL_DELAY, 1000, "getLoginFailDelayInMilliSeconds", true}, + {ACCESS_TOKEN_FAIL_DELAY, 1000, "getAccessTokenLoginFailDelayInMilliSeconds", true}, {USER_MAX_FAILED_ATTEMPTS, 55, "getLoginMaxAttempts", true}, {USER_SUSPENSION_TIME, 3600, "getLoginSuspensionTimeInSeconds", true}, {ACCESS_TOKEN_POLICY_VALID_DAYS, 1212, "getAccessTokenPolicyValidDays", true}, @@ -108,48 +110,58 @@ public class ConfigurationServiceAllGetMethodsTest { {ENCODED_SLASHES_ALLOWED_IN_URL, Boolean.FALSE, "encodedSlashesAllowedInUrl", true}, {SMP_ALERT_CREDENTIALS_SERVER, TEST_STRING, "getTargetServerForCredentialValidation", true}, {SML_TLS_SERVER_CERT_SUBJECT_REGEXP, TEST_STRING, "getSMLIntegrationServerCertSubjectRegExpPattern", false}, - {SML_TLS_TRUSTSTORE_USE_SYSTEM_DEFAULT, Boolean.FALSE , "useSystemTruststoreForTLS", true}, + {SML_TLS_TRUSTSTORE_USE_SYSTEM_DEFAULT, Boolean.FALSE, "useSystemTruststoreForTLS", true}, {SSO_CAS_SMP_LOGIN_URI, TEST_STRING, "getCasSMPLoginRelativePath", true}, {ALERT_USER_LOGIN_FAILURE_ENABLED, Boolean.FALSE, "getAlertUserLoginFailureEnabled", true}, - {ALERT_USER_SUSPENDED_ENABLED, Boolean.FALSE, "getAlertUserSuspendedEnabled", true}, + {ALERT_USER_SUSPENDED_ENABLED, Boolean.FALSE, "getAlertUserSuspendedEnabled", true}, {ALERT_USER_SUSPENDED_MAIL_SUBJECT, TEST_STRING, "getAlertUserSuspendedSubject", true}, - {ALERT_PASSWORD_BEFORE_EXPIRATION_ENABLED, Boolean.FALSE, "getAlertBeforeExpirePasswordEnabled", true}, + {ALERT_PASSWORD_BEFORE_EXPIRATION_ENABLED, Boolean.FALSE, "getAlertBeforeExpirePasswordEnabled", true}, {ALERT_PASSWORD_BEFORE_EXPIRATION_PERIOD, 10, "getAlertBeforeExpirePasswordPeriod", true}, {ALERT_PASSWORD_BEFORE_EXPIRATION_INTERVAL, 10, "getAlertBeforeExpirePasswordInterval", true}, {ALERT_PASSWORD_BEFORE_EXPIRATION_MAIL_SUBJECT, TEST_STRING, "getAlertBeforeExpirePasswordMailSubject", true}, - {ALERT_PASSWORD_EXPIRED_ENABLED, Boolean.FALSE, "getAlertExpiredPasswordEnabled", true}, + {ALERT_PASSWORD_EXPIRED_ENABLED, Boolean.FALSE, "getAlertExpiredPasswordEnabled", true}, {ALERT_PASSWORD_EXPIRED_PERIOD, 10, "getAlertExpiredPasswordPeriod", true}, {ALERT_PASSWORD_EXPIRED_INTERVAL, 10, "getAlertExpiredPasswordInterval", true}, {ALERT_PASSWORD_EXPIRED_MAIL_SUBJECT, TEST_STRING, "getAlertExpiredPasswordMailSubject", true}, - {ALERT_ACCESS_TOKEN_BEFORE_EXPIRATION_ENABLED, Boolean.FALSE, "getAlertBeforeExpireAccessTokenEnabled", true}, + {ALERT_ACCESS_TOKEN_BEFORE_EXPIRATION_ENABLED, Boolean.FALSE, "getAlertBeforeExpireAccessTokenEnabled", true}, {ALERT_ACCESS_TOKEN_BEFORE_EXPIRATION_PERIOD, 10, "getAlertBeforeExpireAccessTokenPeriod", true}, {ALERT_ACCESS_TOKEN_BEFORE_EXPIRATION_INTERVAL, 10, "getAlertBeforeExpireAccessTokenInterval", true}, {ALERT_ACCESS_TOKEN_BEFORE_EXPIRATION_MAIL_SUBJECT, TEST_STRING, "getAlertBeforeExpireAccessTokenMailSubject", true}, - {ALERT_ACCESS_TOKEN_EXPIRED_ENABLED, Boolean.FALSE, "getAlertExpiredAccessTokenEnabled", true}, + {ALERT_ACCESS_TOKEN_EXPIRED_ENABLED, Boolean.FALSE, "getAlertExpiredAccessTokenEnabled", true}, {ALERT_ACCESS_TOKEN_EXPIRED_PERIOD, 10, "getAlertExpiredAccessTokenPeriod", true}, {ALERT_ACCESS_TOKEN_EXPIRED_INTERVAL, 10, "getAlertExpiredAccessTokenInterval", true}, {ALERT_ACCESS_TOKEN_EXPIRED_MAIL_SUBJECT, TEST_STRING, "getAlertExpiredAccessTokenMailSubject", true}, - {ALERT_CERTIFICATE_BEFORE_EXPIRATION_ENABLED, Boolean.FALSE, "getAlertBeforeExpireCertificateEnabled", true}, + {ALERT_CERTIFICATE_BEFORE_EXPIRATION_ENABLED, Boolean.FALSE, "getAlertBeforeExpireCertificateEnabled", true}, {ALERT_CERTIFICATE_BEFORE_EXPIRATION_PERIOD, 10, "getAlertBeforeExpireCertificatePeriod", true}, {ALERT_CERTIFICATE_BEFORE_EXPIRATION_INTERVAL, 10, "getAlertBeforeExpireCertificateInterval", true}, {ALERT_CERTIFICATE_BEFORE_EXPIRATION_MAIL_SUBJECT, TEST_STRING, "getAlertBeforeExpireCertificateMailSubject", true}, - {ALERT_CERTIFICATE_EXPIRED_ENABLED, Boolean.FALSE, "getAlertExpiredCertificateEnabled", true}, + {ALERT_CERTIFICATE_EXPIRED_ENABLED, Boolean.FALSE, "getAlertExpiredCertificateEnabled", true}, {ALERT_CERTIFICATE_EXPIRED_PERIOD, 10, "getAlertExpiredCertificatePeriod", true}, {ALERT_CERTIFICATE_EXPIRED_INTERVAL, 10, "getAlertExpiredCertificateInterval", true}, {ALERT_CERTIFICATE_EXPIRED_MAIL_SUBJECT, TEST_STRING, "getAlertExpiredCertificateMailSubject", true}, {SMP_ALERT_BATCH_SIZE, 10, "getAlertCredentialsBatchSize", true}, {SMP_ALERT_MAIL_FROM, TEST_STRING, "getAlertEmailFrom", true}, + {ALERT_USER_SUSPENDED_LEVEL, AlertLevelEnum.HIGH, "getAlertUserSuspendedLevel", true}, + {ALERT_USER_LOGIN_FAILURE_LEVEL, AlertLevelEnum.HIGH, "getAlertUserLoginFailureLevel", true}, + {ALERT_PASSWORD_BEFORE_EXPIRATION_LEVEL, AlertLevelEnum.HIGH, "getAlertBeforeExpirePasswordLevel", true}, + {ALERT_ACCESS_TOKEN_BEFORE_EXPIRATION_LEVEL, AlertLevelEnum.HIGH, "getAlertBeforeExpireAccessTokenLevel", true}, + {ALERT_ACCESS_TOKEN_EXPIRED_LEVEL, AlertLevelEnum.HIGH, "getAlertExpiredAccessTokenLevel", true}, + {ALERT_CERTIFICATE_BEFORE_EXPIRATION_LEVEL, AlertLevelEnum.HIGH, "getAlertBeforeExpireCertificateLevel", true}, + {ALERT_CERTIFICATE_EXPIRED_LEVEL, AlertLevelEnum.HIGH, "getAlertExpiredCertificateLevel", true}, + + }); } + private final SMPPropertyEnum property; private final Object value; private final String methodName; private final boolean fromValue; - public ConfigurationServiceAllGetMethodsTest(SMPPropertyEnum property, Object value, String methodName,boolean fromValue) { + public ConfigurationServiceAllGetMethodsTest(SMPPropertyEnum property, Object value, String methodName, boolean fromValue) { this.property = property; this.value = value; this.methodName = methodName; @@ -160,14 +172,14 @@ public class ConfigurationServiceAllGetMethodsTest { public void testProperty() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (fromValue) { - doReturn(value).when(configurationDaoMock).getCachedPropertyValue(property); + doReturn(value instanceof AlertLevelEnum ? value.toString() : value).when(configurationDaoMock).getCachedPropertyValue(property); } else { doReturn(value).when(configurationDaoMock).getCachedProperty(property); } Object result = MethodUtils.invokeExactMethod(testInstance, methodName); - if (result instanceof Optional){ + if (result instanceof Optional) { assertEquals(value, ((Optional<?>) result).get()); - }else { + } else { assertEquals(value, result); } } diff --git a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceServiceTest.java b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceServiceTest.java index e60d188ac77d584a79c2256e16cd534d16346514..bac7784cce12a1ca7dec89c7b8fd54627a88e12b 100644 --- a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceServiceTest.java +++ b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UIResourceServiceTest.java @@ -1,6 +1,7 @@ package eu.europa.ec.edelivery.smp.services.ui; import eu.europa.ec.edelivery.smp.config.ConversionTestConfig; +import eu.europa.ec.edelivery.smp.data.dao.AbstractJunit5BaseDao; import eu.europa.ec.edelivery.smp.data.dao.ResourceDao; import eu.europa.ec.edelivery.smp.data.dao.ResourceMemberDao; import eu.europa.ec.edelivery.smp.data.enums.MembershipRoleType; @@ -10,10 +11,11 @@ import eu.europa.ec.edelivery.smp.data.model.user.DBResourceMember; import eu.europa.ec.edelivery.smp.data.ui.MemberRO; import eu.europa.ec.edelivery.smp.data.ui.ResourceRO; import eu.europa.ec.edelivery.smp.data.ui.ServiceResult; -import eu.europa.ec.edelivery.smp.services.AbstractServiceIntegrationTest; +import eu.europa.ec.edelivery.smp.exceptions.ErrorCode; +import eu.europa.ec.edelivery.smp.exceptions.SMPRuntimeException; import eu.europa.ec.edelivery.smp.testutil.TestROUtils; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.ConversionService; import org.springframework.test.context.ContextConfiguration; @@ -21,10 +23,12 @@ import org.springframework.test.context.ContextConfiguration; import java.util.UUID; import static eu.europa.ec.edelivery.smp.testutil.TestConstants.TEST_SG_SCHEMA_1; -import static org.junit.Assert.*; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.*; @ContextConfiguration(classes = {UIResourceService.class, ConversionTestConfig.class}) -public class UIResourceServiceTest extends AbstractServiceIntegrationTest { +public class UIResourceServiceTest extends AbstractJunit5BaseDao { @Autowired protected UIResourceService testInstance; @@ -35,7 +39,7 @@ public class UIResourceServiceTest extends AbstractServiceIntegrationTest { @Autowired ConversionService conversionService; - @Before + @BeforeEach public void prepareDatabase() { // setup initial data! testUtilsDao.clearData(); @@ -77,6 +81,71 @@ public class UIResourceServiceTest extends AbstractServiceIntegrationTest { assertEquals(testResource.getIdentifierScheme(), result.getIdentifierScheme()); } + @Test + public void testCreateResourceForGroupFailsGroupNotExists() { + // given + ResourceRO testResource = TestROUtils.createResource(UUID.randomUUID().toString(), TEST_SG_SCHEMA_1, + testUtilsDao.getDomainResourceDefD1R1().getResourceDef().getIdentifier()); + + // when + SMPRuntimeException result = assertThrows(SMPRuntimeException.class, + () -> testInstance.createResourceForGroup(testResource, -100L, + testUtilsDao.getD1().getId(), testUtilsDao.getUser1().getId())); + // then + assertNotNull(result); + assertEquals(ErrorCode.INVALID_REQUEST, result.getErrorCode()); + assertThat(result.getMessage(), containsString("Group does not exist")); + } + + @Test + public void testCreateResourceForGroupFailsGroupNotForDomain() { + // given + ResourceRO testResource = TestROUtils.createResource(UUID.randomUUID().toString(), TEST_SG_SCHEMA_1, + testUtilsDao.getDomainResourceDefD1R1().getResourceDef().getIdentifier()); + + // when + SMPRuntimeException result = assertThrows(SMPRuntimeException.class, + () -> testInstance.createResourceForGroup(testResource, testUtilsDao.getGroupD1G1().getId(), -100L, + testUtilsDao.getUser1().getId())); + // then + assertNotNull(result); + assertEquals(ErrorCode.INVALID_REQUEST, result.getErrorCode()); + assertThat(result.getMessage(), containsString("Group does not belong to the given domain")); + } + + @Test + public void testCreateResourceForGroupFailInvalidResourceDef() { + // given + ResourceRO testResource = TestROUtils.createResource(UUID.randomUUID().toString(), TEST_SG_SCHEMA_1, + UUID.randomUUID().toString()); + + // when + SMPRuntimeException result = assertThrows(SMPRuntimeException.class, + () -> testInstance.createResourceForGroup(testResource, testUtilsDao.getGroupD1G1().getId(), testUtilsDao.getD1().getId(), + testUtilsDao.getUser1().getId())); + // then + assertNotNull(result); + assertEquals(ErrorCode.INVALID_REQUEST, result.getErrorCode()); + assertThat(result.getMessage(), containsString("Resource definition [" + testResource.getResourceTypeIdentifier() + "] does not exist!")); + } + + @Test + public void testCreateResourceForGroupFailAlreadyExists() { + // given + DBResource dbResource = testUtilsDao.getResourceD1G1RD1(); + ResourceRO testResource = TestROUtils.createResource(dbResource.getIdentifierValue(), dbResource.getIdentifierScheme(), + testUtilsDao.getDomainResourceDefD1R1().getResourceDef().getIdentifier()); + + // when + SMPRuntimeException result = assertThrows(SMPRuntimeException.class, + () -> testInstance.createResourceForGroup(testResource, testUtilsDao.getGroupD1G1().getId(), testUtilsDao.getD1().getId(), + testUtilsDao.getUser1().getId())); + // then + assertNotNull(result); + assertEquals(ErrorCode.INVALID_REQUEST, result.getErrorCode()); + assertThat(result.getMessage(), containsString("Resource [val:" + testResource.getIdentifierValue() + " scheme:" + testResource.getIdentifierScheme() + "] already exists for domain!")); + } + @Test public void testUpdateResourceForGroup() { // given diff --git a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UITruststoreServiceIntegrationTest.java b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UITruststoreServiceIntegrationTest.java index aff77d50b918b23e217e4899ea84708d2451e26f..a92b6e9e3393d9d595cc2cffe92d296a840de14f 100644 --- a/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UITruststoreServiceIntegrationTest.java +++ b/smp-server-library/src/test/java/eu/europa/ec/edelivery/smp/services/ui/UITruststoreServiceIntegrationTest.java @@ -13,7 +13,6 @@ import org.apache.commons.io.IOUtils; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentMatchers; @@ -167,6 +166,15 @@ public class UITruststoreServiceIntegrationTest extends AbstractServiceIntegrati assertFalse(testInstance.isSubjectOnTrustedList(certificateRO.getSubject())); } + @Test + public void testDeleteCertificateNotExists() throws Exception { + // given + // when + X509Certificate cert = testInstance.deleteCertificate("alias-not-exists"); + // then + assertNull(cert); + } + @Test public void testIsTruststoreChanged() throws Exception { // given @@ -203,16 +211,16 @@ public class UITruststoreServiceIntegrationTest extends AbstractServiceIntegrati } @Test - public void validateCertificateWithTruststoreNullCertificate() { + public void validateCertificateWithTruststoreNullCertificate() { CertificateException result = assertThrows(CertificateException.class, - () ->testInstance.validateCertificateWithTruststore(null)); + () -> testInstance.validateCertificateWithTruststore(null)); assertThat(result.getMessage(), containsString("The X509Certificate is null ")); } @Test - public void validateCertificateWithTruststoreNullTruststore() throws Exception { + public void validateCertificateWithTruststoreNullTruststore() throws Exception { String certSubject = "CN=SMP Test,OU=eDelivery,O=DIGITAL,C=BE"; X509Certificate certificate = X509CertificateTestUtils.createX509CertificateForTest(certSubject); Mockito.doReturn(null).when(testInstance).getTrustStore(); @@ -232,7 +240,7 @@ public class UITruststoreServiceIntegrationTest extends AbstractServiceIntegrati CertificateRO cer = testInstance.getCertificateData(buff); //then - assertTrue( cer.isInvalid()); + assertTrue(cer.isInvalid()); assertEquals("Can not read the certificate!", cer.getInvalidReason()); } diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/ResourceController.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/ResourceController.java index ab940997bc57ba090e1bc2bd9df356ccbf5c3ec9..b649cf1c2781c7f4f05a86e6f1e34bf71808ba09 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/ResourceController.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/ResourceController.java @@ -194,6 +194,4 @@ public class ResourceController { throw new SMPRuntimeException(INVALID_REQUEST, "Can not read input stream!", e); } } - - } diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/RootController.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/RootController.java index 5c2fc48b25d3a792c711981eab4957f481cd9ae9..3f0b80e768f95a2b112a7f8252a6e9d840ad7f7a 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/RootController.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/controllers/RootController.java @@ -56,19 +56,27 @@ public class RootController { "image/ico", "image/x-ico" }, value = {"/index.html", "/favicon.png", "/favicon.ico"}) - public byte[] getServiceGroup(HttpServletRequest httpReq, HttpServletResponse httpRes) throws IOException { + public byte[] getStaticResources(HttpServletRequest httpReq, HttpServletResponse httpRes) throws IOException { String host = getRemoteHost(httpReq); LOG.businessInfo(SMPMessageCode.BUS_HTTP_GET_END_STATIC_CONTENT, host, httpReq.getPathInfo()); String value = httpReq.getPathInfo(); + + if (StringUtils.isBlank(value)) { + httpRes.setContentType(MediaType.TEXT_HTML_VALUE); + return IOUtils.readBytesFromStream(RootController.class.getResourceAsStream("/html/index.html")); + } + if (value != null && value.endsWith("favicon.png")) { - httpRes.setContentType("image/x-ico"); + httpRes.setContentType(MediaType.IMAGE_PNG_VALUE); return IOUtils.readBytesFromStream(RootController.class.getResourceAsStream("/html/favicon.png")); } else if (value != null && value.endsWith("favicon.ico")) { - httpRes.setContentType(MediaType.IMAGE_PNG_VALUE); + httpRes.setContentType("image/x-ico"); return IOUtils.readBytesFromStream(RootController.class.getResourceAsStream("/html/favicon.ico")); - } else { - return IOUtils.readBytesFromStream(RootController.class.getResourceAsStream("/html/index.html")); } + + httpRes.setContentType(MediaType.TEXT_HTML_VALUE); + return IOUtils.readBytesFromStream(RootController.class.getResourceAsStream("/html/index.html")); + } /** @@ -88,6 +96,4 @@ public class RootController { String host = httpReq.getHeader("X-Forwarded-For"); return StringUtils.isBlank(host) ? httpReq.getRemoteHost() : host; } - - } diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/monitor/MonitorResource.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/monitor/MonitorController.java similarity index 73% rename from smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/monitor/MonitorResource.java rename to smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/monitor/MonitorController.java index 07046e1b4a20aa3dd224641b6392d02b8b4c1ac7..8d843b8945c12ff8e5ca946e7f74da81ce6a5699 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/monitor/MonitorResource.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/monitor/MonitorController.java @@ -4,7 +4,6 @@ package eu.europa.ec.edelivery.smp.monitor; import eu.europa.ec.edelivery.smp.data.dao.DomainDao; import eu.europa.ec.edelivery.smp.data.model.DBDomain; import eu.europa.ec.edelivery.smp.data.ui.auth.SMPAuthority; -import eu.europa.ec.edelivery.smp.exceptions.SMPTestIsALiveException; import eu.europa.ec.edelivery.smp.logging.SMPLogger; import eu.europa.ec.edelivery.smp.logging.SMPLoggerFactory; import org.apache.commons.lang3.exception.ExceptionUtils; @@ -17,7 +16,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; -import java.util.Objects; /** * @author Joze Rihtarsic @@ -26,17 +24,13 @@ import java.util.Objects; @RestController @RequestMapping(value = "/monitor") -public class MonitorResource { +public class MonitorController { - private static final SMPLogger LOG = SMPLoggerFactory.getLogger(MonitorResource.class); + private static final SMPLogger LOG = SMPLoggerFactory.getLogger(MonitorController.class); - - private static final String TEST_NAME = "urn:test:document:is-alive"; - private static final String TEST_EXTENSION_XML = "<Extension xmlns=\"http://docs.oasis-open.org/bdxr/ns/SMP/2016/05\"><ex:dummynode xmlns:ex=\"http://test.eu\">Sample not mandatory extension</ex:dummynode></Extension>"; - private static final String TEST_DB_SUCCESSFUL_ROLLBACK = "TEST_DB_SUCCESSFUL_ROLLBACK MESSAGE"; private final DomainDao domainDao; - public MonitorResource(DomainDao domainDao) { + public MonitorController(DomainDao domainDao) { this.domainDao = domainDao; } @@ -49,8 +43,6 @@ public class MonitorResource { LOG.debug("Start isAlive function for user: [{}]", user); try { suc = testDatabase(); - } catch (SMPTestIsALiveException ex) { - suc = Objects.equals(TEST_DB_SUCCESSFUL_ROLLBACK, ex.getMessage()); } catch (RuntimeException th) { LOG.error("Error occurred while testing database connection: Msg: [{}]", ExceptionUtils.getRootCauseMessage(th)); } diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/AlertController.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/AlertController.java index d69b03ba588e6072756db341e1e4be122890e70b..dcb9b2bf31a20a1cd1de216b8d7361acf08fcd5a 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/AlertController.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/AlertController.java @@ -31,7 +31,7 @@ public class AlertController { } @GetMapping(produces = {MimeTypeUtils.APPLICATION_JSON_VALUE}) - public ServiceResult<AlertRO> geDomainList( + public ServiceResult<AlertRO> getAlertList( @RequestParam(value = PARAM_PAGINATION_PAGE, defaultValue = "0") int page, @RequestParam(value = PARAM_PAGINATION_PAGE_SIZE, defaultValue = "10") int pageSize, @RequestParam(value = PARAM_PAGINATION_ORDER_BY, defaultValue = "id", required = false) String orderBy, diff --git a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminController.java b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminController.java index 61c57b5ed6521a14679ffc80105353ff439b9595..052d0491845eb376b693889a649ef2137ab9160d 100644 --- a/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminController.java +++ b/smp-webapp/src/main/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminController.java @@ -63,7 +63,7 @@ public class UserAdminController { @GetMapping(path = "/{user-enc-id}/search", produces = MimeTypeUtils.APPLICATION_JSON_VALUE) @PreAuthorize("@smpAuthorizationService.isCurrentlyLoggedIn(#userEncId) and @smpAuthorizationService.isSystemAdministrator") - public ServiceResult<SearchUserRO> getDomainMemberList( + public ServiceResult<SearchUserRO> searchUsers( @PathVariable("user-enc-id") String userEncId, @RequestParam(value = PARAM_PAGINATION_PAGE, defaultValue = "0") int page, @RequestParam(value = PARAM_PAGINATION_PAGE_SIZE, defaultValue = "10") int pageSize, diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/controllers/ResourceControllerTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/controllers/ResourceControllerTest.java index 4b7cc6b0185f935207755683b2519a06f4d47696..47157baf061208e6300e00c0bfefbda2b2a8a52e 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/controllers/ResourceControllerTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/controllers/ResourceControllerTest.java @@ -14,31 +14,18 @@ package eu.europa.ec.edelivery.smp.controllers; import eu.europa.ec.edelivery.smp.data.dao.ConfigurationDao; -import eu.europa.ec.edelivery.smp.test.SmpTestWebAppConfig; -import eu.europa.ec.edelivery.smp.test.testutils.X509CertificateTestUtils; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; +import eu.europa.ec.edelivery.smp.ui.AbstractControllerTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockServletContext; -import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.RequestPostProcessor; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.WebApplicationContext; import org.springframework.web.server.adapter.ForwardedHeaderTransformer; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; import java.io.IOException; import java.net.URLEncoder; import java.util.UUID; @@ -49,7 +36,6 @@ import static java.lang.String.format; import static org.hamcrest.Matchers.stringContainsInOrder; import static org.springframework.http.MediaType.APPLICATION_XML_VALUE; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @@ -57,17 +43,13 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. /** * Created by gutowpa on 02/08/2017. */ -@RunWith(SpringRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = {SmpTestWebAppConfig.class}) -@Sql(scripts = { - "classpath:/cleanup-database.sql", - "classpath:/webapp_integration_test_data.sql"}, - executionPhase = BEFORE_TEST_METHOD) -public class ResourceControllerTest { + +public class ResourceControllerTest extends AbstractControllerTest { public static final Logger LOG = LoggerFactory.getLogger(ResourceControllerTest.class); + private static final String DOCUMENT_TYPE_URL = "smp-1"; + private static final String IDENTIFIER_SCHEME = "ehealth-participantid-qns"; private static final String DOCUMENT_SCHEME = "doctype"; @@ -80,32 +62,16 @@ public class ResourceControllerTest { private static final RequestPostProcessor ADMIN_CREDENTIALS = httpBasic("pat_smp_admin", "123456"); - @Autowired - private WebApplicationContext webAppContext; - @Autowired ForwardedHeaderTransformer forwardedHeaderTransformer; @Autowired ConfigurationDao configurationDao; - private MockMvc mvc; - @Before + @BeforeEach public void setup() throws IOException { - X509CertificateTestUtils.reloadKeystores(); - mvc = MockMvcBuilders.webAppContextSetup(webAppContext) - .apply(SecurityMockMvcConfigurers.springSecurity()) - .build(); - - initServletContext(); - } - - private void initServletContext() { - MockServletContext sc = new MockServletContext(""); - ServletContextListener listener = new ContextLoaderListener(webAppContext); - ServletContextEvent event = new ServletContextEvent(sc); - listener.contextInitialized(event); + super.setup(); } @Test @@ -121,24 +87,10 @@ public class ResourceControllerTest { String urPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); mvc.perform(put(urPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) - .andExpect(status().isCreated()); - } - - @Test - @Ignore("Setting of the 'identifiersBehaviour.scheme.mandatory' not working") - public void adminCanCreateServiceGroupNullScheme() throws Exception { - String participantId = UUID.randomUUID().toString(); - String nullSchemeExample = getSampleServiceGroupBody(null, UUID.randomUUID().toString()); - - mvc.perform(put(format("/%s", participantId)) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(nullSchemeExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isCreated()); } @@ -150,17 +102,17 @@ public class ResourceControllerTest { mvc.perform(put(urPath) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .with(ADMIN_CREDENTIALS) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .with(ADMIN_CREDENTIALS) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isCreated()); mvc.perform(put(urPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isOk()); } @@ -171,10 +123,10 @@ public class ResourceControllerTest { String urPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); mvc.perform(put(urPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isCreated()); mvc.perform(get(urPath)) @@ -182,30 +134,57 @@ public class ResourceControllerTest { } - @Test - public void existingServiceMetadataCanBeRetrievedByEverybody() throws Exception { + @ParameterizedTest + @ValueSource(strings = {"", // use default document and domain values + "/" + DOCUMENT_TYPE_URL, // document type + "/" + HTTP_DOMAIN_VALUE, // as domain value + "/" + HTTP_DOMAIN_VALUE + "/" + DOCUMENT_TYPE_URL // as domain value + }) + public void existingServiceGroupCanBeRetrievedByEverybodyWithSubContext(String context) throws Exception { + String participantId = UUID.randomUUID().toString(); + String resourceExample = getSampleServiceGroupBody(IDENTIFIER_SCHEME, participantId); + String urPath = format("%s/%s::%s", context, IDENTIFIER_SCHEME, participantId); + + mvc.perform(put(urPath) + .with(ADMIN_CREDENTIALS) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) + .andExpect(status().isCreated()); + + mvc.perform(get(urPath)) + .andExpect(content().xml(resourceExample)); + + } + + @ParameterizedTest + @ValueSource(strings = {"", // use default document and domain values + "/" + DOCUMENT_TYPE_URL, // document type + "/" + HTTP_DOMAIN_VALUE, // as domain value + "/" + HTTP_DOMAIN_VALUE + "/" + DOCUMENT_TYPE_URL // as domain value + }) + public void existingServiceMetadataCanBeRetrievedByEverybody(String context) throws Exception { String participantId = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); String resourceExample = getSampleServiceGroupBody(IDENTIFIER_SCHEME, participantId); - String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); + String urlPath = format("%s/%s::%s", context, IDENTIFIER_SCHEME, participantId); String docUrlPath = format("%s/services/%s::%s", urlPath, DOCUMENT_SCHEME, documentId); String xmlMD = generateServiceMetadata(participantId, IDENTIFIER_SCHEME, documentId, DOCUMENT_SCHEME, "test"); // crate service group mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isCreated()); // add service metadata mvc.perform(put(docUrlPath) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .with(ADMIN_CREDENTIALS) - .contentType(APPLICATION_XML_VALUE) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .with(ADMIN_CREDENTIALS) + .contentType(APPLICATION_XML_VALUE) - .content(xmlMD)) + .content(xmlMD)) .andExpect(status().isCreated()); mvc.perform(get(urlPath)) @@ -221,14 +200,14 @@ public class ResourceControllerTest { String participantId = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); - prepareForGet(participantId,documentId); + prepareForGet(participantId, documentId); // when then.. String expectedUrl = "http://ec.test.eu/"; mvc.perform(get(urlPath) - .header("X-Forwarded-Host", "ec.test.eu") - .header("X-Forwarded-Port", "") - .header("X-Forwarded-Proto", "http")) + .header("X-Forwarded-Host", "ec.test.eu") + .header("X-Forwarded-Port", "") + .header("X-Forwarded-Proto", "http")) .andExpect(content().xml(generateExpectedServiceGroup(expectedUrl, IDENTIFIER_SCHEME, participantId, DOCUMENT_SCHEME, documentId))); } @@ -238,14 +217,14 @@ public class ResourceControllerTest { String participantId = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); - prepareForGet(participantId,documentId); + prepareForGet(participantId, documentId); // when then.. String expectedUrl = "http://localhost/"; mvc.perform(get(urlPath) - .header("X-Forwarded-Port", "") - .header("X-Forwarded-Proto", "http")) + .header("X-Forwarded-Port", "") + .header("X-Forwarded-Proto", "http")) .andExpect(content().xml(generateExpectedServiceGroup(expectedUrl, IDENTIFIER_SCHEME, participantId, DOCUMENT_SCHEME, documentId))); } @@ -255,13 +234,13 @@ public class ResourceControllerTest { String participantId = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); - prepareForGet(participantId,documentId); + prepareForGet(participantId, documentId); // when then.. String expectedUrl = "https://ec.test.eu:8443/"; mvc.perform(get(urlPath) - .header("X-Forwarded-Host", "ec.test.eu:8443") - .header("X-Forwarded-Proto", "https")) + .header("X-Forwarded-Host", "ec.test.eu:8443") + .header("X-Forwarded-Proto", "https")) .andExpect(content().xml(generateExpectedServiceGroup(expectedUrl, IDENTIFIER_SCHEME, participantId, DOCUMENT_SCHEME, documentId))); } @@ -271,14 +250,14 @@ public class ResourceControllerTest { String participantId = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); - prepareForGet(participantId,documentId); + prepareForGet(participantId, documentId); // when then.. String expectedUrl = "https://ec.test.eu:8443/"; mvc.perform(get(urlPath) - .header("X-Forwarded-Port", "8443") - .header("X-Forwarded-Host", "ec.test.eu") - .header("X-Forwarded-Proto", "https")) + .header("X-Forwarded-Port", "8443") + .header("X-Forwarded-Host", "ec.test.eu") + .header("X-Forwarded-Proto", "https")) .andExpect(content().xml(generateExpectedServiceGroup(expectedUrl, IDENTIFIER_SCHEME, participantId, DOCUMENT_SCHEME, documentId))); } @@ -290,14 +269,14 @@ public class ResourceControllerTest { String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); LOG.info("Create service metadata: getExistingServiceMetadataWithReverseProxySkipDefaultPortHttps [{}]", urlPath); - prepareForGet(participantId,documentId); + prepareForGet(participantId, documentId); // when then.. String expectedUrl = "https://ec.test.eu/"; mvc.perform(get(urlPath) - .header("X-Forwarded-Port", "443") - .header("X-Forwarded-Host", "ec.test.eu") - .header("X-Forwarded-Proto", "https")) + .header("X-Forwarded-Port", "443") + .header("X-Forwarded-Host", "ec.test.eu") + .header("X-Forwarded-Proto", "https")) .andExpect(content().xml(generateExpectedServiceGroup(expectedUrl, IDENTIFIER_SCHEME, participantId, DOCUMENT_SCHEME, documentId))); } @@ -307,14 +286,14 @@ public class ResourceControllerTest { String participantId = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); - prepareForGet(participantId,documentId); + prepareForGet(participantId, documentId); // when then.. String expectedUrl = "http://ec.test.eu/"; mvc.perform(get(urlPath) - .header("X-Forwarded-Port", "80") - .header("X-Forwarded-Host", "ec.test.eu") - .header("X-Forwarded-Proto", "http")) + .header("X-Forwarded-Port", "80") + .header("X-Forwarded-Host", "ec.test.eu") + .header("X-Forwarded-Proto", "http")) .andExpect(content().xml(generateExpectedServiceGroup(expectedUrl, IDENTIFIER_SCHEME, participantId, DOCUMENT_SCHEME, documentId))); } @@ -324,27 +303,28 @@ public class ResourceControllerTest { String participantId = UUID.randomUUID().toString(); String documentId = UUID.randomUUID().toString(); String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); - prepareForGet(participantId,documentId); + prepareForGet(participantId, documentId); // when then.. String expectedUrl = "https://ec.test.eu:8443/"; mvc.perform(get(urlPath) - .header("X-Forwarded-Port", "8443") - .header("X-Forwarded-Host", "ec.test.eu:8443") - .header("X-Forwarded-Proto", "https")) + .header("X-Forwarded-Port", "8443") + .header("X-Forwarded-Host", "ec.test.eu:8443") + .header("X-Forwarded-Proto", "https")) .andExpect(content().xml(generateExpectedServiceGroup(expectedUrl, IDENTIFIER_SCHEME, participantId, DOCUMENT_SCHEME, documentId))); } public String generateExpectedServiceGroup(String expectedUrl, String resourceScheme, String resourceValue, String subresourceScheme, String subresourceValue) { return "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" + "<ServiceGroup xmlns=\"http://docs.oasis-open.org/bdxr/ns/SMP/2016/05\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\">" + - "<ParticipantIdentifier scheme=\""+resourceScheme+"\">"+resourceValue+"</ParticipantIdentifier>" + + "<ParticipantIdentifier scheme=\"" + resourceScheme + "\">" + resourceValue + "</ParticipantIdentifier>" + "<ServiceMetadataReferenceCollection>" + - "<ServiceMetadataReference href=\"" + generateEncodedURL(expectedUrl, resourceScheme, resourceValue,subresourceScheme,subresourceValue)+ "\"/>" + + "<ServiceMetadataReference href=\"" + generateEncodedURL(expectedUrl, resourceScheme, resourceValue, subresourceScheme, subresourceValue) + "\"/>" + "</ServiceMetadataReferenceCollection></ServiceGroup>"; } - public String generateEncodedURL(String expectedUrl, String resourceScheme, String resourceValue, String subresourceScheme, String subresourceValue){ - return expectedUrl + URLEncoder.encode(resourceScheme + "::" + resourceValue) + "/services/"+ URLEncoder.encode(subresourceScheme + "::" + subresourceValue); + + public String generateEncodedURL(String expectedUrl, String resourceScheme, String resourceValue, String subresourceScheme, String subresourceValue) { + return expectedUrl + URLEncoder.encode(resourceScheme + "::" + resourceValue) + "/services/" + URLEncoder.encode(subresourceScheme + "::" + subresourceValue); } @Test @@ -355,9 +335,9 @@ public class ResourceControllerTest { String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); mvc.perform(put(urlPath) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isUnauthorized()); mvc.perform(get(urlPath)) @@ -371,14 +351,14 @@ public class ResourceControllerTest { String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isCreated()); mvc.perform(delete(urlPath) - .with(ADMIN_CREDENTIALS)) + .with(ADMIN_CREDENTIALS)) .andExpect(status().isOk()); mvc.perform(get(urlPath)) .andExpect(status().isNotFound()); @@ -392,10 +372,10 @@ public class ResourceControllerTest { String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content("malformed input XML")) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content("malformed input XML")) .andExpect(status().isBadRequest()); } @@ -409,10 +389,10 @@ public class ResourceControllerTest { mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .content(resourceExample)) .andExpect(status().isBadRequest()); } @@ -424,10 +404,10 @@ public class ResourceControllerTest { mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .contentType(APPLICATION_XML_VALUE) - .header(HTTP_HEADER_KEY_DOMAIN, "not-existing-domain") - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .contentType(APPLICATION_XML_VALUE) + .header(HTTP_HEADER_KEY_DOMAIN, "not-existing-domain") + .content(resourceExample)) .andExpect(status().isBadRequest()) .andExpect(content().string(stringContainsInOrder("FORMAT_ERROR"))); } @@ -440,10 +420,10 @@ public class ResourceControllerTest { String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .contentType(APPLICATION_XML_VALUE) - .header(HTTP_HEADER_KEY_DOMAIN, "notExistingDomain") - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .contentType(APPLICATION_XML_VALUE) + .header(HTTP_HEADER_KEY_DOMAIN, "notExistingDomain") + .content(resourceExample)) .andExpect(status().isNotFound()) .andExpect(content().string(stringContainsInOrder("NOT_FOUND"))); } @@ -456,11 +436,11 @@ public class ResourceControllerTest { mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .header(HTTP_HEADER_KEY_SERVICE_GROUP_OWNER, OTHER_OWNER_NAME_URL_ENCODED) - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .header(HTTP_HEADER_KEY_SERVICE_GROUP_OWNER, OTHER_OWNER_NAME_URL_ENCODED) + .content(resourceExample)) .andExpect(status().isCreated()); } @@ -471,11 +451,11 @@ public class ResourceControllerTest { String urlPath = format("/%s::%s", IDENTIFIER_SCHEME, participantId); mvc.perform(put(urlPath) - .with(ADMIN_CREDENTIALS) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .contentType(APPLICATION_XML_VALUE) - .header(HTTP_HEADER_KEY_SERVICE_GROUP_OWNER, "not-existing-user") - .content(resourceExample)) + .with(ADMIN_CREDENTIALS) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .contentType(APPLICATION_XML_VALUE) + .header(HTTP_HEADER_KEY_SERVICE_GROUP_OWNER, "not-existing-user") + .content(resourceExample)) .andExpect(status().isBadRequest()); } @@ -489,18 +469,18 @@ public class ResourceControllerTest { LOG.info("create service service group: [{}]", docUrlPath); mvc.perform(put(urlPath) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .with(ADMIN_CREDENTIALS) - .contentType(APPLICATION_XML_VALUE) - .content(xmlSG)) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .with(ADMIN_CREDENTIALS) + .contentType(APPLICATION_XML_VALUE) + .content(xmlSG)) .andExpect(status().isCreated()); // add service metadata LOG.info("create service metadata: [{}]", docUrlPath); ResultActions actions = mvc.perform(put(docUrlPath) - .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) - .with(ADMIN_CREDENTIALS) - .contentType(APPLICATION_XML_VALUE) - .content(xmlMD)) + .header(HTTP_HEADER_KEY_DOMAIN, HTTP_DOMAIN_VALUE) + .with(ADMIN_CREDENTIALS) + .contentType(APPLICATION_XML_VALUE) + .content(xmlMD)) .andExpect(status().isCreated()); } diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/controllers/RootControllerTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/controllers/RootControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..008bb4b702662320702c5fb6abe2501e12a53e32 --- /dev/null +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/controllers/RootControllerTest.java @@ -0,0 +1,59 @@ +package eu.europa.ec.edelivery.smp.controllers; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.Mockito; +import org.springframework.ui.ModelMap; +import org.springframework.web.servlet.ModelAndView; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.*; + +class RootControllerTest { + + RootController testInstance = new RootController(); + + @Test + void testRedirectOldIndexPath() { + ModelMap mockModel = Mockito.mock(ModelMap.class); + ModelAndView result = testInstance.redirectOldIndexPath(mockModel); + + assertNotNull(result); + assertEquals("redirect:/index.html", result.getViewName()); + } + + @ParameterizedTest + @CsvSource({ + ", text/html", + "/index.html, text/html", + "/favicon.png, image/png", + "/favicon.ico, image/x-ico" + }) + void testGetStaticResources(String pathInfo, String contentType) throws IOException { + //given + HttpServletRequest mockHttpServletRequest = Mockito.mock(HttpServletRequest.class); + HttpServletResponse mockHttpServletResponse = Mockito.mock(HttpServletResponse.class); + Mockito.when(mockHttpServletRequest.getPathInfo()).thenReturn(pathInfo); + //when + byte[] result = testInstance.getStaticResources(mockHttpServletRequest, mockHttpServletResponse); + //then + assertNotNull(result); + Mockito.verify(mockHttpServletResponse).setContentType(contentType); + + } + + @Test + void testRedirectWithUsingRedirectPrefix() { + ModelMap mockModel = Mockito.mock(ModelMap.class); + ModelAndView result = testInstance.redirectWithUsingRedirectPrefix(mockModel); + + assertNotNull(result); + assertEquals("redirect:/ui/index.html", result.getViewName()); + } + +} diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorControllerIT.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorControllerIT.java new file mode 100644 index 0000000000000000000000000000000000000000..709df15c5c3763133c0761fa2048f8cce92eb0bf --- /dev/null +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorControllerIT.java @@ -0,0 +1,56 @@ +package eu.europa.ec.edelivery.smp.monitor; + +import eu.europa.ec.edelivery.smp.ui.AbstractControllerTest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.web.servlet.request.RequestPostProcessor; + +import java.io.IOException; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * MonitorController integration tests + * @author Joze Rihtarsic + * @since 4.1 + */ +public class MonitorControllerIT extends AbstractControllerTest { + + private static final String URL = "/monitor/is-alive"; + private static final RequestPostProcessor ADMIN_CREDENTIALS = httpBasic("pat_smp_admin", "123456"); + + @Autowired + private MonitorController testInstance; + + @BeforeEach + public void setup() throws IOException { + super.setup(); + } + + @Test + public void isAliveNotAuthorized() throws Exception { + mvc.perform(get(URL)) + .andExpect(status().isUnauthorized()); + } + + @Test + public void isAlive() throws Exception { + mvc.perform(get(URL) + .with(ADMIN_CREDENTIALS)) + .andExpect(status() + .isOk()); + } + + @Test + public void testDatabase() { + // when + boolean result = testInstance.testDatabase(); + + assertTrue(result); + + } +} diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorControllerTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorControllerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..345989e9407c59260f9907b33e75c9fa743e9f6d --- /dev/null +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorControllerTest.java @@ -0,0 +1,88 @@ +package eu.europa.ec.edelivery.smp.monitor; + +import eu.europa.ec.edelivery.smp.data.dao.DomainDao; +import eu.europa.ec.edelivery.smp.data.model.DBDomain; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * MonitorControllerTest unit tests + * + * @author Joze Rihtarsic + * @since 5.0 + */ +class MonitorControllerTest { + + DomainDao mockDomainDao = Mockito.mock(DomainDao.class); + MonitorController testInstance = new MonitorController(mockDomainDao); + + // mock security context and authentication + @BeforeAll + public static void before() { + SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext()); + SecurityContextHolder.getContext().setAuthentication(Mockito.mock(Authentication.class)); + } + + @AfterAll + public static void cleanup() { + SecurityContextHolder.clearContext(); + } + + @Test + void isAliveOK() { + // given + Mockito.when(mockDomainDao.getAllDomains()).thenReturn(Collections.singletonList(new DBDomain())); + // when + ResponseEntity result = testInstance.isAlive(); + // then + assertEquals(HttpStatus.OK, result.getStatusCode()); + } + + @Test + void isAliveNotConfigured() { + // given + Mockito.when(mockDomainDao.getAllDomains()).thenReturn(Collections.emptyList()); + // when + ResponseEntity result = testInstance.isAlive(); + // then + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + } + + @Test + void isAliveDatabaseRuntimeError() { + // given + Mockito.when(mockDomainDao.getAllDomains()).thenThrow(Mockito.mock(RuntimeException.class)); + // when + ResponseEntity result = testInstance.isAlive(); + // then + assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, result.getStatusCode()); + } + + @Test + void testDatabaseEmpty() { + // when + Mockito.when(mockDomainDao.getAllDomains()).thenReturn(Collections.emptyList()); + boolean result = testInstance.testDatabase(); + + assertFalse(result); + } + + @Test + void testDatabaseNotEmpty() { + // when + Mockito.when(mockDomainDao.getAllDomains()).thenReturn(Collections.singletonList(new DBDomain())); + boolean result = testInstance.testDatabase(); + + assertTrue(result); + } +} diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorResourceTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorResourceTest.java deleted file mode 100644 index 593cec67fde1159d9169a907d7271e97b6c1646a..0000000000000000000000000000000000000000 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/monitor/MonitorResourceTest.java +++ /dev/null @@ -1,96 +0,0 @@ -package eu.europa.ec.edelivery.smp.monitor; - -import eu.europa.ec.edelivery.smp.exceptions.SMPTestIsALiveException; -import eu.europa.ec.edelivery.smp.test.SmpTestWebAppConfig; -import eu.europa.ec.edelivery.smp.test.testutils.X509CertificateTestUtils; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.mock.web.MockServletContext; -import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.jdbc.Sql; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.test.context.web.WebAppConfiguration; -import org.springframework.test.web.servlet.MockMvc; -import org.springframework.test.web.servlet.request.RequestPostProcessor; -import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.WebApplicationContext; - -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import java.io.IOException; - -import static org.junit.Assert.*; -import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.httpBasic; -import static org.springframework.test.context.jdbc.Sql.ExecutionPhase.BEFORE_TEST_METHOD; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; - -/** - * @author Joze Rihtarsic - * @since 4.1 - */ -@RunWith(SpringRunner.class) -@WebAppConfiguration -@ContextConfiguration(classes = {SmpTestWebAppConfig.class}) -@Sql(scripts = { - "classpath:/cleanup-database.sql", - "classpath:/webapp_integration_test_data.sql"}, - executionPhase = BEFORE_TEST_METHOD) -public class MonitorResourceTest { - - private static final String URL = "/monitor/is-alive"; - private static final RequestPostProcessor ADMIN_CREDENTIALS = httpBasic("pat_smp_admin", "123456"); - @Autowired - private WebApplicationContext webAppContext; - - @Autowired - private MonitorResource testInstance; - - private MockMvc mvc; - - @Before - public void setup() throws IOException { - X509CertificateTestUtils.reloadKeystores(); - mvc = MockMvcBuilders.webAppContextSetup(webAppContext) - .apply(SecurityMockMvcConfigurers.springSecurity()) - .build(); - - initServletContext(); - } - - private void initServletContext() { - MockServletContext sc = new MockServletContext(""); - ServletContextListener listener = new ContextLoaderListener(webAppContext); - ServletContextEvent event = new ServletContextEvent(sc); - listener.contextInitialized(event); - } - - @Test - public void isAliveNotAuthorized() throws Exception { - mvc.perform(get(URL)) - .andExpect(status().isUnauthorized()); - } - - @Test - public void isAlive() throws Exception { - mvc.perform(get(URL) - .with(ADMIN_CREDENTIALS)) - .andExpect(status().isOk()); - } - - @Test - public void testDatabase() { - // when - boolean result = testInstance.testDatabase(); - - assertTrue(result); - - } -} diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/test/testutils/TestROUtils.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/test/testutils/TestROUtils.java index 61e5a91953b4d11e42fcd9205af9b7aa62e3a754..99b08b32123c99c7ee72b872b04e363747f01493 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/test/testutils/TestROUtils.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/test/testutils/TestROUtils.java @@ -1,6 +1,7 @@ package eu.europa.ec.edelivery.smp.test.testutils; import eu.europa.ec.edelivery.smp.data.enums.VisibilityType; +import eu.europa.ec.edelivery.smp.data.ui.DomainRO; import eu.europa.ec.edelivery.smp.data.ui.GroupRO; import java.util.UUID; @@ -20,6 +21,17 @@ public class TestROUtils { return groupRO; } + public static DomainRO createDomain() { + return createDomain(anyString()); + } + + public static DomainRO createDomain(String name) { + DomainRO domainRO = new DomainRO(); + domainRO.setDomainCode(name); + domainRO.setVisibility(VisibilityType.PRIVATE); + return domainRO; + } + public static String anyString() { return UUID.randomUUID().toString(); } diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserControllerIT.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserControllerIT.java index 77c32e502e062b34af272f6d4313e5a82f738d94..b028cd77bc180b199f765a551d313013b9e8a358 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserControllerIT.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/external/UserControllerIT.java @@ -1,5 +1,7 @@ package eu.europa.ec.edelivery.smp.ui.external; +import eu.europa.ec.edelivery.smp.data.enums.CredentialType; +import eu.europa.ec.edelivery.smp.data.ui.CredentialRO; import eu.europa.ec.edelivery.smp.data.ui.NavigationTreeNodeRO; import eu.europa.ec.edelivery.smp.data.ui.SearchUserRO; import eu.europa.ec.edelivery.smp.data.ui.UserRO; @@ -35,7 +37,6 @@ public class UserControllerIT extends AbstractControllerTest { super.setup(); } - @Test public void testGetUserNavigationTreeForSystemAdmin() throws Exception { @@ -102,4 +103,43 @@ public class UserControllerIT extends AbstractControllerTest { assertEquals(1, result.size()); assertEquals(userRO.getUsername(), result.get(0).getUsername()); } + + @Test + public void testGetUserCredentialStatus() throws Exception { + MockHttpSession session = loginWithUser2(mvc); + UserRO userRO = getLoggedUserData(mvc, session); + MvcResult response = mvc.perform(get(PATH + "/{user-id}/username-credential-status", userRO.getUserId()) + .session(session) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); + // when + CredentialRO result = getObjectFromResponse(response, CredentialRO.class); + // then + assertNotNull(result); + assertEquals(userRO.getUsername(), result.getName()); + assertTrue(result.isActive()); + assertTrue(result.isExpired()); // set by admin + assertNull(result.getExpireOn()); + } + + + @Test + public void testGetAccessTokenCredentials() throws Exception { + MockHttpSession session = loginWithUser2(mvc); + UserRO userRO = getLoggedUserData(mvc, session); + MvcResult response = mvc.perform(get(PATH + "/{user-id}/access-token-credentials", userRO.getUserId()) + .session(session) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); + // when + List<CredentialRO> result = getArrayFromResponse(response, CredentialRO.class); + // then + assertNotNull(result); + assertEquals(1, result.size()); + CredentialRO credentialRO = result.get(0); + assertEquals(CredentialType.ACCESS_TOKEN, credentialRO.getCredentialType()); + assertTrue(credentialRO.isActive()); + assertTrue(credentialRO.isExpired()); // set by admin + assertNull(credentialRO.getExpireOn()); + } } diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/DomainAdminResourceIT.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/DomainAdminControllerIT.java similarity index 60% rename from smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/DomainAdminResourceIT.java rename to smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/DomainAdminControllerIT.java index adcda948e18a626ad4fac15672f35e8344a3494c..0956d5da6c8e43f9d89d5d69386616a6399bb3d5 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/DomainAdminResourceIT.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/DomainAdminControllerIT.java @@ -5,43 +5,42 @@ import eu.europa.ec.edelivery.smp.data.model.DBDomain; import eu.europa.ec.edelivery.smp.data.ui.DomainRO; import eu.europa.ec.edelivery.smp.data.ui.UserRO; import eu.europa.ec.edelivery.smp.data.ui.enums.EntityROStatus; +import eu.europa.ec.edelivery.smp.data.ui.exceptions.ErrorResponseRO; +import eu.europa.ec.edelivery.smp.exceptions.ErrorBusinessCode; import eu.europa.ec.edelivery.smp.test.testutils.MockMvcUtils; +import eu.europa.ec.edelivery.smp.test.testutils.TestROUtils; import eu.europa.ec.edelivery.smp.ui.AbstractControllerTest; import eu.europa.ec.edelivery.smp.ui.ResourceConstants; import org.apache.commons.lang3.StringUtils; +import org.hamcrest.MatcherAssert; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpSession; -import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; -import org.springframework.web.context.WebApplicationContext; +import java.io.IOException; +import java.util.Collections; import java.util.List; import static eu.europa.ec.edelivery.smp.test.testutils.MockMvcUtils.*; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -public class DomainAdminResourceIT extends AbstractControllerTest { +public class DomainAdminControllerIT extends AbstractControllerTest { private static final String PATH = ResourceConstants.CONTEXT_PATH_INTERNAL_DOMAIN; - @Autowired - private WebApplicationContext webAppContext; - @Autowired DomainDao domainDao; - private MockMvc mvc; - @BeforeEach - public void setup() { - mvc = MockMvcUtils.initializeMockMvc(webAppContext); + public void setup() throws IOException { + super.setup(); } @Test @@ -61,6 +60,69 @@ public class DomainAdminResourceIT extends AbstractControllerTest { assertEquals(domain.size(), response.size()); } + @Test + public void testCreateBasicDomainData() throws Exception { + DomainRO testDomain = TestROUtils.createDomain(); + + MockHttpSession session = loginWithSystemAdmin(mvc); + UserRO userRO = MockMvcUtils.getLoggedUserData(mvc, session); + + MvcResult result = mvc.perform(put(PATH + "/" + userRO.getUserId() + "/create") + .session(session) + .with(csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content(entitiToString(testDomain))) + .andExpect(status().isOk()).andReturn(); + + DomainRO resultObject = parseResponse(result, DomainRO.class); + assertNotNull(resultObject); + assertNotNull(resultObject.getDomainId()); + assertEquals(testDomain.getDomainCode(), resultObject.getDomainCode()); + } + + @Test + public void testCreateDomainWithEmptyCode() throws Exception { + DomainRO testDomain = TestROUtils.createDomain(""); + + MockHttpSession session = loginWithSystemAdmin(mvc); + UserRO userRO = MockMvcUtils.getLoggedUserData(mvc, session); + + MvcResult result = mvc.perform(put(PATH + "/" + userRO.getUserId() + "/create") + .session(session) + .with(csrf()) + .contentType(MediaType.APPLICATION_JSON) + .content(entitiToString(testDomain))) + .andExpect(status().is4xxClientError()).andReturn(); + + ErrorResponseRO errorRO = getObjectFromResponse(result, ErrorResponseRO.class); + assertNotNull(errorRO); + assertEquals(ErrorBusinessCode.INVALID_INPUT_DATA.name(), errorRO.getBusinessCode()); + MatcherAssert.assertThat(errorRO.getErrorDescription(), Matchers.containsString("Invalid domain data! Domain code must not be empty!")); + } + + @Test + public void testUpdateResourceDefDomainList() throws Exception { + String domainCode = "domainTwo"; + String documentType = "edelivery-oasis-cppa"; + MockHttpSession session = loginWithSystemAdmin(mvc); + UserRO userRO = (UserRO) session.getAttribute(MOCK_LOGGED_USER); + + DomainRO domainToUpdate = getDomain(domainCode, userRO, session); + assertTrue(domainToUpdate.getResourceDefinitions().isEmpty()); + + MvcResult result = mvc.perform(post(PATH + "/" + userRO.getUserId() + "/" + domainToUpdate.getDomainId() + "/update-resource-types") + .session(session) + .with(csrf()) + .header("Content-Type", " application/json") + .content(entitiToString(Collections.singletonList(documentType)))) + .andExpect(status().isOk()).andReturn(); + DomainRO resultObject = parseResponse(result, DomainRO.class); + // + assertNotNull(resultObject); + assertEquals(1, resultObject.getResourceDefinitions().size()); + assertEquals(documentType, resultObject.getResourceDefinitions().get(0)); + } + @Test public void testDeleteDomainOK() throws Exception { // given - delete domain two :) @@ -70,7 +132,7 @@ public class DomainAdminResourceIT extends AbstractControllerTest { DomainRO domainToDelete = getDomain(domainCode, userRO, session); assertNotNull(domainToDelete); - MvcResult result = mvc.perform(delete(PATH + "/" + userRO.getUserId() + "/" + domainToDelete.getDomainId() + "" + "/delete") + MvcResult result = mvc.perform(delete(PATH + "/" + userRO.getUserId() + "/" + domainToDelete.getDomainId() + "/delete") .session(session) .with(csrf()) .header("Content-Type", " application/json")) // delete domain with id 2 @@ -91,7 +153,7 @@ public class DomainAdminResourceIT extends AbstractControllerTest { domainToUpdate.setDomainCode("NewCode"); domainToUpdate.setSignatureKeyAlias("New alias"); - MvcResult result = mvc.perform(post(PATH + "/" + userRO.getUserId() + "/" + domainToUpdate.getDomainId() + "" + "/update") + MvcResult result = mvc.perform(post(PATH + "/" + userRO.getUserId() + "/" + domainToUpdate.getDomainId() + "/update") .session(session) .with(csrf()) .header("Content-Type", " application/json") @@ -114,7 +176,7 @@ public class DomainAdminResourceIT extends AbstractControllerTest { domainToUpdate.setSmlSubdomain("NewCode"); domainToUpdate.setSmlClientKeyAlias("New alias"); - MvcResult result = mvc.perform(post(PATH + "/" + userRO.getUserId() + "/" + domainToUpdate.getDomainId() + "" + "/update-sml-integration-data") + MvcResult result = mvc.perform(post(PATH + "/" + userRO.getUserId() + "/" + domainToUpdate.getDomainId() + "/update-sml-integration-data") .session(session) .with(csrf()) .header("Content-Type", " application/json") @@ -128,7 +190,6 @@ public class DomainAdminResourceIT extends AbstractControllerTest { } @Test - @Disabled public void updateDomainDataAddNewResourceDef() throws Exception { // set the webapp_integration_test_data.sql for resourceDefID String resourceDefID = "edelivery-oasis-cppa"; @@ -138,7 +199,7 @@ public class DomainAdminResourceIT extends AbstractControllerTest { DomainRO domainToUpdate = getDomain(domainCode, userRO, session); domainToUpdate.getResourceDefinitions().add(resourceDefID); - MvcResult result = mvc.perform(post(PATH + "/" + userRO.getUserId() + "/" + domainToUpdate.getDomainId() + "" + "/update-resource-types") + MvcResult result = mvc.perform(post(PATH + "/" + userRO.getUserId() + "/" + domainToUpdate.getDomainId() + "/update-resource-types") .session(session) .with(csrf()) .header("Content-Type", " application/json") @@ -151,110 +212,6 @@ public class DomainAdminResourceIT extends AbstractControllerTest { assertEquals(EntityROStatus.UPDATED.getStatusNumber(), resultObject.getStatus()); } -/* - @Test - public void updateDomainListNotExists() throws Exception { -// given when - MockHttpSession session = loginWithSystemAdmin(mvc); - - - MvcResult result = mvc.perform(put(PATH) - .session(session) - .with(csrf()) - .header("Content-Type", " application/json") - .content("[{\"status\":3,\"index\":9,\"id\":10,\"domainCode\":\"domainTwoNotExist\",\"smlSubdomain\":\"newdomain\",\"smlSmpId\":\"CEF-SMP-010\",\"smlParticipantIdentifierRegExp\":null,\"smlClientCertHeader\":null,\"smlClientKeyAlias\":null,\"signatureKeyAlias\":\"sig-key\",\"smlClientCertAuth\":true,\"smlRegistered\":false}]")) // delete domain with id 2 - .andExpect(status().isOk()).andReturn(); - } - - @Test - public void validateDeleteDomainOK() throws Exception { - // given when - MockHttpSession session = loginWithSystemAdmin(mvc); - MvcResult result = mvc.perform(put(PATH + "/validate-delete") - .session(session) - .with(csrf()) - .header("Content-Type", " application/json") - .content("[2]")) // delete domain with id 2 - .andExpect(status().isOk()).andReturn(); - - //then - ObjectMapper mapper = new ObjectMapper(); - DeleteEntityValidation res = mapper.readValue(result.getResponse().getContentAsString(), DeleteEntityValidation.class); - - assertNotNull(res); - assertTrue(res.getListDeleteNotPermitedIds().isEmpty()); - assertEquals(1, res.getListIds().size()); - assertEquals(true, res.isValidOperation()); - assertNull(res.getStringMessage()); - } - - @Test - public void updateDomainListOkUpdate() throws Exception { -// given when - assertEquals("CEF-SMP-002", domainDao.getDomainByCode("domainTwo").get().getSmlSmpId()); - MockHttpSession session = loginWithSystemAdmin(mvc); - MvcResult result = mvc.perform(put(PATH) - .session(session) - .with(csrf()) - .header("Content-Type", " application/json") - .content("[{\"status\":1,\"index\":9,\"id\":2,\"domainCode\":\"domainTwo\",\"smlSubdomain\":\"newdomain\",\"smlSmpId\":\"CEF-SMP-010\",\"smlParticipantIdentifierRegExp\":null,\"smlClientCertHeader\":null,\"smlClientKeyAlias\":null,\"signatureKeyAlias\":\"sig-key\",\"smlClientCertAuth\":true,\"smlRegistered\":false}]")) // delete domain with id 2 - .andExpect(status().isOk()).andReturn(); - - // check if exists - assertEquals("CEF-SMP-010", domainDao.getDomainByCode("domainTwo").get().getSmlSmpId()); - } - - @Test - public void validateDeleteDomainFalse() throws Exception { - // given when - MockHttpSession session = loginWithSystemAdmin(mvc); - MvcResult result = mvc.perform(put(PATH + "/validate-delete") - .session(session) - .with(csrf()) - .header("Content-Type", " application/json") - .content("[1]")) // delete domain with id 2 - .andExpect(status().isOk()).andReturn(); - - //them - ObjectMapper mapper = new ObjectMapper(); - DeleteEntityValidation res = mapper.readValue(result.getResponse().getContentAsString(), DeleteEntityValidation.class); - - assertNotNull(res); - assertEquals(1, res.getListDeleteNotPermitedIds().size()); - assertEquals(1, res.getListIds().size()); - assertEquals(false, res.isValidOperation()); - assertEquals("Could not delete domains used by Service groups! Domain: domain (domain ) uses by:1 SG.", res.getStringMessage()); - } - - @Test - public void registerDomainAndParticipantsNotEnabled() throws Exception { - // given when - // 3- user id - // domainTwo - domain code - MockHttpSession session = loginWithSystemAdmin(mvc); - mvc.perform(put(PATH + "/3/sml-register/domainTwo") - .session(session) - .with(csrf()) - .header("Content-Type", " application/json")) - .andExpect(status().isOk()) - .andExpect(content().string(stringContainsInOrder("Configuration error: [SML integration is not enabled!]!"))); - } - - @Test - public void unregisterDomainAndParticipants() throws Exception { - // given when - // 3- user id - // domainTwo - domain code - MockHttpSession session = loginWithSystemAdmin(mvc); - mvc.perform(put(PATH + "/3/sml-unregister/domainTwo") - .session(session) - .with(csrf()) - .header("Content-Type", " application/json")) - .andExpect(status().isOk()) - .andExpect(content().string(stringContainsInOrder("Configuration error: SML integration is not enabled!!"))); - } -*/ - private List<DomainRO> getAllDomains(UserRO userRO, MockHttpSession session) throws Exception { MvcResult result = mvc.perform(get(PATH + "/" + userRO.getUserId()) .session(session) diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/KeystoreAdminControllerIT.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/KeystoreAdminControllerIT.java index b4d3c7caf5d9fd78e0fa3d44758e13604fa2853f..10a1e17365d49b2a7c080116f18ed02e5e2f72f9 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/KeystoreAdminControllerIT.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/KeystoreAdminControllerIT.java @@ -126,14 +126,14 @@ public class KeystoreAdminControllerIT extends AbstractControllerTest { } @Test - public void deleteKeystoreEntryOK() throws Exception { + public void deleteCertificateOK() throws Exception { MockHttpSession session = loginWithSystemAdmin(mvc); UserRO userRO = getLoggedUserData(mvc, session); - + String alias = "second_domain_alias"; int countStart = uiKeystoreService.getKeystoreEntriesList().size(); // given when - MvcResult result = mvc.perform(delete(PATH + "/" + userRO.getUserId() + "/delete/second_domain_alias") + MvcResult result = mvc.perform(delete(PATH + "/" + userRO.getUserId() + "/delete/" + alias) .session(session) .with(csrf())) .andExpect(status().isOk()).andReturn(); @@ -147,5 +147,19 @@ public class KeystoreAdminControllerIT extends AbstractControllerTest { assertEquals(countStart - 1, uiKeystoreService.getKeystoreEntriesList().size()); } + @Test + public void deleteCertificateNotExists() throws Exception { + MockHttpSession session = loginWithSystemAdmin(mvc); + UserRO userRO = getLoggedUserData(mvc, session); + String alias = "alias-not-exists"; + // given when + MvcResult result = mvc.perform(delete(PATH + "/" + userRO.getUserId() + "/delete/"+ alias) + .session(session) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); + + CertificateRO res = getObjectFromResponse(result, CertificateRO.class); + assertEquals("Certificate Key not removed because alias ["+alias+"] does not exist in keystore!", res.getActionMessage()); + } } diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/TruststoreAdminControllerTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/TruststoreAdminControllerTest.java index 1864ede10f5ef7de1b4056c8c7f12434a81a24f8..d8cf8fd00d464cbf0974de84e65d76b4fb4a0ea6 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/TruststoreAdminControllerTest.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/TruststoreAdminControllerTest.java @@ -112,7 +112,6 @@ public class TruststoreAdminControllerTest extends AbstractControllerTest { @Test public void testDeleteCertificateFailed() throws Exception { - String alias = UUID.randomUUID().toString(); MockHttpSession session = loginWithSystemAdmin(mvc); diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminControllerIT.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminControllerIT.java index e5109dca73eff3091fd1f1f5f1d7a2eebfcb7e9e..49970f1c25dc6d7d7da199a4d89b71362fccde45 100644 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminControllerIT.java +++ b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/ui/internal/UserAdminControllerIT.java @@ -15,6 +15,7 @@ import java.util.Map; import java.util.UUID; import static eu.europa.ec.edelivery.smp.test.testutils.MockMvcUtils.*; +import static eu.europa.ec.edelivery.smp.ui.ResourceConstants.PARAM_PAGINATION_FILTER; import static org.junit.Assert.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; @@ -48,6 +49,40 @@ public class UserAdminControllerIT extends AbstractControllerTest { }); } + @Test + public void testSearch() throws Exception { + MockHttpSession session = loginWithSystemAdmin(mvc); + UserRO userROAdmin = getLoggedUserData(mvc, session); + MvcResult result = mvc.perform(get(PATH_INTERNAL + "/{user-enc-id}/search", userROAdmin.getUserId()) + .session(session) + .with(csrf())) + .andExpect(status().isOk()).andReturn(); + ServiceResult res = getObjectMapper().readValue(result.getResponse().getContentAsString(), ServiceResult.class); + // then + assertNotNull(res); + assertEquals(7, res.getServiceEntities().size()); + res.getServiceEntities().forEach(sgMap -> { + UserRO sgro = getObjectMapper().convertValue(sgMap, UserRO.class); + assertNotNull(sgro.getUserId()); + assertNotNull(sgro.getUsername()); + }); + } + + @Test + public void testSearchFilterNoMatch() throws Exception { + MockHttpSession session = loginWithSystemAdmin(mvc); + UserRO userROAdmin = getLoggedUserData(mvc, session); + MvcResult result = mvc.perform(get(PATH_INTERNAL + "/{user-enc-id}/search", userROAdmin.getUserId()) + .session(session) + .param(PARAM_PAGINATION_FILTER, "no-user-matches-this-filter") + .with(csrf())) + .andExpect(status().isOk()).andReturn(); + ServiceResult res = getObjectMapper().readValue(result.getResponse().getContentAsString(), ServiceResult.class); + // then + assertNotNull(res); + assertEquals(0, res.getServiceEntities().size()); + } + @Test public void testValidateDeleteUserOK() throws Exception { diff --git a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/validation/ServiceGroupValidatorTest.java b/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/validation/ServiceGroupValidatorTest.java deleted file mode 100644 index b53d8c877b1226a3a1f5aa066567ddc4a681a122..0000000000000000000000000000000000000000 --- a/smp-webapp/src/test/java/eu/europa/ec/edelivery/smp/validation/ServiceGroupValidatorTest.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2017 European Commission | CEF eDelivery - * - * Licensed under the EUPL, Version 1.2 or – as soon they will be approved by the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * - * You may obtain a copy of the Licence attached in file: LICENCE-EUPL-v1.2.pdf - * - * Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and limitations under the Licence. - */ - -package eu.europa.ec.edelivery.smp.validation; - -import eu.europa.ec.edelivery.smp.conversion.IdentifierService; -import eu.europa.ec.edelivery.smp.identifiers.Identifier; -import eu.europa.ec.edelivery.smp.services.ConfigurationService; - -import org.hamcrest.CoreMatchers; -import org.hamcrest.MatcherAssert; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.mockito.Mockito; - -import java.util.Arrays; -import java.util.Collection; -import java.util.regex.Pattern; - -/** - * Created by gutowpa on 02/08/2017. - */ -@RunWith(Parameterized.class) -@Ignore -public class ServiceGroupValidatorTest { -/* - private static final Pattern ALLOWED_SCHEME_PATTERN = Pattern.compile("^$|^(?!^.{26})([a-z0-9]+-[a-z0-9]+-[a-z0-9]+)$|^urn:oasis:names:tc:ebcore:partyid-type:(iso6523|unregistered)(:.+)?$"); - - private ServiceGroupValidator validator; - ConfigurationService configurationService = Mockito.mock(ConfigurationService.class); - IdentifierService normalizer = new IdentifierService(configurationService); - - @Parameterized.Parameters(name = "{index}: {0}") - public static Collection<Object[]> data() { - return Arrays.asList(new Object[][]{ - - {"Good peppol schema", "good6-scheme4-ok", "urn:poland:ncpb", false, true, ALLOWED_SCHEME_PATTERN, null, null}, - {"Allowed null schema", null, "urn:poland:ncpb", false, false, ALLOWED_SCHEME_PATTERN, null, null}, - {"Length exceeded", "ength-exceeeeeedsTheCharacters-25chars", "urn:poland:ncpb", true, true, ALLOWED_SCHEME_PATTERN, MalformedIdentifierException.class, "Scheme does not match pattern:"}, - {"Too many parts", "too-many-segments-inside", "urn:poland:ncpb", true, true, ALLOWED_SCHEME_PATTERN, MalformedIdentifierException.class, "Scheme does not match pattern:"}, - {"Missing parts", "only-two", "urn:poland:ncpb", true, true, ALLOWED_SCHEME_PATTERN, MalformedIdentifierException.class, "Scheme does not match pattern: "}, - {"Null not allowed", null, "urn:poland:ncpb", true, true, ALLOWED_SCHEME_PATTERN, IllegalArgumentException.class, "Invalid Identifier: "}, - {"EBCorePartyId Oasis", "urn:oasis:names:tc:ebcore:partyid-type:iso6523:0088", "123456", false, true, ALLOWED_SCHEME_PATTERN, null, null}, - {"EBCorePartyId eDelivery", null, "urn:oasis:names:tc:ebcore:partyid-type:iso6523:0088:123456", false, true, ALLOWED_SCHEME_PATTERN, null, null}, - }); - } - - @Before - public void init() { - validator = new ServiceGroupValidator(configurationService, normalizer); - } - - @Parameterized.Parameter - public String caseName; - @Parameterized.Parameter(1) - public String schema; - @Parameterized.Parameter(2) - public String value; - @Parameterized.Parameter(3) - public boolean expectedThrowError; - @Parameterized.Parameter(4) - public boolean mandatoryScheme; - @Parameterized.Parameter(5) - public Pattern schemePattern; - @Parameterized.Parameter(6) - public Class errorClass; - @Parameterized.Parameter(7) - public String errorMessage; - - - @Test - public void testServiceGroupIdentifier() { - normalizer.configureParticipantIdentifierFormatter(null, mandatoryScheme, schemePattern); - - validateScheme(schema, value); - } - - private void validateScheme(String scheme, String value) { - - Identifier id = new Identifier(value, scheme); - /* - //ServiceGroup sg = new ServiceGroup(); - sg.setParticipantIdentifier(id); - - if (expectedThrowError) { - Throwable throwable = Assert.assertThrows(errorClass, () -> validator.validate(normalizer.formatParticipant(id), sg)); - MatcherAssert.assertThat(throwable.getMessage(), CoreMatchers.containsString(errorMessage)); - } else { - validator.validate(normalizer.formatParticipant(id), sg); - } - - - } - */ - -}