From a2feaf9b65cbba66181fb560b5815a62427d65cc Mon Sep 17 00:00:00 2001 From: vasraz Date: Fri, 5 May 2023 11:57:56 +0100 Subject: Support SIP TLS Signed-off-by: Vasyl Razinkov Change-Id: Icbadd04cfa87302491c59f2e4a39ef92aaafcaa3 Issue-ID: SDC-4483 --- catalog-be/pom.xml | 58 ++- catalog-be/src/main/docker/backend/Dockerfile | 2 +- .../cookbooks/sdc-catalog-be/attributes/default.rb | 4 +- .../sdc-catalog-be/recipes/BE_4_jetty_Modules.rb | 2 + .../sdc-catalog-be/templates/default/ssl-ini.erb | 8 +- .../sdc/be/filters/BeCadiServletFilter.java | 151 ------- .../sdc/be/listen/BEAppContextListener.java | 1 + .../sdc/config/CatalogBESpringConfig.java | 52 ++- catalog-fe/sdc-frontend/Dockerfile | 2 +- .../cookbooks/sdc-catalog-fe/attributes/default.rb | 4 +- .../recipes/FE_7_create_jetty_modules.rb | 2 + .../sdc-catalog-fe/templates/default/ssl-ini.erb | 8 +- .../org/openecomp/sdc/fe/impl/PluginStatusBL.java | 29 +- .../sdc/fe/listen/FEAppContextListener.java | 2 + .../openecomp/sdc/fe/servlets/FeProxyServlet.java | 33 +- .../openecomp/sdc/fe/servlets/SSLProxyServlet.java | 26 +- .../sdc/fe/servlets/FeProxyServletTest.java | 483 +++++++++++---------- common-app-api/pom.xml | 6 + .../sdc/be/config/ConfigurationManager.java | 9 +- .../common/http/client/api/HttpClientFactory.java | 34 +- .../sdc/common/http/client/api/HttpResponse.java | 36 +- .../sdc/common/listener/AppContextListener.java | 2 + .../ApacheClientLogRequestInterceptor.java | 63 --- .../ApacheClientLogResponseInterceptor.java | 51 --- .../org/openecomp/sdc/common/util/StreamUtils.java | 132 ------ .../sdc/fe/config/ConfigurationManager.java | 5 +- .../http/client/api/HttpClientFactoryTest.java | 16 +- .../common/http/client/api/HttpResponseTest.java | 26 +- .../sdc/common/util/StreamUtilsTests.java | 142 ------ .../onap-configuration-management-api/pom.xml | 5 + .../java/org/onap/config/api/JettySSLUtils.java | 79 ++-- .../item-rest/item-rest-services/pom.xml | 5 + .../rest/services/VnfPackageRepositoryImpl.java | 50 +-- .../backend/openecomp-sdc-security-util/pom.xml | 6 - .../artifacts/Dockerfile | 2 +- .../sdc-onboard-backend/attributes/default.rb | 12 +- .../recipes/ON_4_setup_jetty_modules.rb | 16 +- .../templates/default/ssl-ini.erb | 8 +- .../artifacts/startup.sh | 4 +- .../openecomp-sdc-logging-core/pom.xml | 5 - .../openecomp-sdc-validation-impl/pom.xml | 198 ++++----- pom.xml | 15 +- utils/webseal-simulator/sdc-simulator/Dockerfile | 2 +- .../SDC_Simulator_5_create_jetty_modules.rb | 6 +- .../templates/default/SDC-Simulator-ssl-ini.erb | 8 +- .../openecomp/sdc/webseal/simulator/SdcProxy.java | 102 +++-- 46 files changed, 733 insertions(+), 1179 deletions(-) delete mode 100644 catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java delete mode 100644 common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java delete mode 100644 common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java delete mode 100644 common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java delete mode 100644 common-app-api/src/test/java/org/openecomp/sdc/common/util/StreamUtilsTests.java diff --git a/catalog-be/pom.xml b/catalog-be/pom.xml index 9f5348acd7..987b2e7c64 100644 --- a/catalog-be/pom.xml +++ b/catalog-be/pom.xml @@ -1,6 +1,6 @@ + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 catalog-be @@ -19,6 +19,7 @@ 3.2.0 1.5.3 ${project.version} + 7.4.11 @@ -40,6 +41,12 @@ ${jsoup.version} + + org.slf4j + slf4j-api + ${slf4j-api.version} + + com.fasterxml.jackson.core @@ -216,11 +223,11 @@ - - io.micrometer - micrometer-registry-prometheus - ${micrometer.version} - + + io.micrometer + micrometer-registry-prometheus + ${micrometer.version} + ch.qos.logback @@ -618,7 +625,6 @@ compile - com.att.nsa @@ -821,31 +827,6 @@ - - - org.onap.aaf.authz - aaf-cadi-aaf - ${cadi.version} - - - com.datastax.cassandra - cassandra-driver-core - - - org.slf4j - slf4j-log4j12 - - - log4j - log4j - - - javax.servlet - javax.servlet-api - - - - org.assertj @@ -1062,6 +1043,17 @@ kafka-clients + + io.github.hakky54 + sslcontext-kickstart-for-jetty + ${io.github.hakky54.version} + + + io.github.hakky54 + sslcontext-kickstart + ${io.github.hakky54.version} + + diff --git a/catalog-be/src/main/docker/backend/Dockerfile b/catalog-be/src/main/docker/backend/Dockerfile index db2ab154ca..5f83e75db6 100644 --- a/catalog-be/src/main/docker/backend/Dockerfile +++ b/catalog-be/src/main/docker/backend/Dockerfile @@ -1,4 +1,4 @@ -FROM onap/integration-java11:9.0.0 +FROM onap/integration-java11:10.0.0 USER root ARG JETTY_FOLDER=/app/jetty diff --git a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb index a3e519826c..ba94e21449 100644 --- a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb +++ b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/attributes/default.rb @@ -11,11 +11,11 @@ default['disableHttp'] = true #| Jetty | #| | #+----------------------------------+ - default['jetty']['dmaap_truststore_pwd'] = "dmaap_truststore_pwd" +default['jetty']['keystore_path'] = "etc/org.onap.sdc.p12" default['jetty']['keystore_pwd'] = "?(kP!Yur![*!Y5!E^f(ZKc31" default['jetty']['keymanager_pwd'] = "?(kP!Yur![*!Y5!E^f(ZKc31" -default['jetty']['truststore_path'] = "#{ENV['JETTY_BASE']}/etc/truststore" +default['jetty']['truststore_path'] = "etc/org.onap.sdc.trust.jks" # TO CHANGE THE TRUSTSTORE CERT THE JVM CONFIGURATION # MUST BE ALSO CHANGE IN THE startup.sh FILE default['jetty'][:truststore_pwd] = "z+KEj;t+,KN^iimSiS89e#p0" diff --git a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_jetty_Modules.rb b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_jetty_Modules.rb index 5655d0fd6f..ad66a67e22 100644 --- a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_jetty_Modules.rb +++ b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/recipes/BE_4_jetty_Modules.rb @@ -51,8 +51,10 @@ template "ssl-ini" do mode "0755" variables ({ :https_port => "#{node['BE'][:https_port]}" , + :jetty_keystore_path => "#{node['jetty'][:keystore_path]}" , :jetty_keystore_pwd => "#{node['jetty'][:keystore_pwd]}" , :jetty_keymanager_pwd => "#{node['jetty'][:keymanager_pwd]}" , + :jetty_truststore_path => "#{node['jetty'][:truststore_path]}", :jetty_truststore_pwd => "#{node['jetty'][:truststore_pwd]}" }) end diff --git a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/ssl-ini.erb b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/ssl-ini.erb index 278fdea2ae..c489825c7b 100644 --- a/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/ssl-ini.erb +++ b/catalog-be/src/main/docker/backend/chef-repo/cookbooks/sdc-catalog-be/templates/default/ssl-ini.erb @@ -42,17 +42,17 @@ jetty.ssl.port=<%= @https_port %> ## See http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html ## Keystore file path (relative to $jetty.base) -jetty.sslContext.keyStorePath=etc/org.onap.sdc.p12 +jetty.sslContext.keyStorePath=<%= @jetty_keystore_path %> ## Truststore file path (relative to $jetty.base) -jetty.sslContext.trustStorePath=etc/org.onap.sdc.trust.jks +jetty.sslContext.trustStorePath=<%= @jetty_truststore_path %> ## Keystore password # jetty.sslContext.keyStorePassword=OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4 jetty.sslContext.keyStorePassword=<%= @jetty_keystore_pwd %> ## Keystore type and provider -# jetty.sslContext.keyStoreType=JKS +jetty.sslContext.keyStoreType=JKS # jetty.sslContext.keyStoreProvider= ## KeyManager password @@ -64,7 +64,7 @@ jetty.sslContext.keyManagerPassword=<%= @jetty_keymanager_pwd %> jetty.sslContext.trustStorePassword=<%= @jetty_truststore_pwd %> ## Truststore type and provider -# jetty.sslContext.trustStoreType=JKS +jetty.sslContext.trustStoreType=JKS # jetty.sslContext.trustStoreProvider= ## whether client certificate authentication is required diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java deleted file mode 100644 index 7edd1621b1..0000000000 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java +++ /dev/null @@ -1,151 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.openecomp.sdc.be.filters; - -import java.io.IOException; -import java.util.function.Supplier; -import javax.annotation.Priority; -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import org.onap.aaf.cadi.Access; -import org.onap.aaf.cadi.PropAccess; -import org.onap.aaf.cadi.config.Config; -import org.onap.aaf.cadi.filter.CadiFilter; -import org.openecomp.sdc.be.components.impl.CADIHealthCheck; -import org.openecomp.sdc.be.config.CadiFilterParams; -import org.openecomp.sdc.be.config.ConfigurationManager; -import org.openecomp.sdc.be.impl.WebAppContextWrapper; -import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.api.HealthCheckInfo; -import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.util.ThreadLocalsHolder; -import org.springframework.web.context.WebApplicationContext; - -@Priority(2) -public class BeCadiServletFilter extends CadiFilter { - - private static final Logger log = Logger.getLogger(BeCadiServletFilter.class); - private static final String BE_CADI_SERVICE_FILTER = "BeCadiServletFilter: "; - private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); - - public BeCadiServletFilter() { - super(); - log.debug(BE_CADI_SERVICE_FILTER); - } - - /** - * This constructor to be used when directly constructing and placing in HTTP Engine - * - * @param access - * @param moreTafLurs - * @throws ServletException - */ - public BeCadiServletFilter(Access access, Object... moreTafLurs) throws ServletException { - super(access, moreTafLurs); - log.debug(BE_CADI_SERVICE_FILTER); - } - - /** - * Use this to pass in a PreContructed CADI Filter, but with initializing... let Servlet do it - * - * @param init - * @param access - * @param moreTafLurs - * @throws ServletException - */ - public BeCadiServletFilter(boolean init, PropAccess access, Object... moreTafLurs) throws ServletException { - super(init, access, moreTafLurs); - log.debug(BE_CADI_SERVICE_FILTER); - } - - private void checkIfNullProperty(String key, String value) { - /* When value is null, so not defined in application.properties - set nothing in System properties */ - if (value != null) { - /* Ensure that any properties already defined in System.prop by JVM params - won't be overwritten by Spring application.properties values */ - System.setProperty(key, System.getProperty(key, value)); - } - } - - @Override - public void init(FilterConfig filterConfig) throws ServletException { - // set some properties in System so that Cadi filter will find its config - - // The JVM values set will always overwrite the Spring ones. - CadiFilterParams cadiFilterParams = configurationManager.getConfiguration().getCadiFilterParams(); - checkIfNullProperty(Config.HOSTNAME, cadiFilterParams.getHostname()); - log.debug("BeCadiServletFilter: HOSTNAME", cadiFilterParams.getHostname()); - checkIfNullProperty(Config.CADI_KEYFILE, cadiFilterParams.getCadi_keyfile()); - checkIfNullProperty(Config.CADI_LOGLEVEL, cadiFilterParams.getCadi_loglevel()); - checkIfNullProperty(Config.CADI_LATITUDE, cadiFilterParams.getAFT_LATITUDE()); - checkIfNullProperty(Config.CADI_LONGITUDE, cadiFilterParams.getAFT_LONGITUDE()); - checkIfNullProperty(Config.AAF_URL, cadiFilterParams.getAaf_url()); - //checkIfNullProperty(Config.AAF_LOCATE_URL, cadiFilterParams.getAafLocateUrl()); - checkIfNullProperty(Config.AAF_APPID, cadiFilterParams.getAaf_id()); - checkIfNullProperty(Config.AAF_APPPASS, cadiFilterParams.getAaf_password()); - checkIfNullProperty(Config.AAF_ENV, cadiFilterParams.getAFT_ENVIRONMENT()); - checkIfNullProperty(Config.CADI_X509_ISSUERS, cadiFilterParams.getCadiX509Issuers()); - checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiFilterParams.getCadi_truststore()); - checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiFilterParams.getCadi_truststore_password()); - super.init(filterConfig); - log.debug("BeCadiServletFilter finishing init(), Current status of CADI would be UP"); - if (!isNeedAuth()) { - CADIHealthCheck.getCADIHealthCheckInstance().setIsCADIUp(HealthCheckInfo.HealthCheckStatus.DOWN); - } else { - CADIHealthCheck.getCADIHealthCheckInstance().setIsCADIUp(HealthCheckInfo.HealthCheckStatus.UP); - } - } - - @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - if (ThreadLocalsHolder.isExternalRequest() && isNeedAuth()) { - log.debug("doFilter: {}", request.getContentType()); - HttpServletRequest hreq = (HttpServletRequest) request; - log.debug("Need aaf authentication : {}", hreq); - ThreadLocalUtils threadLocalUtils = getThreadLocalUtils(((HttpServletRequest) request).getSession().getServletContext()); - threadLocalUtils.setUserContext((HttpServletRequest) request); - super.doFilter(request, response, chain); - } else { - log.debug("No need aaf authentication"); - chain.doFilter(request, response); - } - } - - private boolean isNeedAuth() { - return configurationManager.getConfiguration().getAafAuthNeeded(); - } - - ThreadLocalUtils getThreadLocalUtils(ServletContext context) { - return getClassFromWebAppContext(context, () -> ThreadLocalUtils.class); - } - - T getClassFromWebAppContext(ServletContext context, Supplier> businessLogicClassGen) { - WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context - .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); - WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); - return webApplicationContext.getBean(businessLogicClassGen.get()); - } -} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java index 76be33cedf..0bd921db54 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/listen/BEAppContextListener.java @@ -39,6 +39,7 @@ public class BEAppContextListener extends AppContextListener implements ServletC private static final String MANIFEST_FILE_NAME = "/META-INF/MANIFEST.MF"; private static final Logger log = Logger.getLogger(BEAppContextListener.class); + @Override public void contextInitialized(ServletContextEvent context) { super.contextInitialized(context); ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource()); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java index b38210116c..c423795a2f 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/config/CatalogBESpringConfig.java @@ -21,7 +21,11 @@ */ package org.openecomp.sdc.config; +import nl.altindag.ssl.SSLFactory; +import nl.altindag.ssl.util.JettySslUtils; import org.apache.http.impl.client.CloseableHttpClient; +import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.onap.config.api.JettySSLUtils; import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; import org.onap.sdc.security.PortalClient; import org.openecomp.sdc.be.auditing.impl.ConfigurationProvider; @@ -29,19 +33,27 @@ import org.openecomp.sdc.be.components.impl.ComponentLocker; import org.openecomp.sdc.be.components.impl.aaf.RoleAuthorizationHandler; import org.openecomp.sdc.be.components.impl.lock.ComponentLockAspect; import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic; +import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; import org.openecomp.sdc.be.ecomp.converters.AssetMetadataConverter; import org.openecomp.sdc.be.filters.FilterConfiguration; import org.openecomp.sdc.be.filters.PortalConfiguration; import org.openecomp.sdc.be.filters.ThreadLocalUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; +import javax.net.ssl.SSLSessionContext; +import javax.net.ssl.X509ExtendedKeyManager; +import javax.net.ssl.X509ExtendedTrustManager; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; + + // @formatter:off -@Configuration +@org.springframework.context.annotation.Configuration @ComponentScan({ "org.openecomp.sdc.be.user", "org.openecomp.sdc.be.facade.operations", @@ -73,10 +85,11 @@ public class CatalogBESpringConfig { private static final int BEFORE_TRANSACTION_MANAGER = 0; private final ComponentLocker componentLocker; + private final JettySSLUtils.JettySslConfig sslConfig; - @Autowired public CatalogBESpringConfig(ComponentLocker componentLocker) { this.componentLocker = componentLocker; + sslConfig = JettySSLUtils.getSSLConfig(); } @Bean(name = "lifecycleBusinessLogic") @@ -132,7 +145,36 @@ public class CatalogBESpringConfig { } @Bean - public org.openecomp.sdc.be.config.Configuration configuration() { + public Configuration configuration() { return ConfigurationManager.getConfigurationManager().getConfiguration(); } + + @Bean + public SSLFactory sslFactory() throws IOException { + return SSLFactory.builder().withSwappableIdentityMaterial() + .withIdentityMaterial(Files.newInputStream(Path.of(sslConfig.getKeystorePath()), StandardOpenOption.READ), sslConfig.getKeystorePass().toCharArray(), sslConfig.getKeystoreType()).withSwappableTrustMaterial() + .withTrustMaterial(Files.newInputStream(Path.of(sslConfig.getTruststorePath()), StandardOpenOption.READ), sslConfig.getTruststorePass().toCharArray(), sslConfig.getTruststoreType()).withNeedClientAuthentication() + .build(); + } + + @Bean + public SslContextFactory.Server sslContextFactory(SSLFactory sslFactory) { + return JettySslUtils.forServer(sslFactory); + } + + @Bean + public X509ExtendedKeyManager keyManager(SSLFactory sslFactory) throws Exception { + return sslFactory.getKeyManager().orElseThrow(Exception::new); + } + + @Bean + public X509ExtendedTrustManager trustManager(SSLFactory sslFactory) throws Exception { + return sslFactory.getTrustManager().orElseThrow(Exception::new); + } + + @Bean + public SSLSessionContext serverSessionContext(SSLFactory sslFactory) { + return sslFactory.getSslContext().getServerSessionContext(); + } + } diff --git a/catalog-fe/sdc-frontend/Dockerfile b/catalog-fe/sdc-frontend/Dockerfile index 7de4b1f3fd..341dda2410 100644 --- a/catalog-fe/sdc-frontend/Dockerfile +++ b/catalog-fe/sdc-frontend/Dockerfile @@ -1,4 +1,4 @@ -FROM onap/integration-java11:9.0.0 +FROM onap/integration-java11:10.0.0 USER root ARG JETTY_FOLDER=/app/jetty diff --git a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/attributes/default.rb b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/attributes/default.rb index 9fbb363bf9..85f8fcf6a3 100644 --- a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/attributes/default.rb +++ b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/attributes/default.rb @@ -4,8 +4,10 @@ default['BE'][:https_port] = 8443 default['FE'][:http_port] = 8181 default['FE'][:https_port] = 9443 default['disableHttp'] = true +default['jetty']['keystore_path'] = "etc/org.onap.sdc.p12" default['jetty'][:keystore_pwd] = "?(kP!Yur![*!Y5!E^f(ZKc31" default['jetty'][:keymanager_pwd] = "?(kP!Yur![*!Y5!E^f(ZKc31" +default['jetty']['truststore_path'] = "etc/org.onap.sdc.trust.jks" # TO CHANGE THE TRUSTSTORE CERT THE JVM CONFIGURATION # MUST BE ALSO CHANGE IN THE startup.sh FILE default['jetty'][:truststore_pwd] = "z+KEj;t+,KN^iimSiS89e#p0" @@ -17,4 +19,4 @@ default['ONBOARDING_BE'][:https_port] = 8445 #BasicAuth default['basic_auth']['enabled'] = true default['basic_auth'][:user_name] = "testName" -default['basic_auth'][:user_pass] = "testPass" \ No newline at end of file +default['basic_auth'][:user_pass] = "testPass" diff --git a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_create_jetty_modules.rb b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_create_jetty_modules.rb index 734c05ae02..e465d9f087 100644 --- a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_create_jetty_modules.rb +++ b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/recipes/FE_7_create_jetty_modules.rb @@ -49,8 +49,10 @@ template "ssl-ini" do mode "0755" variables({ :https_port => "#{node['FE'][:https_port]}" , + :jetty_keystore_path => "#{node['jetty'][:keystore_path]}" , :jetty_keystore_pwd => "#{node['jetty'][:keystore_pwd]}" , :jetty_keymanager_pwd => "#{node['jetty'][:keymanager_pwd]}" , + :jetty_truststore_path => "#{node['jetty'][:truststore_path]}", :jetty_truststore_pwd => "#{node['jetty'][:truststore_pwd]}" }) end diff --git a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/ssl-ini.erb b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/ssl-ini.erb index 278fdea2ae..c489825c7b 100644 --- a/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/ssl-ini.erb +++ b/catalog-fe/sdc-frontend/chef-repo/cookbooks/sdc-catalog-fe/templates/default/ssl-ini.erb @@ -42,17 +42,17 @@ jetty.ssl.port=<%= @https_port %> ## See http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html ## Keystore file path (relative to $jetty.base) -jetty.sslContext.keyStorePath=etc/org.onap.sdc.p12 +jetty.sslContext.keyStorePath=<%= @jetty_keystore_path %> ## Truststore file path (relative to $jetty.base) -jetty.sslContext.trustStorePath=etc/org.onap.sdc.trust.jks +jetty.sslContext.trustStorePath=<%= @jetty_truststore_path %> ## Keystore password # jetty.sslContext.keyStorePassword=OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4 jetty.sslContext.keyStorePassword=<%= @jetty_keystore_pwd %> ## Keystore type and provider -# jetty.sslContext.keyStoreType=JKS +jetty.sslContext.keyStoreType=JKS # jetty.sslContext.keyStoreProvider= ## KeyManager password @@ -64,7 +64,7 @@ jetty.sslContext.keyManagerPassword=<%= @jetty_keymanager_pwd %> jetty.sslContext.trustStorePassword=<%= @jetty_truststore_pwd %> ## Truststore type and provider -# jetty.sslContext.trustStoreType=JKS +jetty.sslContext.trustStoreType=JKS # jetty.sslContext.trustStoreProvider= ## whether client certificate authentication is required diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java index e1b4572a05..b095a1cde7 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/impl/PluginStatusBL.java @@ -21,8 +21,6 @@ package org.openecomp.sdc.fe.impl; import com.google.gson.Gson; import com.google.gson.GsonBuilder; -import java.io.IOException; -import java.security.GeneralSecurityException; import org.apache.http.HttpStatus; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; @@ -43,6 +41,8 @@ import org.openecomp.sdc.fe.config.ConfigurationManager; import org.openecomp.sdc.fe.config.PluginsConfiguration; import org.openecomp.sdc.fe.config.PluginsConfiguration.Plugin; +import java.io.IOException; + public class PluginStatusBL { private static final Logger log = Logger.getLogger(PluginStatusBL.class.getName()); @@ -74,23 +74,24 @@ public class PluginStatusBL { private boolean hasSecuredPlugins() { if (this.getPluginsList() != null) { return pluginsConfiguration.getPluginsList().stream() - .anyMatch(plugin -> plugin.getPluginDiscoveryUrl().toLowerCase().startsWith("https")); + .anyMatch(plugin -> plugin.getPluginDiscoveryUrl().toLowerCase().startsWith("https")); } return false; } - private CloseableHttpClient getPooledClient(boolean isSecured) throws GeneralSecurityException, IOException { + private CloseableHttpClient getPooledClient(final boolean isSecured) throws Exception { final PoolingHttpClientConnectionManager poolingConnManager; - if (!isSecured) { - poolingConnManager = new PoolingHttpClientConnectionManager(); - } else { - SSLConnectionSocketFactory s = new SSLConnectionSocketFactory(JettySSLUtils.getSslContext(), new NoopHostnameVerifier()); - Registry registry = RegistryBuilder.create() - .register("http", new PlainConnectionSocketFactory()).register("https", s).build(); + if (isSecured) { + final SSLConnectionSocketFactory s = new SSLConnectionSocketFactory(JettySSLUtils.getSslContext(), new NoopHostnameVerifier()); + final Registry registry = RegistryBuilder.create() + .register("http", new PlainConnectionSocketFactory()) + .register("https", s).build(); poolingConnManager = new PoolingHttpClientConnectionManager(registry); + } else { + poolingConnManager = new PoolingHttpClientConnectionManager(); } - int maxTotal = System.getProperties().containsKey(MAX_CONNECTION_POOL) ? Integer.parseInt(System.getProperty(MAX_CONNECTION_POOL)) : 5; - int routeMax = System.getProperties().containsKey(MAX_ROUTE_POOL) ? Integer.parseInt(System.getProperty(MAX_ROUTE_POOL)) : 20; + final int maxTotal = System.getProperties().containsKey(MAX_CONNECTION_POOL) ? Integer.parseInt(System.getProperty(MAX_CONNECTION_POOL)) : 5; + final int routeMax = System.getProperties().containsKey(MAX_ROUTE_POOL) ? Integer.parseInt(System.getProperty(MAX_ROUTE_POOL)) : 20; poolingConnManager.setMaxTotal(maxTotal); poolingConnManager.setDefaultMaxPerRoute(routeMax); return HttpClients.custom().setConnectionManager(poolingConnManager).setSSLHostnameVerifier(new NoopHostnameVerifier()).build(); @@ -115,9 +116,9 @@ public class PluginStatusBL { log.debug("The value returned from getConfig is {}", pluginsConfiguration); Integer connectionTimeout = pluginsConfiguration.getConnectionTimeout(); this.requestConfig = RequestConfig.custom().setSocketTimeout(connectionTimeout).setConnectTimeout(connectionTimeout) - .setConnectionRequestTimeout(connectionTimeout).build(); + .setConnectionRequestTimeout(connectionTimeout).build(); Plugin wantedPlugin = pluginsConfiguration.getPluginsList().stream().filter(plugin -> plugin.getPluginId().equals(pluginId)).findAny() - .orElse(null); + .orElse(null); if (wantedPlugin != null) { result = gson.toJson(checkPluginAvailability(wantedPlugin)); } diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java index 877d637a3e..79ef07a5da 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/listen/FEAppContextListener.java @@ -38,6 +38,7 @@ public class FEAppContextListener extends AppContextListener implements ServletC private static final int PROBE_INTERVALE = 15; private static Logger log = Logger.getLogger(FEAppContextListener.class.getName()); + @Override public void contextInitialized(ServletContextEvent context) { super.contextInitialized(context); ConfigurationManager configurationManager = new ConfigurationManager(ExternalConfiguration.getConfigurationSource()); @@ -61,6 +62,7 @@ public class FEAppContextListener extends AppContextListener implements ServletC log.debug("After executing {}", this.getClass()); } + @Override public void contextDestroyed(ServletContextEvent context) { ExecutorService executorPool = (ExecutorService) context.getServletContext().getAttribute(Constants.THREAD_EXECUTOR_ATTR); if (executorPool != null) { diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java index 0ef435311f..1bec4e48c4 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java @@ -19,13 +19,7 @@ */ package org.openecomp.sdc.fe.servlets; -import static org.apache.commons.lang3.StringUtils.isEmpty; - import com.google.common.annotations.VisibleForTesting; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Base64; -import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.NotImplementedException; import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.client.api.Request; @@ -44,6 +38,13 @@ import org.openecomp.sdc.fe.config.PluginsConfiguration.Plugin; import org.openecomp.sdc.fe.impl.LogHandler; import org.openecomp.sdc.fe.utils.BeProtocol; +import javax.servlet.http.HttpServletRequest; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Base64; + +import static org.apache.commons.lang3.StringUtils.isEmpty; + public class FeProxyServlet extends SSLProxyServlet { public static final String UUID = "uuid"; @@ -101,7 +102,7 @@ public class FeProxyServlet extends SSLProxyServlet { BasicAuthConfig basicAuth = config.getBasicAuth(); if (basicAuth.isEnabled()) { proxyRequest.header(HttpHeader.AUTHORIZATION, - "Basic " + Base64.getEncoder().encodeToString((basicAuth.getUserName() + ":" + basicAuth.getUserPass()).getBytes())); + "Basic " + Base64.getEncoder().encodeToString((basicAuth.getUserName() + ":" + basicAuth.getUserPass()).getBytes())); } super.addProxyHeaders(clientRequest, proxyRequest); } @@ -127,7 +128,7 @@ public class FeProxyServlet extends SSLProxyServlet { } private String getModifiedUrl(Configuration config, PluginsConfiguration pluginConf, String uri, String queryString) - throws MalformedURLException { + throws MalformedURLException { if (config == null) { log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "FeProxyServlet getModifiedUrl", "sdc-FE", "failed to retrieve configuration."); throw new RuntimeException("failed to read FE configuration"); @@ -153,8 +154,8 @@ public class FeProxyServlet extends SSLProxyServlet { } else if (uri.contains(WORKFLOW_CONTEXT)) { uri = uri.replace(SDC1_FE_PROXY + WORKFLOW_CONTEXT, WORKFLOW_CONTEXT); String workflowPluginURL = pluginConf.getPluginsList().stream() - .filter(plugin -> plugin.getPluginId().equalsIgnoreCase(PLUGIN_ID_WORKFLOW)).map(Plugin::getPluginDiscoveryUrl).findFirst() - .orElse(null); + .filter(plugin -> plugin.getPluginId().equalsIgnoreCase(PLUGIN_ID_WORKFLOW)).map(Plugin::getPluginDiscoveryUrl).findFirst() + .orElse(null); java.net.URL workflowURL = new URL(workflowPluginURL); protocol = workflowURL.getProtocol(); host = workflowURL.getHost(); @@ -192,7 +193,7 @@ public class FeProxyServlet extends SSLProxyServlet { private PluginsConfiguration getPluginConfiguration(HttpServletRequest request) { return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getPluginsConfiguration(); + .getPluginsConfiguration(); } private boolean isMsToggleOn(Configuration config) { @@ -224,7 +225,7 @@ public class FeProxyServlet extends SSLProxyServlet { String facadeSuffix = String.format("%s%s", FACADE_PATH_IDENTIFIER, CATALOG_REQUEST_IDENTIFIER); String nonFacadeUrl = currentURI.replace(facadeSuffix, "rest/v1/screen"); redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, - "excludeTypes=VFCMT&excludeTypes=Configuration"); + "excludeTypes=VFCMT&excludeTypes=Configuration"); } // Home else if (currentURI.endsWith(HOME_REQUEST_IDENTIFIER)) { @@ -249,10 +250,10 @@ public class FeProxyServlet extends SSLProxyServlet { String facadeSuffix = String.format("%s%s", FACADE_PATH_IDENTIFIER, CATALOG_REQUEST_IDENTIFIER); String nonFacadeUrl = currentURI.replace(facadeSuffix, "rest/v1/screen"); redirectValue = getModifiedUrl(config, getPluginConfiguration(request), nonFacadeUrl, - "excludeTypes=VFCMT&excludeTypes=Configuration"); + "excludeTypes=VFCMT&excludeTypes=Configuration"); } else { String message = String - .format("facade is toggled off, Could not rediret url %s with query params %s", currentURI, getQueryString(request)); + .format("facade is toggled off, Could not rediret url %s with query params %s", currentURI, getQueryString(request)); log.error(message); throw new NotImplementedException(message); } @@ -265,7 +266,7 @@ public class FeProxyServlet extends SSLProxyServlet { if (StringUtils.isEmpty(msUrl)) { // do that only once msUrl = String.format(MS_URL, config.getCatalogFacadeMs().getProtocol(), config.getCatalogFacadeMs().getHost(), - config.getCatalogFacadeMs().getPort()); + config.getCatalogFacadeMs().getPort()); } StringBuilder url; String queryString; @@ -293,7 +294,7 @@ public class FeProxyServlet extends SSLProxyServlet { private Configuration getConfiguration(HttpServletRequest request) { return ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); + .getConfiguration(); } private String getAuthority(String host, String port) { diff --git a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java index 891bc4ae34..812be7f8ea 100644 --- a/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java +++ b/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/SSLProxyServlet.java @@ -19,10 +19,12 @@ */ package org.openecomp.sdc.fe.servlets; -import javax.servlet.ServletException; import org.eclipse.jetty.client.HttpClient; +import org.eclipse.jetty.client.dynamic.HttpClientTransportDynamic; +import org.eclipse.jetty.io.ClientConnector; import org.eclipse.jetty.proxy.ProxyServlet; import org.eclipse.jetty.util.ssl.SslContextFactory; +import org.onap.config.api.JettySSLUtils; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.fe.config.Configuration; import org.openecomp.sdc.fe.config.ConfigurationManager; @@ -30,15 +32,17 @@ import org.openecomp.sdc.fe.utils.BeProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.servlet.ServletException; + public abstract class SSLProxyServlet extends ProxyServlet { private static final long serialVersionUID = 1L; - private static final Logger log = LoggerFactory.getLogger(SSLProxyServlet.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SSLProxyServlet.class); @Override protected HttpClient createHttpClient() throws ServletException { Configuration config = ((ConfigurationManager) getServletConfig().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)) - .getConfiguration(); + .getConfiguration(); boolean isSecureClient = !config.getBeProtocol().equals(BeProtocol.HTTP.getProtocolName()); HttpClient client = (isSecureClient) ? getSecureHttpClient() : super.createHttpClient(); int requestTimeout = config.getRequestTimeout() * 1000; @@ -47,22 +51,30 @@ public abstract class SSLProxyServlet extends ProxyServlet { } setTimeout(requestTimeout); client.setIdleTimeout(requestTimeout); - client.setStopTimeout(requestTimeout); return client; } private HttpClient getSecureHttpClient() throws ServletException { - // Instantiate HttpClient with the SslContextFactory - final var httpClient = new HttpClient(new SslContextFactory.Client(true)); + final SslContextFactory.Client sslContextFactory = new SslContextFactory.Client(true); + try { + sslContextFactory.setSslContext(JettySSLUtils.getSslContext()); + } catch (Exception e) { + LOGGER.error("Exception thrown while getting SslContext", e); + throw new ServletException(e); + } + final ClientConnector clientConnector = new ClientConnector(); + clientConnector.setSslContextFactory(sslContextFactory); + final HttpClient httpClient = new HttpClient(new HttpClientTransportDynamic(clientConnector)); // Configure HttpClient, for example: httpClient.setFollowRedirects(false); // Start HttpClient try { httpClient.start(); } catch (Exception x) { - log.error("Exception thrown while starting httpClient", x); + LOGGER.error("Exception thrown while starting httpClient", x); throw new ServletException(x); } return httpClient; } + } diff --git a/catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/FeProxyServletTest.java b/catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/FeProxyServletTest.java index 36f218a391..ef31b49669 100644 --- a/catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/FeProxyServletTest.java +++ b/catalog-fe/src/test/java/org/openecomp/sdc/fe/servlets/FeProxyServletTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -22,9 +22,9 @@ package org.openecomp.sdc.fe.servlets; import org.eclipse.jetty.client.api.Request; import org.eclipse.jetty.http.HttpFields; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.fe.config.Configuration; @@ -41,241 +41,248 @@ import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; public class FeProxyServletTest { - /* - * Example Url Mappings: - * http://localhost:8080/sdc1/feProxy/rest/services/MichaelTest2/0.0.1/csar - * --> http://localhost:8090/sdc2/rest/services/MichaelTest2/0.0.1/csar - * http://localhost:8080/sdc1/feProxy/dummy/not/working --> - * http://localhost:8090/sdc2/dummy/not/working - */ - FeProxyServletForTest feProxy = new FeProxyServletForTest(); - final static HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); - final static HttpSession httpSession = Mockito.mock(HttpSession.class); - final static ServletContext servletContext = Mockito.mock(ServletContext.class); - final static ConfigurationManager configurationManager = Mockito.mock(ConfigurationManager.class); - final static Configuration configuration = Mockito.mock(Configuration.class); - final static Configuration.OnboardingConfig onboardingConfiguration = Mockito.mock(Configuration.OnboardingConfig.class); - private final static Configuration.CatalogFacadeMsConfig catalogFacadeMsConfig = Mockito.mock(Configuration.CatalogFacadeMsConfig.class); - final static Request proxyRequest = Mockito.spy(Request.class); - final static HttpFields httpFields = Mockito.mock(HttpFields.class); - private static final PluginsConfiguration pluginsConfiguration = Mockito.mock(PluginsConfiguration.class); - private static final PluginsConfiguration.Plugin plugin = Mockito.mock(PluginsConfiguration.Plugin.class); - - final static String BE_PROTOCOL = "http"; - final static String BE_HOST = "172.20.43.124"; - final static int BE_PORT = 8090; - final static String ONBOARDING_BE_PROTOCOL = "http"; - final static String ONBOARDING_BE_HOST = "172.20.43.125"; - final static int ONBOARDING_BE_PORT = 8091; - final static String WF_PROTOCOL = "http"; - final static String WF_HOST = "172.20.43.126"; - final static int WF_PORT = 8092; - final static String HEADER_1 = "Header1"; - final static String HEADER_2 = "Header2"; - final static String HEADER_3 = "Header3"; - final static String HEADER_1_VAL = "Header1_Val"; - final static String HEADER_2_VAL = "Header2_Val"; - final static String HEADER_3_VAL = "Header3_Val"; - final static String REQUEST_ID_VAL = "4867495a-5ed7-49e4-8be2-cc8d66fdd52b"; - private final static String msProtocol = "http"; - private final static String msHealth = "/healthCheck"; - private final static String msHost = "localhost"; - private final static Integer msPort = 8080; - private final static String msPath = "/uicache"; - private final static String msUrl = String.format("%s://%s:%s", msProtocol, msHost, msPort); - - @BeforeClass - public static void beforeClass() { - when(servletRequest.getSession()).thenReturn(httpSession); - when(httpSession.getServletContext()).thenReturn(servletContext); - when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); - when(configurationManager.getConfiguration()).thenReturn(configuration); - when(configuration.getBeProtocol()).thenReturn(BE_PROTOCOL); - when(configuration.getBeHost()).thenReturn(BE_HOST); - when(configuration.getBeHttpPort()).thenReturn(BE_PORT); - when(configuration.getOnboarding()).thenReturn(onboardingConfiguration); - when(configuration.getOnboarding().getProtocolBe()).thenReturn(ONBOARDING_BE_PROTOCOL); - when(configuration.getOnboarding().getHostBe()).thenReturn(ONBOARDING_BE_HOST); - when(configuration.getOnboarding().getPortBe()).thenReturn(ONBOARDING_BE_PORT); - - List strList = new ArrayList<>(); - strList.add(HEADER_1); - strList.add(HEADER_2); - strList.add(HEADER_3); - - when(servletRequest.getHeaderNames()).thenReturn(Collections.enumeration(strList)); - when(servletRequest.getHeader(HEADER_1)).thenReturn(HEADER_1_VAL); - when(servletRequest.getHeader(HEADER_2)).thenReturn(HEADER_2_VAL); - when(servletRequest.getHeader(HEADER_3)).thenReturn(HEADER_3_VAL); - when(servletRequest.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(REQUEST_ID_VAL); - - when(proxyRequest.getHeaders()).thenReturn(httpFields); - when(httpFields.containsKey(HEADER_1)).thenReturn(true); - when(httpFields.containsKey(HEADER_2)).thenReturn(true); - when(httpFields.containsKey(HEADER_3)).thenReturn(false); - - List pluginList = new ArrayList(); - when(plugin.getPluginId()).thenReturn("WORKFLOW"); - when(plugin.getPluginSourceUrl()).thenReturn(WF_PROTOCOL + "://" + WF_HOST + ":" + WF_PORT); - when(plugin.getPluginDiscoveryUrl()).thenReturn(WF_PROTOCOL + "://" + WF_HOST + ":" + WF_PORT); - pluginList.add(plugin); - when(configurationManager.getPluginsConfiguration()).thenReturn(pluginsConfiguration); - when(pluginsConfiguration.getPluginsList()).thenReturn(pluginList); - - } - - @Before - public void setUp() { - when(configuration.getCatalogFacadeMs()).thenReturn(catalogFacadeMsConfig); - when(servletRequest.getQueryString()).thenReturn(null); - when(catalogFacadeMsConfig.getPath()).thenReturn(null); - } - @Test - public void testRewriteURI_APIRequest() { - when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/rest/dummyBeAPI"); - String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/rest/dummyBeAPI"; - String expectedChangedUrl = BE_PROTOCOL + "://" + BE_HOST + ":" + BE_PORT + "/sdc2/rest/dummyBeAPI"; - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); - - when(servletRequest.getContextPath()).thenReturn("/sdc1"); - when(servletRequest.getServletPath()).thenReturn("/feProxy/rest/dummyBeAPI"); - - String rewriteURI = feProxy.rewriteTarget(servletRequest); - - assertTrue(rewriteURI.equals(expectedChangedUrl)); - } - - @Test - public void testRewriteURIWithOnboardingAPIRequest() { - when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/onboarding-api/gg%20g?subtype=VF"); - String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/onboarding-api/gg%20g?subtype=VF"; - String expectedChangedUrl = ONBOARDING_BE_PROTOCOL + "://" + ONBOARDING_BE_HOST + ":" + ONBOARDING_BE_PORT + "/onboarding-api/gg%20g?subtype=VF"; - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); - - when(servletRequest.getContextPath()).thenReturn("/sdc1"); - when(servletRequest.getServletPath()).thenReturn("/feProxy/onboarding-api/gg%20g?subtype=VF"); - - String rewriteURI = feProxy.rewriteTarget(servletRequest); - - assertTrue(rewriteURI.equals(expectedChangedUrl)); - } - - - @Test - public void testRewriteURIWithQureyParam_APIRequest() { - when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/dcae-api/gg%20g?subtype=VF"); - String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/dcae-api/gg%20g?subtype=VF"; - String expectedChangedUrl = BE_PROTOCOL + "://" + BE_HOST + ":" + BE_PORT + "/dcae-api/gg%20g?subtype=VF"; - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); - - when(servletRequest.getContextPath()).thenReturn("/sdc1"); - when(servletRequest.getServletPath()).thenReturn("/feProxy/dcae-api/gg%20g?subtype=VF"); - - String rewriteURI = feProxy.rewriteTarget(servletRequest); - - assertTrue(rewriteURI.equals(expectedChangedUrl)); - } - - @Test - public void testRewriteTargetWithRedeirectAPIRequest() { - when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/rest/gg%20g?subtype=VF"); - String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/rest/gg%20g?subtype=VF"; - String expectedChangedUrl = BE_PROTOCOL + "://" + BE_HOST + ":" + BE_PORT + "/sdc2/rest/gg%20g?subtype=VF"; - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); - - when(servletRequest.getContextPath()).thenReturn("/sdc1"); - when(servletRequest.getServletPath()).thenReturn("/feProxy/rest/gg%20g?subtype=VF"); - - String rewriteURI = feProxy.rewriteTarget(servletRequest); - - assertTrue(rewriteURI.equals(expectedChangedUrl)); - } - - - - @Test - public void testRewriteURIWithWFAPIRequest() { - when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/wf/workflows"); - String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/wf/workflows"; - String expectedChangedUrl = WF_PROTOCOL + "://" + WF_HOST + ":" + WF_PORT + "/wf/workflows"; - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); - - when(servletRequest.getContextPath()).thenReturn("/sdc1"); - when(servletRequest.getServletPath()).thenReturn("/feProxy/wf/workflows"); - - String rewriteURI = feProxy.rewriteTarget(servletRequest); - - assertEquals(expectedChangedUrl, rewriteURI); - } - - @Test - public void testRedirectToMSWhenMsUrlExists() throws MalformedURLException { - final String urlParams = "x=1&y=2&z=3"; - final String url = "http//test.com:8080/uicache/v1/catalog"; - setUpConfigMocks(); - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); - when(servletRequest.getQueryString()).thenReturn(urlParams); - assertTrue(feProxy.isMsRequest(url + urlParams)); - assertEquals(msUrl + "/uicache/v1/catalog?" + urlParams, - feProxy.redirectMsRequestToMservice(servletRequest, configuration)); - } - - @Test - public void testRedirectToMSWhenMsUrlExistsWithoutParams() throws MalformedURLException { - final String uri = "/uicache/v1/home"; - final String url = String.format("http//test.com:8080%s", uri); - setUpConfigMocks(); - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); - when(servletRequest.getRequestURI()).thenReturn(uri); - assertTrue(feProxy.isMsRequest(url)); - assertEquals(msUrl + "/uicache/v1/home", feProxy.redirectMsRequestToMservice(servletRequest, configuration)); - } - @Test - public void testRedirectToBeOnToggleOff() throws MalformedURLException { - final String uri = "/uicache/v1/catalog"; - final String url = String.format("http//test.com:8080%s", uri); - when(catalogFacadeMsConfig.getPath()).thenReturn(null); - - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); - when(servletRequest.getRequestURI()).thenReturn(uri); - assertTrue(feProxy.isMsRequest(url)); - String expectedUrl = String.format("%s://%s:%s/rest/v1/screen?excludeTypes=VFCMT&excludeTypes=Configuration", - BE_PROTOCOL, BE_HOST, BE_PORT); - assertEquals(expectedUrl, feProxy.redirectMsRequestToMservice(servletRequest, configuration)); - } - @Test(expected = StringIndexOutOfBoundsException.class) - public void testRedirectToMSWhenMsUrlExistsButItIsNotCatalogRequest() throws MalformedURLException { - final String url = "http//test.com:8080/rest/v1/sc"; - final String urlParams = "x=1&y=2&z=3"; - setUpConfigMocks(); - when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); - when(servletRequest.getQueryString()).thenReturn(urlParams); - assertFalse(feProxy.isMsRequest(url)); - feProxy.redirectMsRequestToMservice(servletRequest, configuration); - } - - private void setUpConfigMocks() { - when(catalogFacadeMsConfig.getPath()).thenReturn(msPath); - when(catalogFacadeMsConfig.getProtocol()).thenReturn(msProtocol); - when(catalogFacadeMsConfig.getHost()).thenReturn(msHost); - when(catalogFacadeMsConfig.getPort()).thenReturn(msPort); - when(catalogFacadeMsConfig.getHealthCheckUri()).thenReturn(msHealth); - } - - /* class for testing only exposes the protected method.*/ - public static class FeProxyServletForTest extends FeProxyServlet{ - private static final long serialVersionUID = 1L; - @Override - public String rewriteTarget(HttpServletRequest request) { - return super.rewriteTarget(request); - } - @Override - boolean isMsRequest(String currentUrl) { - return super.isMsRequest(currentUrl); - } - } + /* + * Example Url Mappings: + * http://localhost:8080/sdc1/feProxy/rest/services/MichaelTest2/0.0.1/csar + * --> http://localhost:8090/sdc2/rest/services/MichaelTest2/0.0.1/csar + * http://localhost:8080/sdc1/feProxy/dummy/not/working --> + * http://localhost:8090/sdc2/dummy/not/working + */ + private final FeProxyServletForTest feProxy = new FeProxyServletForTest(); + private static final HttpServletRequest servletRequest = Mockito.mock(HttpServletRequest.class); + private static final HttpSession httpSession = Mockito.mock(HttpSession.class); + private static final ServletContext servletContext = Mockito.mock(ServletContext.class); + private static final ConfigurationManager configurationManager = Mockito.mock(ConfigurationManager.class); + private static final Configuration configuration = Mockito.mock(Configuration.class); + private static final Configuration.OnboardingConfig onboardingConfiguration = Mockito.mock(Configuration.OnboardingConfig.class); + private static final Configuration.CatalogFacadeMsConfig catalogFacadeMsConfig = Mockito.mock(Configuration.CatalogFacadeMsConfig.class); + private static final Request proxyRequest = Mockito.spy(Request.class); + private static final HttpFields httpFields = Mockito.mock(HttpFields.class); + private static final PluginsConfiguration pluginsConfiguration = Mockito.mock(PluginsConfiguration.class); + private static final PluginsConfiguration.Plugin plugin = Mockito.mock(PluginsConfiguration.Plugin.class); + + private static final boolean sslEnabled = false; + private static final String BE_PROTOCOL = "http"; + private static final String BE_PROTOCOL_SSL = "https"; + private static final String BE_HOST = "172.20.43.124"; + private static final int BE_PORT = 8090; + private static final int BE_PORT_SSL = 9443; + private static final String ONBOARDING_BE_PROTOCOL = "http"; + private static final String ONBOARDING_BE_HOST = "172.20.43.125"; + private static final int ONBOARDING_BE_PORT = 8091; + private static final String WF_PROTOCOL = "http"; + private static final String WF_HOST = "172.20.43.126"; + private static final int WF_PORT = 8092; + private static final String HEADER_1 = "Header1"; + private static final String HEADER_2 = "Header2"; + private static final String HEADER_3 = "Header3"; + private static final String HEADER_1_VAL = "Header1_Val"; + private static final String HEADER_2_VAL = "Header2_Val"; + private static final String HEADER_3_VAL = "Header3_Val"; + private static final String REQUEST_ID_VAL = "4867495a-5ed7-49e4-8be2-cc8d66fdd52b"; + private static final String msProtocol = "http"; + private static final String msHealth = "/healthCheck"; + private static final String msHost = "localhost"; + private static final Integer msPort = 8080; + private static final String msPath = "/uicache"; + private static final String msUrl = String.format("%s://%s:%s", msProtocol, msHost, msPort); + + @BeforeAll + public static void beforeClass() { + when(servletRequest.getSession()).thenReturn(httpSession); + when(httpSession.getServletContext()).thenReturn(servletContext); + when(servletContext.getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).thenReturn(configurationManager); + when(configurationManager.getConfiguration()).thenReturn(configuration); + when(configuration.getBeProtocol()).thenReturn(sslEnabled ? BE_PROTOCOL_SSL : BE_PROTOCOL); + when(configuration.getBeHost()).thenReturn(BE_HOST); + when(configuration.getBeHttpPort()).thenReturn(BE_PORT); + when(configuration.getBeSslPort()).thenReturn(BE_PORT_SSL); + when(configuration.getOnboarding()).thenReturn(onboardingConfiguration); + when(configuration.getOnboarding().getProtocolBe()).thenReturn(ONBOARDING_BE_PROTOCOL); + when(configuration.getOnboarding().getHostBe()).thenReturn(ONBOARDING_BE_HOST); + when(configuration.getOnboarding().getPortBe()).thenReturn(ONBOARDING_BE_PORT); + + List strList = new ArrayList<>(); + strList.add(HEADER_1); + strList.add(HEADER_2); + strList.add(HEADER_3); + + when(servletRequest.getHeaderNames()).thenReturn(Collections.enumeration(strList)); + when(servletRequest.getHeader(HEADER_1)).thenReturn(HEADER_1_VAL); + when(servletRequest.getHeader(HEADER_2)).thenReturn(HEADER_2_VAL); + when(servletRequest.getHeader(HEADER_3)).thenReturn(HEADER_3_VAL); + when(servletRequest.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER)).thenReturn(REQUEST_ID_VAL); + + when(proxyRequest.getHeaders()).thenReturn(httpFields); + when(httpFields.contains(HEADER_1)).thenReturn(true); + when(httpFields.contains(HEADER_2)).thenReturn(true); + when(httpFields.contains(HEADER_3)).thenReturn(false); + + List pluginList = new ArrayList(); + when(plugin.getPluginId()).thenReturn("WORKFLOW"); + when(plugin.getPluginSourceUrl()).thenReturn(WF_PROTOCOL + "://" + WF_HOST + ":" + WF_PORT); + when(plugin.getPluginDiscoveryUrl()).thenReturn(WF_PROTOCOL + "://" + WF_HOST + ":" + WF_PORT); + pluginList.add(plugin); + when(configurationManager.getPluginsConfiguration()).thenReturn(pluginsConfiguration); + when(pluginsConfiguration.getPluginsList()).thenReturn(pluginList); + + } + + @BeforeEach + public void setUp() { + when(configuration.getCatalogFacadeMs()).thenReturn(catalogFacadeMsConfig); + when(servletRequest.getQueryString()).thenReturn(null); + when(catalogFacadeMsConfig.getPath()).thenReturn(null); + } + + @Test + void testRewriteURI_APIRequest() { + when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/rest/dummyBeAPI"); + String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/rest/dummyBeAPI"; + String expectedChangedUrl = (sslEnabled ? BE_PROTOCOL_SSL : BE_PROTOCOL) + "://" + BE_HOST + ":" + (sslEnabled ? BE_PORT_SSL : BE_PORT) + "/sdc2/rest/dummyBeAPI"; + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); + + when(servletRequest.getContextPath()).thenReturn("/sdc1"); + when(servletRequest.getServletPath()).thenReturn("/feProxy/rest/dummyBeAPI"); + + String rewriteURI = feProxy.rewriteTarget(servletRequest); + + assertEquals(expectedChangedUrl, rewriteURI); + } + + @Test + void testRewriteURIWithOnboardingAPIRequest() { + when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/onboarding-api/gg%20g?subtype=VF"); + String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/onboarding-api/gg%20g?subtype=VF"; + String expectedChangedUrl = ONBOARDING_BE_PROTOCOL + "://" + ONBOARDING_BE_HOST + ":" + ONBOARDING_BE_PORT + "/onboarding-api/gg%20g?subtype=VF"; + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); + + when(servletRequest.getContextPath()).thenReturn("/sdc1"); + when(servletRequest.getServletPath()).thenReturn("/feProxy/onboarding-api/gg%20g?subtype=VF"); + + String rewriteURI = feProxy.rewriteTarget(servletRequest); + + assertEquals(expectedChangedUrl, rewriteURI); + } + + @Test + void testRewriteURIWithQureyParam_APIRequest() { + when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/dcae-api/gg%20g?subtype=VF"); + String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/dcae-api/gg%20g?subtype=VF"; + String expectedChangedUrl = (sslEnabled ? BE_PROTOCOL_SSL : BE_PROTOCOL) + "://" + BE_HOST + ":" + (sslEnabled ? BE_PORT_SSL : BE_PORT) + "/dcae-api/gg%20g?subtype=VF"; + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); + + when(servletRequest.getContextPath()).thenReturn("/sdc1"); + when(servletRequest.getServletPath()).thenReturn("/feProxy/dcae-api/gg%20g?subtype=VF"); + + String rewriteURI = feProxy.rewriteTarget(servletRequest); + + assertEquals(expectedChangedUrl, rewriteURI); + } + + @Test + void testRewriteTargetWithRedeirectAPIRequest() { + when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/rest/gg%20g?subtype=VF"); + String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/rest/gg%20g?subtype=VF"; + String expectedChangedUrl = (sslEnabled ? BE_PROTOCOL_SSL : BE_PROTOCOL) + "://" + BE_HOST + ":" + (sslEnabled ? BE_PORT_SSL : BE_PORT) + "/sdc2/rest/gg%20g?subtype=VF"; + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); + + when(servletRequest.getContextPath()).thenReturn("/sdc1"); + when(servletRequest.getServletPath()).thenReturn("/feProxy/rest/gg%20g?subtype=VF"); + + String rewriteURI = feProxy.rewriteTarget(servletRequest); + + assertEquals(expectedChangedUrl, rewriteURI); + } + + @Test + void testRewriteURIWithWFAPIRequest() { + when(servletRequest.getRequestURI()).thenReturn("/sdc1/feProxy/wf/workflows"); + String requestResourceUrl = "http://localhost:8080/sdc1/feProxy/wf/workflows"; + String expectedChangedUrl = WF_PROTOCOL + "://" + WF_HOST + ":" + WF_PORT + "/wf/workflows"; + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(requestResourceUrl)); + + when(servletRequest.getContextPath()).thenReturn("/sdc1"); + when(servletRequest.getServletPath()).thenReturn("/feProxy/wf/workflows"); + + String rewriteURI = feProxy.rewriteTarget(servletRequest); + + assertEquals(expectedChangedUrl, rewriteURI); + } + + @Test + void testRedirectToMSWhenMsUrlExists() throws MalformedURLException { + final String urlParams = "x=1&y=2&z=3"; + final String url = "http//test.com:8080/uicache/v1/catalog"; + setUpConfigMocks(); + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); + when(servletRequest.getQueryString()).thenReturn(urlParams); + assertTrue(feProxy.isMsRequest(url + urlParams)); + assertEquals(msUrl + "/uicache/v1/catalog?" + urlParams, + feProxy.redirectMsRequestToMservice(servletRequest, configuration)); + } + + @Test + void testRedirectToMSWhenMsUrlExistsWithoutParams() throws MalformedURLException { + final String uri = "/uicache/v1/home"; + final String url = String.format("http//test.com:8080%s", uri); + setUpConfigMocks(); + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); + when(servletRequest.getRequestURI()).thenReturn(uri); + assertTrue(feProxy.isMsRequest(url)); + assertEquals(msUrl + "/uicache/v1/home", feProxy.redirectMsRequestToMservice(servletRequest, configuration)); + } + + @Test + void testRedirectToBeOnToggleOff() throws MalformedURLException { + final String uri = "/uicache/v1/catalog"; + final String url = String.format("http//test.com:8080%s", uri); + when(catalogFacadeMsConfig.getPath()).thenReturn(null); + + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); + when(servletRequest.getRequestURI()).thenReturn(uri); + assertTrue(feProxy.isMsRequest(url)); + String expectedUrl = String.format("%s://%s:%s/rest/v1/screen?excludeTypes=VFCMT&excludeTypes=Configuration", + (sslEnabled ? BE_PROTOCOL_SSL : BE_PROTOCOL), BE_HOST, (sslEnabled ? BE_PORT_SSL : BE_PORT)); + assertEquals(expectedUrl, feProxy.redirectMsRequestToMservice(servletRequest, configuration)); + } + + @Test + void testRedirectToMSWhenMsUrlExistsButItIsNotCatalogRequest() throws MalformedURLException { + final String url = "http//test.com:8080/rest/v1/sc"; + final String urlParams = "x=1&y=2&z=3"; + setUpConfigMocks(); + when(servletRequest.getRequestURL()).thenReturn(new StringBuffer(url)); + when(servletRequest.getQueryString()).thenReturn(urlParams); + assertFalse(feProxy.isMsRequest(url)); + assertThrows(StringIndexOutOfBoundsException.class, () -> feProxy.redirectMsRequestToMservice(servletRequest, configuration)); + } + + private void setUpConfigMocks() { + when(catalogFacadeMsConfig.getPath()).thenReturn(msPath); + when(catalogFacadeMsConfig.getProtocol()).thenReturn(msProtocol); + when(catalogFacadeMsConfig.getHost()).thenReturn(msHost); + when(catalogFacadeMsConfig.getPort()).thenReturn(msPort); + when(catalogFacadeMsConfig.getHealthCheckUri()).thenReturn(msHealth); + } + + /* class for testing only exposes the protected method.*/ + public static class FeProxyServletForTest extends FeProxyServlet { + private static final long serialVersionUID = 1L; + + @Override + public String rewriteTarget(HttpServletRequest request) { + return super.rewriteTarget(request); + } + + @Override + boolean isMsRequest(String currentUrl) { + return super.isMsRequest(currentUrl); + } + } } diff --git a/common-app-api/pom.xml b/common-app-api/pom.xml index dc9b5fb256..6f1ec78165 100644 --- a/common-app-api/pom.xml +++ b/common-app-api/pom.xml @@ -394,6 +394,12 @@ + + org.onap.sdc.common + onap-configuration-management-api + ${project.version} + compile + diff --git a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java index 7241decd62..03cbc5952a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/be/config/ConfigurationManager.java @@ -20,8 +20,6 @@ package org.openecomp.sdc.be.config; import com.google.common.annotations.VisibleForTesting; -import java.util.HashMap; -import java.util.Map; import org.openecomp.sdc.be.config.validation.ArtifactConfigValidator; import org.openecomp.sdc.common.api.ArtifactTypeEnum; import org.openecomp.sdc.common.api.BasicConfiguration; @@ -31,11 +29,14 @@ import org.openecomp.sdc.common.api.FileChangeCallback; import org.openecomp.sdc.common.config.EcompErrorConfiguration; import org.openecomp.sdc.common.config.IEcompConfigurationManager; +import java.util.HashMap; +import java.util.Map; + public class ConfigurationManager implements FileChangeCallback, IEcompConfigurationManager { private static ConfigurationManager instance; final Map configurations = new HashMap<>(); - ConfigurationSource configurationSource = null; + private ConfigurationSource configurationSource; @VisibleForTesting public ConfigurationManager() { @@ -67,7 +68,7 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura final Object configurationObj = configurations.get(getKey(Configuration.class)); if (configurationObj instanceof Configuration) { final ArtifactConfigValidator artifactConfigValidator = new ArtifactConfigValidator((Configuration) configurationObj, - ArtifactTypeEnum.getBaseArtifacts()); + ArtifactTypeEnum.getBaseArtifacts()); artifactConfigValidator.validate(); } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java index d45deb328b..599c43ac67 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpClientFactory.java @@ -23,15 +23,17 @@ import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.UserTokenHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; +import org.onap.config.api.JettySSLUtils; import org.openecomp.sdc.common.api.Constants; import org.openecomp.sdc.common.http.config.ClientCertificate; -import org.openecomp.sdc.common.log.wrappers.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class HttpClientFactory { - private static final Logger logger = Logger.getLogger(HttpClientFactory.class.getName()); + private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientFactory.class); private static final UserTokenHandler userTokenHandler = context -> null; private final HttpConnectionMngFactory connectionMngFactory; @@ -40,13 +42,25 @@ public class HttpClientFactory { } HttpClient createClient(String protocol, HttpClientConfigImmutable config) { - logger.debug("Create {} client based on {}", protocol, config); - ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; - HttpClientConnectionManager connectionManager = connectionMngFactory.getOrCreate(clientCertificate); - RequestConfig requestConfig = createClientTimeoutConfiguration(config); - CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(connectionManager) - .setUserTokenHandler(userTokenHandler).setRetryHandler(resolveRetryHandler(config)).build(); - return new HttpClient(client, config); + LOGGER.debug("Create {} client based on {}", protocol, config); + final ClientCertificate clientCertificate = Constants.HTTPS.equals(protocol) ? config.getClientCertificate() : null; + final HttpClientConnectionManager connectionManager = connectionMngFactory.getOrCreate(clientCertificate); + final RequestConfig requestConfig = createClientTimeoutConfiguration(config); + + try { + final HttpClientBuilder httpClientBuilder = HttpClients.custom() + .setDefaultRequestConfig(requestConfig) + .setConnectionManager(connectionManager) + .setUserTokenHandler(userTokenHandler) + .setRetryHandler(resolveRetryHandler(config)); + if (clientCertificate != null) { + httpClientBuilder.setSSLContext(JettySSLUtils.getSslContext()); + } + return new HttpClient(httpClientBuilder.build(), config); + } catch (Exception e) { + LOGGER.error("Failed to createClient", e); + throw new RuntimeException(e); + } } private HttpRequestRetryHandler resolveRetryHandler(HttpClientConfigImmutable config) { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java index 573c97f130..bd5990eed5 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/http/client/api/HttpResponse.java @@ -19,8 +19,12 @@ */ package org.openecomp.sdc.common.http.client.api; +import lombok.AllArgsConstructor; +import lombok.Getter; import org.apache.commons.lang3.StringUtils; +@Getter +@AllArgsConstructor public class HttpResponse { private final T response; @@ -28,39 +32,11 @@ public class HttpResponse { private final String description; public HttpResponse(T response, int statusCode) { - this.response = response; - this.statusCode = statusCode; - this.description = StringUtils.EMPTY; - } - - public HttpResponse(T response, int statusCode, String description) { - this.response = response; - this.statusCode = statusCode; - this.description = description; - } - - public T getResponse() { - return response; - } - - public int getStatusCode() { - return statusCode; - } - - public String getDescription() { - return description; + this(response, statusCode, StringUtils.EMPTY); } @Override public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("HttpResponse [response="); - builder.append(response); - builder.append(", statusCode="); - builder.append(statusCode); - builder.append(", description="); - builder.append(description); - builder.append("]"); - return builder.toString(); + return "HttpResponse [response=" + response + ", statusCode=" + statusCode + ", description=" + description + "]"; } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java index 70a94fd460..d85dab0db6 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/listener/AppContextListener.java @@ -39,6 +39,7 @@ public class AppContextListener implements ServletContextListener { private static Logger log = Logger.getLogger(AppContextListener.class.getName()); + @Override public void contextInitialized(ServletContextEvent context) { log.debug("ServletContextListener initialized "); log.debug("After read values from Manifest {}", getManifestInfo(context.getServletContext())); @@ -57,6 +58,7 @@ public class AppContextListener implements ServletContextListener { ExternalConfiguration.listenForChanges(); } + @Override public void contextDestroyed(ServletContextEvent context) { log.debug("ServletContextListener destroyed"); ExternalConfiguration.stopListenForFileChanges(); diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java deleted file mode 100644 index 82bf295762..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogRequestInterceptor.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.openecomp.sdc.common.log.interceptors; - -import java.io.IOException; -import java.net.URI; -import org.apache.http.HttpException; -import org.apache.http.HttpMessage; -import org.apache.http.HttpRequest; -import org.apache.http.HttpRequestInterceptor; -import org.apache.http.HttpResponse; -import org.apache.http.protocol.HttpContext; -import org.onap.logging.filter.base.AbstractMetricLogFilter; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; - -public class ApacheClientLogRequestInterceptor extends AbstractMetricLogFilter implements - HttpRequestInterceptor { - - private String previousInvocationId; - - @Override - protected void addHeader(HttpMessage httpMessage, String s, String s1) { - httpMessage.addHeader(s, s1); - } - - @Override - protected String getTargetServiceName(HttpRequest httpRequest) { - return httpRequest.getRequestLine().getUri(); - } - - @Override - protected String getServiceName(HttpRequest httpRequest) { - return URI.create(httpRequest.getRequestLine().getUri()).getPath(); - } - - @Override - protected int getHttpStatusCode(HttpResponse httpResponse) { - return httpResponse.getStatusLine().getStatusCode(); - } - - @Override - protected String getResponseCode(HttpResponse httpResponse) { - return String.valueOf(httpResponse.getStatusLine().getStatusCode()); - } - - @Override - protected String getTargetEntity(HttpRequest httpRequest) { - //fallback to default value that provided by AbstractMetricLogFilter - return null; - } - - @Override - protected void additionalPre(HttpRequest httpRequest, HttpMessage httpMessage) { - String outgoingInvocationId = httpMessage.getFirstHeader(ONAPLogConstants.Headers.INVOCATION_ID).getValue(); - LogFieldsMdcHandler.getInstance().setOutgoingInvocationId(outgoingInvocationId); - LogFieldsMdcHandler.getInstance().setKeyInvocationId(previousInvocationId); - } - - @Override - public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { - previousInvocationId = LogFieldsMdcHandler.getInstance().getKeyInvocationId(); - super.pre(httpRequest, httpRequest); - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java b/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java deleted file mode 100644 index 26c7c2540b..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/log/interceptors/ApacheClientLogResponseInterceptor.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.openecomp.sdc.common.log.interceptors; - -import java.io.IOException; -import java.net.URI; -import org.apache.http.HttpException; -import org.apache.http.HttpMessage; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.HttpResponseInterceptor; -import org.apache.http.protocol.HttpContext; -import org.onap.logging.filter.base.AbstractMetricLogFilter; - -public class ApacheClientLogResponseInterceptor extends AbstractMetricLogFilter implements - HttpResponseInterceptor { - - @Override - protected void addHeader(HttpMessage httpMessage, String s, String s1) { - httpMessage.addHeader(s, s1); - } - - @Override - protected String getTargetServiceName(HttpRequest httpRequest) { - return httpRequest.getRequestLine().getUri(); - } - - @Override - protected String getServiceName(HttpRequest httpRequest) { - return URI.create(httpRequest.getRequestLine().getUri()).getPath(); - } - - @Override - protected int getHttpStatusCode(HttpResponse httpResponse) { - return httpResponse.getStatusLine().getStatusCode(); - } - - @Override - protected String getResponseCode(HttpResponse httpResponse) { - return String.valueOf(httpResponse.getStatusLine().getStatusCode()); - } - - @Override - protected String getTargetEntity(HttpRequest httpRequest) { - //fallback to default value that provided by AbstractMetricLogFilter - return null; - } - - @Override - public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { - super.post(null, httpResponse); - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java deleted file mode 100644 index 37769fbaef..0000000000 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java +++ /dev/null @@ -1,132 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ -package org.openecomp.sdc.common.util; - -import java.util.ArrayList; -import java.util.List; -import java.util.Spliterator; -import java.util.Spliterators.AbstractSpliterator; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - -/** - * Utility Class For Actions On Streams - * - * @author mshitrit - */ -public final class StreamUtils { - - private StreamUtils() { - throw new UnsupportedOperationException(); - } - - /** - * Breaks the stream when the predicate is not met.
Does not evaluate elements after the stream breaks.
This method evaluates the - * stream.
- * - * @param stream - * @param predicate - * @return - */ - public static Stream takeWhilePlusOneNoEval(Stream stream, Predicate predicate) { - List results = new ArrayList<>(); - Consumer listAdder = results::add; - stream.map(e -> { - listAdder.accept(e); - return e; - }).filter(e -> !predicate.test(e)).findFirst(); - return results.stream(); - } - - public static Stream takeWhile(Stream stream, Predicate predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false); - } - - public static Stream takeWhilePlusOne(Stream stream, Predicate predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), new StopAfterFailPredicate<>(predicate)), false); - } - - private static Spliterator takeWhile(Spliterator splitr, Predicate predicate) { - return new MySplitIterator<>(splitr, predicate); - } - - public static class MySplitIterator extends AbstractSpliterator implements Spliterator { - - boolean stillGoing = true; - private Spliterator innerItr; - private Predicate innerPred; - - private MySplitIterator(Spliterator splitItr, Predicate pred) { - super(splitItr.estimateSize(), 0); - innerItr = splitItr; - innerPred = pred; - } - - @Override - public boolean tryAdvance(Consumer action) { - boolean canAdvance = true; - if (stillGoing) { - stillGoing = innerItr.tryAdvance(createConsumerWrapper(action)); - } else { - canAdvance = false; - } - return canAdvance; - } - - private Consumer createConsumerWrapper(Consumer action) { - return new Consumer() { - @Override - public void accept(T t) { - stillGoing = innerPred.test(t); - if (stillGoing) { - action.accept(t); - } - } - }; - } - } - - public static class StopAfterFailPredicate implements Predicate { - - boolean hasNotFailed; - Predicate innerPredicate; - - private StopAfterFailPredicate(Predicate pred) { - hasNotFailed = true; - innerPredicate = pred; - } - - ; - - @Override - public boolean test(T t) { - boolean isPassed; - if (hasNotFailed) { - isPassed = true; - hasNotFailed = innerPredicate.test(t); - } else { - isPassed = false; - } - return isPassed; - } - } -} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java index 0d5cf62cb1..798bacf9a3 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/fe/config/ConfigurationManager.java @@ -34,8 +34,8 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura private static final Logger log = Logger.getLogger(ConfigurationManager.class.getName()); private static ConfigurationManager instance; - ConfigurationSource configurationSource = null; - Map configurations = new HashMap<>(); + private final ConfigurationSource configurationSource; + private final Map configurations = new HashMap<>(); public ConfigurationManager(ConfigurationSource configurationSource) { super(); @@ -101,6 +101,7 @@ public class ConfigurationManager implements FileChangeCallback, IEcompConfigura return (Configuration) configurations.get(getKey(Configuration.class)); } + @Override public void reconfigure(BasicConfiguration obj) { // diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java index 4958202811..feb49d0cc8 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpClientFactoryTest.java @@ -20,11 +20,11 @@ package org.openecomp.sdc.common.http.client.api; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import org.onap.sdc.security.SecurityUtil; import org.openecomp.sdc.common.http.config.BasicAuthorization; import org.openecomp.sdc.common.http.config.ClientCertificate; @@ -36,15 +36,15 @@ import java.util.Map; import static junit.framework.TestCase.assertNotNull; -@RunWith(MockitoJUnitRunner.class) -public class HttpClientFactoryTest { +@ExtendWith(MockitoExtension.class) +class HttpClientFactoryTest { @Mock - HttpConnectionMngFactory httpConnectionMngFactory; + private HttpConnectionMngFactory httpConnectionMngFactory; @Test - public void validateNewClientCreationReturnsValidClient() throws HttpExecuteException { - HttpClient httpClient = new HttpClientFactory(httpConnectionMngFactory).createClient("Http",prepareTestClientConfigImmutable()); + void validateNewClientCreationReturnsValidClient() { + final HttpClient httpClient = new HttpClientFactory(httpConnectionMngFactory).createClient("Http", prepareTestClientConfigImmutable()); assertNotNull(httpClient); httpClient.close(); } diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpResponseTest.java b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpResponseTest.java index d96f071e3c..85246a1b45 100644 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpResponseTest.java +++ b/common-app-api/src/test/java/org/openecomp/sdc/common/http/client/api/HttpResponseTest.java @@ -21,38 +21,38 @@ package org.openecomp.sdc.common.http.client.api; import org.apache.http.HttpStatus; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; -public class HttpResponseTest { +class HttpResponseTest { @Test - public void validateNoDescriptionConstructor() { + void validateNoDescriptionConstructor() { final String testResponse = "test response"; HttpResponse httpResponseTest = new HttpResponse<>(testResponse, HttpStatus.SC_OK); - assertEquals(httpResponseTest.getStatusCode(),HttpStatus.SC_OK); - assertEquals(httpResponseTest.getResponse(),testResponse); - assertEquals(httpResponseTest.getDescription(),""); + assertEquals(httpResponseTest.getStatusCode(), HttpStatus.SC_OK); + assertEquals(httpResponseTest.getResponse(), testResponse); + assertEquals(httpResponseTest.getDescription(), ""); } @Test - public void validateAllArgsConstructor() { + void validateAllArgsConstructor() { final String testResponse = "test response"; final String testDescription = "test description"; HttpResponse httpResponseTest = new HttpResponse<>(testResponse, HttpStatus.SC_OK, testDescription); - assertEquals(httpResponseTest.getStatusCode(),HttpStatus.SC_OK); - assertEquals(httpResponseTest.getResponse(),testResponse); - assertEquals(httpResponseTest.getDescription(),testDescription); + assertEquals(httpResponseTest.getStatusCode(), HttpStatus.SC_OK); + assertEquals(httpResponseTest.getResponse(), testResponse); + assertEquals(httpResponseTest.getDescription(), testDescription); } @Test - public void validateToStringConstructor() { + void validateToStringConstructor() { final String testResponse = "test response"; final String testDescription = "test description"; diff --git a/common-app-api/src/test/java/org/openecomp/sdc/common/util/StreamUtilsTests.java b/common-app-api/src/test/java/org/openecomp/sdc/common/util/StreamUtilsTests.java deleted file mode 100644 index 5ee8f42b6b..0000000000 --- a/common-app-api/src/test/java/org/openecomp/sdc/common/util/StreamUtilsTests.java +++ /dev/null @@ -1,142 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.common.util; - -import fj.data.Either; -import static org.junit.Assert.assertEquals; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.junit.Assert.assertTrue; - -public class StreamUtilsTests { - @Test - public void testTakeWhilePredicateNotMet() { - List> list = buildListWith10Integers(); - - assertEquals(10, StreamUtils.takeWhile(list.stream(), Either::isLeft).count()); - } - - @Test - public void testTakeWhilePredicateIsMet() { - List> list = buildListWith10Integers(); - addToBooleansToList(list); - - final Stream> takeWhileStream = StreamUtils.takeWhile(list.stream(), Either::isLeft); - assertEquals(0, takeWhileStream.filter(Either::isRight).count()); - } - - @Test - public void testTakeErrorEvalOnlyOnce() { - List bucket = new ArrayList<>(); - // API - Function> cons = num -> { - Either ret; - bucket.add(num); - if (num > 5) { - ret = Either.right(false); - } else { - ret = Either.left(num); - } - ; - return ret; - }; - - List num1to10 = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); - Stream> streamEithers = num1to10.stream().map(cons::apply); - List> collect = StreamUtils.takeWhilePlusOneNoEval(streamEithers, Either::isLeft) - .collect(Collectors.toList()); - assertTrue(bucket.size() <= 6); - assertTrue(collect.size() <= 6); - assertEquals(1, collect.stream().filter(Either::isRight).count()); - - } - - @Test - public void testTakeWhilePlusOnePredicateNotMet() { - List> list = buildListWith10Integers(); - - assertEquals(10, StreamUtils.takeWhilePlusOne(list.stream(), Either::isLeft).count()); - } - - @Test - public void testTakeWhilePlusOnePredicateIsMet() { - List> list = buildListWith10Integers(); - addToBooleansToList(list); - - final Stream> takeWhilePlusOneStream = StreamUtils.takeWhilePlusOne(list.stream(), - Either::isLeft); - assertEquals(1, takeWhilePlusOneStream.filter(Either::isRight).count()); - } - - private void addToBooleansToList(List> list) { - list.add(Either.right(false)); - list.add(Either.right(false)); - } - - private List> buildListWith10Integers() { - List> list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - list.add(Either.left(i)); - } - return list; - } - - @Test - public void myTest() { - List list = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - list.add(i); - } - - List> container = new ArrayList<>(); - list.stream().map(e -> myBusinessLogic(e, container)).filter(Either::isRight).findAny(); - // Actual Results are in container - assertEquals(6, container.size()); - - } - - private Either myBusinessLogic(int e, List> cobtainerList) { - Either eitherElement = similuteDBAccess(e); - // Keep The results in external List - cobtainerList.add(eitherElement); - - return eitherElement; - } - - private Either similuteDBAccess(int e) { - Either eitherElement; - if (e < 5) { - // DB Success - eitherElement = Either.left(e); - } else { - // DB Fail - eitherElement = Either.right(true); - } - return eitherElement; - } -} diff --git a/common/onap-common-configuration-management/onap-configuration-management-api/pom.xml b/common/onap-common-configuration-management/onap-configuration-management-api/pom.xml index 36bff43532..f8fc085b1f 100644 --- a/common/onap-common-configuration-management/onap-configuration-management-api/pom.xml +++ b/common/onap-common-configuration-management/onap-configuration-management-api/pom.xml @@ -24,6 +24,11 @@ + + org.projectlombok + lombok + ${lombok.version} + org.apache.httpcomponents diff --git a/common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/JettySSLUtils.java b/common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/JettySSLUtils.java index 44280cf105..ad3395f720 100644 --- a/common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/JettySSLUtils.java +++ b/common/onap-common-configuration-management/onap-configuration-management-api/src/main/java/org/onap/config/api/JettySSLUtils.java @@ -19,59 +19,61 @@ */ package org.onap.config.api; -import java.io.File; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.NoArgsConstructor; +import org.apache.http.conn.ssl.TrustSelfSignedStrategy; +import org.apache.http.ssl.SSLContexts; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.net.ssl.SSLContext; import java.io.FileInputStream; -import java.io.IOException; -import java.security.GeneralSecurityException; +import java.io.InputStream; import java.security.KeyStore; import java.util.Properties; -import javax.net.ssl.SSLContext; -import org.apache.http.conn.ssl.TrustSelfSignedStrategy; -import org.apache.http.ssl.SSLContexts; +@NoArgsConstructor(access = AccessLevel.PRIVATE) public class JettySSLUtils { + private static final Logger LOGGER = LoggerFactory.getLogger(JettySSLUtils.class); + private static final String JETTY_BASE = System.getenv("JETTY_BASE"); - private JettySSLUtils() { - } - - public static JettySslConfig getSSLConfig() throws IOException { - Properties sslProperties = new Properties(); - String sslPropsPath = System.getenv("JETTY_BASE") + File.separator + "/start.d/ssl.ini"; - File sslPropsFile = new File(sslPropsPath); - try (FileInputStream fis = new FileInputStream(sslPropsFile)) { + public static JettySslConfig getSSLConfig() { + final Properties sslProperties = new Properties(); + final String sslPropsPath = JETTY_BASE + "/start.d/ssl.ini"; + try (final InputStream fis = new FileInputStream(sslPropsPath)) { sslProperties.load(fis); + } catch (Exception e) { + LOGGER.error("Failed to read '{}'", sslPropsPath, e); } return new JettySslConfig(sslProperties); } - public static SSLContext getSslContext() throws GeneralSecurityException, IOException { - JettySslConfig sslProperties = JettySSLUtils.getSSLConfig(); - KeyStore trustStore = KeyStore.getInstance(sslProperties.getTruststoreType()); - try (FileInputStream instream = new FileInputStream(new File(sslProperties.getTruststorePath()));) { - trustStore.load(instream, (sslProperties.getTruststorePass()).toCharArray()); + public static SSLContext getSslContext() throws Exception { + final JettySslConfig sslProperties = getSSLConfig(); + final KeyStore trustStore = KeyStore.getInstance(sslProperties.getTruststoreType()); + try (final InputStream fis = new FileInputStream(sslProperties.getTruststorePath())) { + trustStore.load(fis, (sslProperties.getTruststorePass()).toCharArray()); } - KeyStore keystore = KeyStore.getInstance(sslProperties.getKeystoreType()); - try (FileInputStream instream = new FileInputStream(new File(sslProperties.getKeystorePath()));) { - keystore.load(instream, sslProperties.getKeystorePass().toCharArray()); + + final KeyStore keystore = KeyStore.getInstance(sslProperties.getKeystoreType()); + try (final InputStream fis = new FileInputStream(sslProperties.getKeystorePath())) { + keystore.load(fis, sslProperties.getKeystorePass().toCharArray()); } // Trust own CA and all self-signed certs - return SSLContexts.custom().loadKeyMaterial(keystore, sslProperties.getKeystorePass().toCharArray()) - .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build(); + return SSLContexts.custom() + .loadKeyMaterial(keystore, sslProperties.getKeystorePass().toCharArray()) + .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()) + .build(); } + @AllArgsConstructor public static class JettySslConfig { - static final String JETTY_BASE = System.getenv("JETTY_BASE"); - static final String KEY_STORE_TYPE_PROPERTY_NAME = "jetty.sslContext.keyStoreType"; - static final String TRUST_STORE_TYPE_PROPERTY_NAME = "jetty.sslContext.trustStoreType"; - Properties sslProperties; + private final Properties sslProperties; - JettySslConfig(Properties sslProperties) { - this.sslProperties = sslProperties; - } - - public String getJettyBase() { - return JettySslConfig.JETTY_BASE; + public String getJettyBase(){ + return JETTY_BASE; } public String getKeystorePath() { @@ -83,7 +85,7 @@ public class JettySSLUtils { } public String getKeystoreType() { - return sslProperties.getProperty(KEY_STORE_TYPE_PROPERTY_NAME, KeyStore.getDefaultType()); + return sslProperties.getProperty("jetty.sslContext.keyStoreType", KeyStore.getDefaultType()); } public String getTruststorePath() { @@ -95,10 +97,10 @@ public class JettySSLUtils { } public String getTruststoreType() { - return sslProperties.getProperty(TRUST_STORE_TYPE_PROPERTY_NAME, KeyStore.getDefaultType()); + return sslProperties.getProperty("jetty.sslContext.trustStoreType", KeyStore.getDefaultType()); } - public String getKeyStoreManager() { + public String getKeyManagerPassword() { return sslProperties.getProperty("jetty.sslContext.keyManagerPassword"); } @@ -110,8 +112,5 @@ public class JettySSLUtils { } } - public String getProperty(String key) { - return sslProperties.getProperty(key); - } } } diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml index 2ccfa6d156..18de9b88b2 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/item-rest/item-rest-services/pom.xml @@ -110,6 +110,11 @@ + + org.apache.httpcomponents + httpcore + ${httpcore.version} +
diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java index 5bfd29affa..754199ac29 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vnf-repository-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/VnfPackageRepositoryImpl.java @@ -16,24 +16,6 @@ */ package org.openecomp.sdcrests.vsp.rest.services; -import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION; -import static org.openecomp.core.utilities.file.FileUtils.getFileExtension; -import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName; - -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.security.GeneralSecurityException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import javax.inject.Named; -import javax.net.ssl.SSLContext; -import javax.ws.rs.client.Client; -import javax.ws.rs.client.ClientBuilder; -import javax.ws.rs.core.Response; import org.onap.config.api.ConfigurationManager; import org.onap.config.api.JettySSLUtils; import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum; @@ -57,6 +39,20 @@ import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFile import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; +import javax.inject.Named; +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.core.Response; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +import static javax.ws.rs.core.HttpHeaders.CONTENT_DISPOSITION; +import static org.openecomp.core.utilities.file.FileUtils.getFileExtension; +import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName; + /** * Enables integration API interface with VNF Repository (VNFSDK). *
    @@ -77,17 +73,15 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { private static Client trustSSLClient() { try { - SSLContext sslcontext = JettySSLUtils.getSslContext(); - return ClientBuilder.newBuilder().sslContext(sslcontext).hostnameVerifier((requestedHost, remoteServerSession) - -> requestedHost.equalsIgnoreCase(remoteServerSession.getPeerHost())).build(); - - } catch (IOException | GeneralSecurityException e) { + return ClientBuilder.newBuilder() + .sslContext(JettySSLUtils.getSslContext()) + .hostnameVerifier((requestedHost, remoteServerSession) -> requestedHost.equalsIgnoreCase(remoteServerSession.getPeerHost())).build(); + } catch (final Exception e) { LOGGER.error("Failed to initialize SSL context", e); } return ClientBuilder.newClient(); } - private final Configuration config; public VnfPackageRepositoryImpl(Configuration config) { @@ -126,15 +120,15 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { private Response uploadVnfPackage(final String vspId, final String versionId, final String csarId, final byte[] payload) { try { final OrchestrationTemplateCandidateManager candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance() - .createInterface(); + .createInterface(); final String filename = formatFilename(csarId); final String fileExtension = getFileExtension(filename); final OnboardPackageInfo onboardPackageInfo = new OnboardPackageInfo(getNetworkPackageName(filename), fileExtension, - ByteBuffer.wrap(payload), OnboardingTypesEnum.getOnboardingTypesEnum(fileExtension)); + ByteBuffer.wrap(payload), OnboardingTypesEnum.getOnboardingTypesEnum(fileExtension)); final VspDetails vspDetails = new VspDetails(vspId, getVersion(vspId, versionId)); final UploadFileResponse response = candidateManager.upload(vspDetails, onboardPackageInfo); final UploadFileResponseDto uploadFileResponse = new MapUploadFileResponseToUploadFileResponseDto() - .applyMapping(response, UploadFileResponseDto.class); + .applyMapping(response, UploadFileResponseDto.class); return Response.ok(uploadFileResponse).build(); } catch (final Exception e) { ErrorCode error = new GeneralErrorBuilder().build(); @@ -172,7 +166,7 @@ public class VnfPackageRepositoryImpl implements VnfPackageRepository { if (LOGGER.isErrorEnabled()) { String body = response.hasEntity() ? response.readEntity(String.class) : ""; LOGGER.error("Unexpected response status while {}: URI={}, status={}, body={}", action, uri, response.getStatus(), body, - new CoreException(error)); + new CoreException(error)); } return generateInternalServerError(error); } diff --git a/openecomp-be/backend/openecomp-sdc-security-util/pom.xml b/openecomp-be/backend/openecomp-sdc-security-util/pom.xml index 78d2236a08..166f4604a8 100644 --- a/openecomp-be/backend/openecomp-sdc-security-util/pom.xml +++ b/openecomp-be/backend/openecomp-sdc-security-util/pom.xml @@ -13,12 +13,6 @@ - - org.slf4j - slf4j-api - 1.7.25 - - org.apache.commons commons-crypto diff --git a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/Dockerfile b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/Dockerfile index f0f9d5fa42..cc34c81f09 100644 --- a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/Dockerfile +++ b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/Dockerfile @@ -1,4 +1,4 @@ -FROM onap/integration-java11:9.0.0 +FROM onap/integration-java11:10.0.0 USER root ARG JETTY_FOLDER=/app/jetty diff --git a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb index 074584a6e8..d2a40942e8 100644 --- a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb +++ b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/attributes/default.rb @@ -5,15 +5,19 @@ default['FE'][:http_port] = 8181 default['FE'][:https_port] = 9443 default['disableHttp'] = true default['cassandra'][:truststore_password] = "Aa123456" + +default['jetty']['keystore_path'] = "etc/org.onap.sdc.p12" default['jetty'][:keystore_pwd] = "?(kP!Yur![*!Y5!E^f(ZKc31" default['jetty'][:keymanager_pwd] = "?(kP!Yur![*!Y5!E^f(ZKc31" +default['jetty']['truststore_path'] = "etc/org.onap.sdc.trust.jks" +# TO CHANGE THE TRUSTSTORE CERT THE JVM CONFIGURATION +# MUST BE ALSO CHANGE IN THE startup.sh FILE default['jetty'][:truststore_pwd] = "z+KEj;t+,KN^iimSiS89e#p0" -default['jetty']['truststore_path'] = "#{ENV['JETTY_BASE']}/etc/truststore" default['VnfRepo']['vnfRepoPort'] = 8702 default['VnfRepo']['vnfRepoHost'] = "refrepo" -#Cassandra +# Cassandra default['cassandra']['cassandra_port'] = 9042 default['cassandra']['datacenter_name'] = "DC-" default['cassandra']['cluster_name'] = "SDC-CS-" @@ -21,12 +25,12 @@ default['cassandra']['socket_read_timeout'] = 20000 default['cassandra']['socket_connect_timeout'] = 20000 default['cassandra']['janusgraph_connection_timeout'] = 10000 -#Basicauth +# Basicauth default['basic_auth']['enabled'] = true default['basic_auth'][:user_name] = "testName" default['basic_auth'][:user_pass] = "testPass" default['basic_auth']['excludedUrls'] = "/v1.0/healthcheck" -#ExternalTesting +# ExternalTesting default['EXTTEST']['ep1_config'] = "vtp,VTP,true,http://refrepo:8702/onapapi/vnfsdk-marketplace,onap.*" default['EXTTEST']['ep2_config'] = "repository,Repository,false,,.*" diff --git a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/recipes/ON_4_setup_jetty_modules.rb b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/recipes/ON_4_setup_jetty_modules.rb index 6b2b79b49c..2e51402016 100644 --- a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/recipes/ON_4_setup_jetty_modules.rb +++ b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/recipes/ON_4_setup_jetty_modules.rb @@ -1,4 +1,4 @@ -#Set the http module option +# Set the http module option if node['disableHttp'] http_option = "#--module=http" else @@ -18,12 +18,11 @@ template "http-ini" do group "#{ENV['JETTY_GROUP']}" mode "0755" variables ({ - :http_option => http_option , + :http_option => http_option, :http_port => "#{node['ONBOARDING_BE'][:http_port]}" }) - -end +end template "https-ini" do path "#{ENV['JETTY_BASE']}/start.d/https.ini" @@ -34,7 +33,6 @@ template "https-ini" do variables :https_port => "#{node['ONBOARDING_BE'][:https_port]}" end - template "ssl-ini" do path "#{ENV['JETTY_BASE']}/start.d/ssl.ini" source "ssl-ini.erb" @@ -42,9 +40,11 @@ template "ssl-ini" do group "#{ENV['JETTY_GROUP']}" mode "0755" variables ({ - :https_port => "#{node['ONBOARDING_BE'][:https_port]}" , - :jetty_keystore_pwd => "#{node['jetty'][:keystore_pwd]}" , - :jetty_keymanager_pwd => "#{node['jetty'][:keymanager_pwd]}" , + :https_port => "#{node['ONBOARDING_BE'][:https_port]}", + :jetty_keystore_path => "#{node['jetty'][:keystore_path]}", + :jetty_keystore_pwd => "#{node['jetty'][:keystore_pwd]}", + :jetty_keymanager_pwd => "#{node['jetty'][:keymanager_pwd]}", + :jetty_truststore_path => "#{node['jetty'][:truststore_path]}", :jetty_truststore_pwd => "#{node['jetty'][:truststore_pwd]}" }) end diff --git a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/templates/default/ssl-ini.erb b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/templates/default/ssl-ini.erb index 278fdea2ae..c489825c7b 100644 --- a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/templates/default/ssl-ini.erb +++ b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/chef-repo/cookbooks/sdc-onboard-backend/templates/default/ssl-ini.erb @@ -42,17 +42,17 @@ jetty.ssl.port=<%= @https_port %> ## See http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html ## Keystore file path (relative to $jetty.base) -jetty.sslContext.keyStorePath=etc/org.onap.sdc.p12 +jetty.sslContext.keyStorePath=<%= @jetty_keystore_path %> ## Truststore file path (relative to $jetty.base) -jetty.sslContext.trustStorePath=etc/org.onap.sdc.trust.jks +jetty.sslContext.trustStorePath=<%= @jetty_truststore_path %> ## Keystore password # jetty.sslContext.keyStorePassword=OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4 jetty.sslContext.keyStorePassword=<%= @jetty_keystore_pwd %> ## Keystore type and provider -# jetty.sslContext.keyStoreType=JKS +jetty.sslContext.keyStoreType=JKS # jetty.sslContext.keyStoreProvider= ## KeyManager password @@ -64,7 +64,7 @@ jetty.sslContext.keyManagerPassword=<%= @jetty_keymanager_pwd %> jetty.sslContext.trustStorePassword=<%= @jetty_truststore_pwd %> ## Truststore type and provider -# jetty.sslContext.trustStoreType=JKS +jetty.sslContext.trustStoreType=JKS # jetty.sslContext.trustStoreProvider= ## whether client certificate authentication is required diff --git a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/startup.sh b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/startup.sh index 43aad8726a..6ee1b7b344 100644 --- a/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/startup.sh +++ b/openecomp-be/dist/sdc-onboard-backend-docker/artifacts/startup.sh @@ -8,6 +8,8 @@ JAVA_OPTIONS="$JAVA_OPTIONS \ -Dconfiguration.yaml=$JETTY_BASE/config/onboarding-be/onboarding_configuration.yaml \ -Dfeatures.properties=$JETTY_BASE/config/onboarding-be/features.properties \ -XX:+HeapDumpOnOutOfMemoryError \ + -Djavax.net.ssl.trustStore=$JETTY_BASE/etc/org.onap.sdc.trust.jks \ + -Djavax.net.ssl.trustStorePassword=z+KEj;t+,KN^iimSiS89e#p0 \ -Dconfig.location=$JETTY_BASE/config/onboarding-be/." cd $JETTY_BASE @@ -16,6 +18,6 @@ cd $JETTY_BASE/chef-solo chef-solo -c solo.rb -E ${ENVNAME} cd $JETTY_HOME -echo "jetty.httpConfig.sendServerVersion=false" >> $JETTY_HOME/start.d/start.ini +echo "jetty.httpConfig.sendServerVersion=false" >>$JETTY_HOME/start.d/start.ini java $JAVA_OPTIONS -jar "${JETTY_HOME}/start.jar" diff --git a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/pom.xml b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/pom.xml index 3748ef8b26..ea2aa235e2 100644 --- a/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/pom.xml +++ b/openecomp-be/lib/openecomp-sdc-logging-lib/openecomp-sdc-logging-core/pom.xml @@ -18,11 +18,6 @@ openecomp-sdc-logging-api ${project.version} - - org.slf4j - slf4j-api - ${slf4j-api.version} - ch.qos.logback logback-classic diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/pom.xml b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/pom.xml index dd9e77422e..fe4e1b70ae 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/pom.xml +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/pom.xml @@ -16,106 +16,110 @@ --> - 4.0.0 + xmlns="http://maven.apache.org/POM/4.0.0" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + 4.0.0 - openecomp-sdc-validation-impl - openecomp-sdc-validation-impl + openecomp-sdc-validation-impl + openecomp-sdc-validation-impl - - org.openecomp.sdc - openecomp-sdc-validation-lib - 1.12.4-SNAPSHOT - + + org.openecomp.sdc + openecomp-sdc-validation-lib + 1.12.4-SNAPSHOT + - - - ch.qos.logback - logback-classic - ${logback.version} - - - org.openecomp.sdc - openecomp-sdc-logging-core - ${project.version} - runtime - - - org.openecomp.sdc - openecomp-sdc-logging-api - ${project.version} - - - org.openecomp.sdc.core - openecomp-utilities-lib - ${project.version} - - - org.eclipse.jetty - jetty-server - - - org.eclipse.jetty - jetty-servlet - - - - - org.openecomp.sdc - openecomp-sdc-validation-api - ${project.version} - - - org.openecomp.sdc.core - openecomp-common-lib - ${project.version} - - - org.openecomp.sdc.core - openecomp-heat-lib - ${project.version} - - - commons-io - commons-io - ${commons.io.version} - test - - - org.openecomp.sdc - openecomp-sdc-validation-core - ${project.version} - - - org.onap.vnfsdk.validation - validation-pmdictionary - ${onap.vnfsdk.validation.pmdictionary.version} - - - org.apache.logging.log4j - log4j-slf4j-impl - - - - - io.vavr - vavr - ${io.vavr.version} - - - org.apache.httpcomponents - httpmime - ${httpclient.version} - compile - - - org.apache.httpcomponents - httpcore - - - - + + + ch.qos.logback + logback-classic + ${logback.version} + + + org.openecomp.sdc + openecomp-sdc-logging-core + ${project.version} + runtime + + + org.openecomp.sdc + openecomp-sdc-logging-api + ${project.version} + + + org.openecomp.sdc.core + openecomp-utilities-lib + ${project.version} + + + org.eclipse.jetty + jetty-server + + + org.eclipse.jetty + jetty-servlet + + + + + org.openecomp.sdc + openecomp-sdc-validation-api + ${project.version} + + + org.openecomp.sdc.core + openecomp-common-lib + ${project.version} + + + org.openecomp.sdc.core + openecomp-heat-lib + ${project.version} + + + commons-io + commons-io + ${commons.io.version} + test + + + org.openecomp.sdc + openecomp-sdc-validation-core + ${project.version} + + + org.onap.vnfsdk.validation + validation-pmdictionary + ${onap.vnfsdk.validation.pmdictionary.version} + + + org.apache.logging.log4j + log4j-slf4j-impl + + + + + io.vavr + vavr + ${io.vavr.version} + + + org.apache.httpcomponents + httpmime + ${httpclient.version} + + + org.apache.httpcomponents + httpcore + + + + + org.apache.httpcomponents + httpcore + ${httpcore.version} + + diff --git a/pom.xml b/pom.xml index 24ebf53a40..7844a524a1 100644 --- a/pom.xml +++ b/pom.xml @@ -60,7 +60,6 @@ Modifications copyright (c) 2018-2019 Nokia 2.26.3 3.4.0 4.3.1.0 - 2.1.8 1.18.24 1.9.4 2.8.0 @@ -80,8 +79,8 @@ Modifications copyright (c) 2018-2019 Nokia 2.1.1 2.0.1.Final - 9.4.49.v20220914 - ${jetty.version} + 10.0.14 + 9.4.51.v20230217 3.4.4 2.4.0.0 @@ -110,8 +109,8 @@ Modifications copyright (c) 2018-2019 Nokia - 1.2.10 - 1.7.25 + 1.2.12 + 1.7.36 1.15 1.2 3.0.6 @@ -356,6 +355,11 @@ Modifications copyright (c) 2018-2019 Nokia keycloak-authz-client ${keycloak.version} + + org.slf4j + slf4j-api + ${slf4j-api.version} + org.keycloak keycloak-spring-security-adapter @@ -881,6 +885,7 @@ Modifications copyright (c) 2018-2019 Nokia true true true + true true true diff --git a/utils/webseal-simulator/sdc-simulator/Dockerfile b/utils/webseal-simulator/sdc-simulator/Dockerfile index 5f30e8cc7a..22e74dfdb3 100644 --- a/utils/webseal-simulator/sdc-simulator/Dockerfile +++ b/utils/webseal-simulator/sdc-simulator/Dockerfile @@ -1,4 +1,4 @@ -FROM onap/integration-java11:9.0.0 +FROM onap/integration-java11:10.0.0 USER root ARG JETTY_FOLDER=/app/jetty diff --git a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_5_create_jetty_modules.rb b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_5_create_jetty_modules.rb index ab6c5aabdb..34c874e8c4 100644 --- a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_5_create_jetty_modules.rb +++ b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_5_create_jetty_modules.rb @@ -53,9 +53,11 @@ template "ssl-ini" do mode "0755" variables({ :https_port => "8443", - :jetty_truststore_pwd => "z+KEj;t+,KN^iimSiS89e#p0", + :jetty_keystore_path => "etc/org.onap.sdc.p12" , :jetty_keystore_pwd => "?(kP!Yur![*!Y5!E^f(ZKc31", - :jetty_keymanager_pwd => "?(kP!Yur![*!Y5!E^f(ZKc31", + :jetty_truststore_path => "etc/org.onap.sdc.trust.jks", + :jetty_truststore_pwd => "z+KEj;t+,KN^iimSiS89e#p0", + :jetty_keymanager_pwd => "?(kP!Yur![*!Y5!E^f(ZKc31" }) end diff --git a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-ssl-ini.erb b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-ssl-ini.erb index 278fdea2ae..c489825c7b 100644 --- a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-ssl-ini.erb +++ b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/templates/default/SDC-Simulator-ssl-ini.erb @@ -42,17 +42,17 @@ jetty.ssl.port=<%= @https_port %> ## See http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html ## Keystore file path (relative to $jetty.base) -jetty.sslContext.keyStorePath=etc/org.onap.sdc.p12 +jetty.sslContext.keyStorePath=<%= @jetty_keystore_path %> ## Truststore file path (relative to $jetty.base) -jetty.sslContext.trustStorePath=etc/org.onap.sdc.trust.jks +jetty.sslContext.trustStorePath=<%= @jetty_truststore_path %> ## Keystore password # jetty.sslContext.keyStorePassword=OBF:1vny1zlo1x8e1vnw1vn61x8g1zlu1vn4 jetty.sslContext.keyStorePassword=<%= @jetty_keystore_pwd %> ## Keystore type and provider -# jetty.sslContext.keyStoreType=JKS +jetty.sslContext.keyStoreType=JKS # jetty.sslContext.keyStoreProvider= ## KeyManager password @@ -64,7 +64,7 @@ jetty.sslContext.keyManagerPassword=<%= @jetty_keymanager_pwd %> jetty.sslContext.trustStorePassword=<%= @jetty_truststore_pwd %> ## Truststore type and provider -# jetty.sslContext.trustStoreType=JKS +jetty.sslContext.trustStoreType=JKS # jetty.sslContext.trustStoreProvider= ## whether client certificate authentication is required diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java index 6112d983ea..c2cb5b58ae 100644 --- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java +++ b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SdcProxy.java @@ -20,34 +20,6 @@ package org.openecomp.sdc.webseal.simulator; -import static java.nio.charset.StandardCharsets.UTF_8; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLEncoder; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.stream.Collectors; -import java.util.zip.GZIPInputStream; -import javax.net.ssl.SSLContext; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.ServletInputStream; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import lombok.Getter; import org.apache.commons.lang3.StringUtils; @@ -74,17 +46,47 @@ import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContextBuilder; +import org.onap.config.api.JettySSLUtils; import org.openecomp.sdc.webseal.simulator.conf.Conf; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import javax.net.ssl.SSLContext; +import javax.servlet.RequestDispatcher; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLEncoder; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.zip.GZIPInputStream; + +import static java.nio.charset.StandardCharsets.UTF_8; + public class SdcProxy extends HttpServlet { private static final Logger LOGGER = LoggerFactory.getLogger(SdcProxy.class); private static final long serialVersionUID = 1L; private static final Set RESERVED_HEADERS = - Arrays.stream(ReservedHeaders.values()).map(ReservedHeaders::getValue).collect(Collectors.toSet()); + Arrays.stream(ReservedHeaders.values()).map(ReservedHeaders::getValue).collect(Collectors.toSet()); private static final String USER_ID = "USER_ID"; private static final String HTTP_IV_USER = "HTTP_IV_USER"; private static final String SDC1 = "/sdc1"; @@ -174,6 +176,13 @@ public class SdcProxy extends HttpServlet { HttpRequestBase httpMethod = createHttpMethod(request, methodEnum, uri); addHeadersToMethod(httpMethod, user, request); + try { + httpClient = buildRestClient(); + } catch (Exception e) { + LOGGER.error("Failed to buildRestClient", e); + throw new RuntimeException(e); + } + try (CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpMethod)) { response.setStatus(closeableHttpResponse.getStatusLine().getStatusCode()); if (request.getRequestURI().indexOf(".svg") > -1) { @@ -378,26 +387,37 @@ public class SdcProxy extends HttpServlet { private CloseableHttpClient buildRestClient() throws NoSuchAlgorithmException, KeyStoreException { final var builder = new SSLContextBuilder(); + SSLContext sslContext; + try { + sslContext = JettySSLUtils.getSslContext(); + } catch (Exception e) { + LOGGER.error("Failed to getSslContext", e); + throw new RuntimeException(e); + } builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); - SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(), - NoopHostnameVerifier.INSTANCE); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry registry = RegistryBuilder.create() - .register("http", new PlainConnectionSocketFactory()) - .register("https", sslsf) - .build(); - PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); + .register("http", new PlainConnectionSocketFactory()) + .register("https", sslsf) + .build(); return HttpClients.custom() - .setSSLSocketFactory(sslsf) - .setConnectionManager(cm) - .build(); + .setSSLSocketFactory(sslsf) + .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) + .build(); } @AllArgsConstructor @Getter enum ReservedHeaders { - HTTP_IV_USER(SdcProxy.HTTP_IV_USER), USER_ID(SdcProxy.USER_ID), HTTP_CSP_FIRSTNAME("HTTP_CSP_FIRSTNAME"), HTTP_CSP_EMAIL( - "HTTP_CSP_EMAIL"), HTTP_CSP_LASTNAME("HTTP_CSP_LASTNAME"), HTTP_IV_REMOTE_ADDRESS("HTTP_IV_REMOTE_ADDRESS"), HTTP_CSP_WSTYPE( - "HTTP_CSP_WSTYPE"), HOST("Host"), CONTENTLENGTH("Content-Length"); + HTTP_IV_USER(SdcProxy.HTTP_IV_USER), + USER_ID(SdcProxy.USER_ID), + HTTP_CSP_FIRSTNAME("HTTP_CSP_FIRSTNAME"), + HTTP_CSP_EMAIL("HTTP_CSP_EMAIL"), + HTTP_CSP_LASTNAME("HTTP_CSP_LASTNAME"), + HTTP_IV_REMOTE_ADDRESS("HTTP_IV_REMOTE_ADDRESS"), + HTTP_CSP_WSTYPE("HTTP_CSP_WSTYPE"), + HOST("Host"), + CONTENTLENGTH("Content-Length"); private final String value; -- cgit 1.2.3-korg