Changes for backend to support SSL 52/98652/3
authorilanap <ilanap@amdocs.com>
Mon, 18 Nov 2019 11:38:23 +0000 (13:38 +0200)
committerilanap <ilanap@amdocs.com>
Wed, 18 Dec 2019 13:17:23 +0000 (15:17 +0200)
Changes to support starting in https mode and changes to support making a secured call to the SDC backend
(cherry picked from commit 820f4ec65a28ed822d4205b05ac6fbbd910a46cc)

Issue-ID: SDC-2405

Change-Id: I0588484fdcb0903934814906672f4fc9a76eca2c
Signed-off-by: ilanap <ilanap@amdocs.com>
14 files changed:
workflow-designer-be/docker/Dockerfile [new file with mode: 0644]
workflow-designer-be/docker/org.onap.sdc.p12 [new file with mode: 0644]
workflow-designer-be/docker/org.onap.sdc.trust.jks [new file with mode: 0644]
workflow-designer-be/docker/startup.sh [new file with mode: 0644]
workflow-designer-be/pom.xml
workflow-designer-be/src/main/java/org/onap/sdc/workflow/api/ArtifactAssociationService.java
workflow-designer-be/src/main/resources/application.properties
workflow-designer-ui/docker/Dockerfile
workflow-designer-ui/docker/org.onap.sdc.p12 [new file with mode: 0644]
workflow-designer-ui/docker/org.onap.sdc.trust.jks [new file with mode: 0644]
workflow-designer-ui/docker/startup.sh
workflow-designer-ui/src/main/frontend/yarn.lock
workflow-designer-ui/src/main/java/org/onap/workflow/web/SSLProxyServlet.java [new file with mode: 0644]
workflow-designer-ui/src/main/webapp/WEB-INF/web.xml

diff --git a/workflow-designer-be/docker/Dockerfile b/workflow-designer-be/docker/Dockerfile
new file mode 100644 (file)
index 0000000..ea20fa5
--- /dev/null
@@ -0,0 +1,17 @@
+FROM openjdk:8-jdk-alpine
+
+EXPOSE 8080
+
+USER root
+
+ARG ARTIFACT
+
+ADD ${ARTIFACT} /app.jar
+
+COPY org.onap.sdc.p12 /keystore
+COPY org.onap.sdc.trust.jks /truststore
+
+COPY startup.sh .
+RUN chmod 744 startup.sh
+
+ENTRYPOINT [ "./startup.sh" ]
\ No newline at end of file
diff --git a/workflow-designer-be/docker/org.onap.sdc.p12 b/workflow-designer-be/docker/org.onap.sdc.p12
new file mode 100644 (file)
index 0000000..d03ca1c
Binary files /dev/null and b/workflow-designer-be/docker/org.onap.sdc.p12 differ
diff --git a/workflow-designer-be/docker/org.onap.sdc.trust.jks b/workflow-designer-be/docker/org.onap.sdc.trust.jks
new file mode 100644 (file)
index 0000000..d07ce1a
Binary files /dev/null and b/workflow-designer-be/docker/org.onap.sdc.trust.jks differ
diff --git a/workflow-designer-be/docker/startup.sh b/workflow-designer-be/docker/startup.sh
new file mode 100644 (file)
index 0000000..bc1d646
--- /dev/null
@@ -0,0 +1,28 @@
+#!/bin/sh
+
+HTTPS_ENABLED=${SERVER_SSL_ENABLED:-"false"}
+if [ "$HTTPS_ENABLED" = "true" ]
+then
+    KEYSTORE=${SERVER_SSL_KEYSTORE_PATH}
+    if [ -f "$KEYSTORE" ]; then
+        echo "$KEYSTORE exist"
+    else
+        echo "Copying default keystore"
+        KEYSTORE_DIR=${KEYSTORE%/*}
+        mkdir -p $KEYSTORE_DIR
+        cp /keystore $KEYSTORE_DIR
+        chmod 755 $KEYSTORE
+    fi
+
+    TRUSTSTORE=${SERVER_SSL_TRUSTSTORE_PATH}
+    if [ -f "$TRUSTSTORE" ]; then
+        echo "$TRUSTSTORE exist"
+    else
+        echo "Copying default truststore"
+        TRUSTSTORE_DIR=${TRUSTSTORE%/*}
+        mkdir -p $TRUSTSTORE_DIR
+        cp /truststore $TRUSTSTORE_DIR
+        chmod 755 $TRUSTSTORE
+    fi
+fi
+java ${JAVA_OPTIONS} -jar /app.jar ${SPRING_BOOT_OPTIONS}
\ No newline at end of file
index 8cea7cb..dd108a1 100644 (file)
             <artifactId>logback-classic</artifactId>
             <scope>runtime</scope>
         </dependency>
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.mapstruct</groupId>
             <artifactId>mapstruct</artifactId>
         <dependency>
             <groupId>org.onap.sdc.sdc-be-common</groupId>
             <artifactId>session-lib</artifactId>
-            <version>1.5.2-SNAPSHOT</version>
+            <version>1.5.2</version>
         </dependency>
         <dependency>
             <groupId>org.onap.sdc.sdc-be-common</groupId>
             <artifactId>versioning-lib</artifactId>
-            <version>1.5.2-SNAPSHOT</version>
+            <version>1.5.2</version>
             <exclusions>
                 <exclusion>
                     <groupId>org.springframework.boot</groupId>
         <dependency>
             <groupId>org.onap.sdc.sdc-be-common</groupId>
             <artifactId>zusammen-lib</artifactId>
-            <version>1.5.2-SNAPSHOT</version>
+            <version>1.5.2</version>
             <exclusions>
                 <exclusion>
                     <groupId>org.springframework.boot</groupId>
             </activation>
             <build>
                 <plugins>
+                    <plugin>
+                        <artifactId>maven-resources-plugin</artifactId>
+                        <version>2.6</version>
+                        <executions>
+                            <execution>
+                                <id>copy-resources-docker</id>
+                                <phase>install</phase>
+                                <goals>
+                                    <goal>copy-resources</goal>
+                                </goals>
+                                <configuration>
+                                    <outputDirectory>${basedir}/docker</outputDirectory>
+                                    <resources>
+                                        <resource>
+                                            <directory>${project.build.directory}</directory>
+                                            <include>${project.build.finalName}.jar</include>
+                                        </resource>
+                                    </resources>
+                                </configuration>
+                            </execution>
+                        </executions>
+                    </plugin>
                     <plugin>
                         <groupId>io.fabric8</groupId>
                         <artifactId>docker-maven-plugin</artifactId>
                                         <tags>
                                             <tag>${project.version}</tag>
                                         </tags>
-                                        <from>openjdk:8-jdk-alpine</from>
-                                        <user>root</user>
-                                        <assembly>
-                                            <descriptorRef>artifact</descriptorRef>
-                                            <targetDir>/</targetDir>
-                                        </assembly>
-                                        <entryPoint>
-                                            java ${JAVA_OPTIONS} -jar /${project.build.finalName}.jar
-                                        </entryPoint>
+                                        <dockerFileDir>${project.basedir}/docker</dockerFileDir>
+                                        <args>
+                                            <ARTIFACT>${project.build.finalName}.jar</ARTIFACT>
+                                        </args>
                                     </build>
                                 </image>
                             </images>
index 621d180..2b24577 100644 (file)
@@ -19,30 +19,47 @@ package org.onap.sdc.workflow.api;
 import static org.apache.commons.codec.digest.DigestUtils.md5Hex;
 
 import com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.io.File;
+import java.io.FileInputStream;
 import java.io.IOException;
 import java.nio.charset.Charset;
+import java.security.GeneralSecurityException;
+import java.security.KeyStore;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
 import java.util.ArrayList;
-import java.util.Base64;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Optional;
+
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.openecomp.sdc.logging.api.Logger;
+import org.openecomp.sdc.logging.api.LoggerFactory;
+
+import java.util.Base64;
+
 import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpHost;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.ssl.SSLContexts;
 import org.onap.sdc.workflow.api.types.dto.ArtifactDeliveriesRequestDto;
 import org.onap.sdc.workflow.persistence.types.ArtifactEntity;
-import org.openecomp.sdc.logging.api.Logger;
-import org.openecomp.sdc.logging.api.LoggerFactory;
+
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.boot.web.client.RestTemplateBuilder;
-import org.springframework.http.HttpEntity;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.HttpMethod;
-import org.springframework.http.HttpStatus;
-import org.springframework.http.MediaType;
-import org.springframework.http.ResponseEntity;
+import org.springframework.http.*;
+import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
 import org.springframework.stereotype.Component;
 import org.springframework.web.client.RestTemplate;
 
+import javax.net.ssl.SSLContext;
+
 
 @Component("ArtifactAssociationHandler")
 public class ArtifactAssociationService {
@@ -54,6 +71,8 @@ public class ArtifactAssociationService {
     private static final String X_ECOMP_INSTANCE_ID_HEADER = "X-ECOMP-InstanceID";
     private static final String INIT_ERROR_MSG =
             "Failed while attaching workflow artifact to Operation in SDC. Parameters were not initialized: %s";
+    private static final String INIT_CLIENT_MSG =
+            "Failed while creating the HTTP client to SDC. Following exception: %s";
     private static final Logger LOGGER = LoggerFactory.getLogger(ArtifactAssociationService.class);
     @Value("${sdc.be.endpoint}")
     private String sdcBeEndpoint;
@@ -66,12 +85,63 @@ public class ArtifactAssociationService {
 
     private RestTemplate restClient;
 
+    private KeyStore getKeyStore(String file, String password, String keyStoreType) throws IOException, GeneralSecurityException {
+        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
+        File keyFile = new File(file);
+        try (FileInputStream inStr = new FileInputStream(keyFile)) {
+            keyStore.load(inStr, password.toCharArray());
+        }
+        return keyStore;
+
+    }
+
+
     @Autowired
-    public ArtifactAssociationService(RestTemplateBuilder builder) {
-        this.restClient = builder.build();
+    public ArtifactAssociationService(RestTemplateBuilder builder,
+                                      @Value("${server.ssl.trust-store}")
+                                              String truststorePath,
+                                      @Value("${server.ssl.trust-store-password}")
+                                              String truststorePassword,
+                                      @Value("${server.ssl.trust-store-type}")
+                                              String truststoreType,
+                                      @Value("${server.ssl.key-store}")
+                                              String keystorePath,
+                                      @Value("${server.ssl.key-password}")
+                                              String keystorePassword,
+                                      @Value("${server.ssl.key-store-type}")
+                                              String keystoreType,
+                                      @Value("${sdc.be.protocol}")
+                                              String protocol) {
+        if (protocol != null &&
+                !protocol.equalsIgnoreCase(HttpHost.DEFAULT_SCHEME_NAME)) {
+            try {
+                KeyStore trustStore = getKeyStore(truststorePath, truststorePassword, truststoreType);
+                KeyStore keyStore = getKeyStore(keystorePath, keystorePassword, keystoreType);
+
+                SSLContext sslcontext = SSLContexts.custom()
+                        .loadKeyMaterial(keyStore, keystorePassword.toCharArray())
+                        .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
+                        .build();
+                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
+                        sslcontext,
+                        new NoopHostnameVerifier()
+                );
+                CloseableHttpClient httpClient =
+                        HttpClients.custom()
+                                .setSSLSocketFactory(sslsf)
+                                .setSSLHostnameVerifier(new NoopHostnameVerifier())
+                                .build();
+                HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
+                this.restClient = new RestTemplate(factory);
+            } catch (Exception e) {
+                LOGGER.error(String.format(INIT_CLIENT_MSG, e.getMessage()), e);
+            }
+        } else {
+            this.restClient = builder.build();
+        }
     }
 
-     void setRestClient(RestTemplate restClient) {
+    void setRestClient(RestTemplate restClient) {
         this.restClient = restClient;
     }
 
@@ -80,12 +150,12 @@ public class ArtifactAssociationService {
     }
 
     ResponseEntity<String> execute(String userId, ArtifactDeliveriesRequestDto deliveriesRequestDto,
-            ArtifactEntity artifactEntity) {
+                                   ArtifactEntity artifactEntity) {
 
         Optional<String> initializationState = parametersInitializationState();
-        if(initializationState.isPresent()) {
-            LOGGER.error(String.format(INIT_ERROR_MSG,initializationState.get()));
-            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(String.format(INIT_ERROR_MSG,initializationState.get()));
+        if (initializationState.isPresent()) {
+            LOGGER.error(String.format(INIT_ERROR_MSG, initializationState.get()));
+            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(String.format(INIT_ERROR_MSG, initializationState.get()));
         }
 
         String formattedArtifact;
@@ -96,7 +166,7 @@ public class ArtifactAssociationService {
             return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(e.getMessage());
         }
 
-        HttpEntity<String> request = new HttpEntity<>(formattedArtifact, createHeaders(userId,formattedArtifact));
+        HttpEntity<String> request = new HttpEntity<>(formattedArtifact, createHeaders(userId, formattedArtifact));
 
         return restClient.exchange(sdcBeProtocol + "://" + sdcBeEndpoint + "/" + deliveriesRequestDto.getEndpoint(),
                 HttpMethod.valueOf(deliveriesRequestDto.getMethod()), request, String.class);
@@ -117,7 +187,7 @@ public class ArtifactAssociationService {
             result.add("SDC_PASSWORD");
         }
 
-        if (result.isEmpty()) {
+        if (result.isEmpty() || this.restClient == null) {
             return Optional.empty();
         } else {
             return Optional.of(result.toString());
@@ -143,7 +213,7 @@ public class ArtifactAssociationService {
     private HttpHeaders createHeaders(String userId, String formattedArtifact) {
         HttpHeaders headers = new HttpHeaders();
         headers.add(USER_ID_HEADER, userId);
-        headers.add(HttpHeaders.AUTHORIZATION, createAuthorizationsHeaderValue(sdcUser,sdcPassword));
+        headers.add(HttpHeaders.AUTHORIZATION, createAuthorizationsHeaderValue(sdcUser, sdcPassword));
         headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
         headers.add(MD5_HEADER, calculateMD5Base64EncodedByString(formattedArtifact));
         headers.add(X_ECOMP_INSTANCE_ID_HEADER, "InstanceId");
index 203e385..1bcc1d6 100644 (file)
@@ -18,9 +18,16 @@ http.port=${HTTP_PORT:8080}
 
 server.port=${SERVER_PORT:8443}
 server.ssl.enabled=${SERVER_SSL_ENABLED:true}
-server.ssl.key-password=${SERVER_SSL_KEY_PASSWORD:rTIS;B4kM]2GHcNK2c3B4&Ng}
-server.ssl.key-store=${SERVER_SSL_KEYSTORE_PATH:classpath:org.onap.sdc.p12}
-server.ssl.key-store-type=${SERVER_SSL_KEYSTORE_TYPE:PKCS12}
+server.ssl.key-password=${SERVER_SSL_KEY_PASSWORD:}
+server.ssl.key-store-password=${SERVER_SSL_KEY_PASSWORD:}
+server.ssl.key-store=${SERVER_SSL_KEYSTORE_PATH:}
+server.ssl.key-store-type=${SERVER_SSL_KEYSTORE_TYPE:}
+server.ssl.trust-store-password=${SERVER_SSL_TRUST_PASSWORD:}
+server.ssl.trust-store=${SERVER_SSL_TRUSTSTORE_PATH:}
+server.ssl.trust-store-type=${SERVER_SSL_TRUSTSTORE_TYPE:}
+#server.ssl.protocol=${SERVER_SSL_PROTOCOL:TLS}
+#server.ssl.enabled-protocols=${SERVER_SSL_ENABLED_PROTOCOL:TLSv1.2}
+
 
 sdc.be.protocol=${SDC_PROTOCOL:https}
 sdc.be.endpoint=${SDC_ENDPOINT:}
index 83e8d5a..5256237 100644 (file)
@@ -7,10 +7,12 @@ USER root
 
 ARG ARTIFACT
 
+COPY org.onap.sdc.p12 org.onap.sdc.trust.jks ${JETTY_BASE}/etc/
+
 ADD ${ARTIFACT} ${JETTY_BASE}/webapps/
-RUN chown -R jetty:jetty ${JETTY_BASE}/webapps
+RUN chown -R jetty:jetty ${JETTY_BASE}/webapps ${JETTY_BASE}/etc/
 
 COPY startup.sh .
 RUN chmod 744 startup.sh
 
-ENTRYPOINT [ "./startup.sh" ]
\ No newline at end of file
+ENTRYPOINT [ "./startup.sh" ]
diff --git a/workflow-designer-ui/docker/org.onap.sdc.p12 b/workflow-designer-ui/docker/org.onap.sdc.p12
new file mode 100644 (file)
index 0000000..d03ca1c
Binary files /dev/null and b/workflow-designer-ui/docker/org.onap.sdc.p12 differ
diff --git a/workflow-designer-ui/docker/org.onap.sdc.trust.jks b/workflow-designer-ui/docker/org.onap.sdc.trust.jks
new file mode 100644 (file)
index 0000000..d07ce1a
Binary files /dev/null and b/workflow-designer-ui/docker/org.onap.sdc.trust.jks differ
index 359e6ac..b2f2d51 100644 (file)
@@ -2,24 +2,26 @@
 
 # adding support for https
 HTTPS_ENABLED=${IS_HTTPS:-"false"}
-
+CLIENT_AUTH=${IS_CLIENT_AUTH:-"false"}
 if [ "$HTTPS_ENABLED" = "true" ]
 then
     echo "enable ssl"
-    if [ -z "$KEYSTORE_PATH" ]; then
-        java -jar "${JETTY_HOME}/start.jar" --add-to-start=https,ssl \
-            jetty.sslContext.keyStorePath=$KEYSTORE_PATH \
-            jetty.sslContext.keyStorePassword=$KEYSTORE_PASSWORD \
-            jetty.sslContext.keyStoreType=$KEYSTORE_TYPE \
-            jetty.sslContext.trustStorePath=$TRUSTSTORE_PATH \
-            jetty.sslContext.trustStorePassword=$TRUSTSTORE_PASSWORD \
-            jetty.sslContext.trustStoreType=$TRUSTSTORE_TYPE \
-     else
-         echo "Using jetty default SSL"
-         java -jar "${JETTY_HOME}/start.jar" --add-to-start=https,ssl
-     fi
+
+    java -jar "${JETTY_HOME}/start.jar" --add-to-start=https,ssl \
+        jetty.sslContext.keyStorePath=$KEYSTORE_PATH \
+        jetty.sslContext.keyStorePassword=$KEYSTORE_PASS \
+           jetty.sslContext.keyManagerPassword=$KEYSTORE_PASS \
+        jetty.sslContext.trustStorePath=$TRUSTSTORE_PATH \
+        jetty.sslContext.trustStorePassword=$TRUSTSTORE_PASS
+
+    echo "setting SSL environment variable"
+
+    SSL_JAVA_OPTS=" -DkeystorePath=$JETTY_BASE/$KEYSTORE_PATH -DkeystorePassword=$KEYSTORE_PASS -DkeyManagerPassword=$KEYSTORE_PASS -DtruststorePath=$JETTY_BASE/$KEYSTORE_PATH -DtruststorePassword=$TRUSTSTORE_PASS -DsslTrustAll=$TRUST_ALL"
+
+    echo $SSL_JAVA_OPTS
+
 else
     echo "no ssl required"
 fi
+java $JAVA_OPTIONS -DproxyTo=$BACKEND $SSL_JAVA_OPTS -jar $JETTY_HOME/start.jar
 
-java -DproxyTo=$BACKEND $JAVA_OPTIONS -jar $JETTY_HOME/start.jar
\ No newline at end of file
index 9670e72..633f8b3 100644 (file)
@@ -8292,19 +8292,21 @@ on-headers@~1.0.1:
   version "1.0.1"
   resolved "https://registry.yarnpkg.com/on-headers/-/on-headers-1.0.1.tgz#928f5d0f470d49342651ea6794b0857c100693f7"
 
-onap-ui-common@1.0.100:
-  version "1.0.100"
-  resolved "https://registry.yarnpkg.com/onap-ui-common/-/onap-ui-common-1.0.100.tgz#c0dae1d3d1c3fd2b866340d27a1179ed10a3a860"
-  integrity sha512-d+eaYgVgrj9B8/3iVDlkxO2jiE7wXFrvMogxxHsyM8E0Fa7wXGEGwohA4JD5nGydT84dU2vPzwkby7SZNgGpKA==
+onap-ui-common@1.0.101:
+  version "1.0.101"
+  resolved "https://registry.yarnpkg.com/onap-ui-common/-/onap-ui-common-1.0.101.tgz#c79b8fb903b7d2d3f959e3b5c27b561b563d961b"
 
-onap-ui-react@^0.1.1:
-  version "0.1.1"
-  resolved "https://registry.yarnpkg.com/onap-ui-react/-/onap-ui-react-0.1.1.tgz#3640bdb9fb10f85104ad9dd57a9f320b0703abf3"
-  integrity sha512-hax7WzSMIPll9fHvKVjFbn2dIOh39fWuiy0VQKONq/ccU3f/y08Y6EzJo7rzWcwjt8bp2KDhqNZky0HwIquc6w==
+onap-ui-common@^1.0.101:
+  version "1.0.106"
+  resolved "https://registry.yarnpkg.com/onap-ui-common/-/onap-ui-common-1.0.106.tgz#d7bf8e3eb1c422afcb87fc8f3eaaf5a996aa2947"
+
+onap-ui-react@^1.0.0:
+  version "1.0.2"
+  resolved "https://registry.yarnpkg.com/onap-ui-react/-/onap-ui-react-1.0.2.tgz#e99dc5a924f84a991c71a3e9c05a44a915830168"
   dependencies:
     "@storybook/react" "^3.1.5"
     http-loader "0.0.1"
-    onap-ui-common "1.0.100"
+    onap-ui-common "1.0.101"
     prop-types "^15.6.0"
     react "15.6.2"
     react-dom "15.6.2"
diff --git a/workflow-designer-ui/src/main/java/org/onap/workflow/web/SSLProxyServlet.java b/workflow-designer-ui/src/main/java/org/onap/workflow/web/SSLProxyServlet.java
new file mode 100644 (file)
index 0000000..8c17a92
--- /dev/null
@@ -0,0 +1,211 @@
+/*-
+ * ============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.onap.workflow.web;
+
+
+import org.eclipse.jetty.client.HttpClient;
+import org.eclipse.jetty.client.api.Request;
+import org.eclipse.jetty.http.HttpHeader;
+import org.eclipse.jetty.http.HttpScheme;
+import org.eclipse.jetty.proxy.ProxyServlet;
+import org.eclipse.jetty.util.URIUtil;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Enumeration;
+
+
+/***
+ * Class that provides the proxy implementation for both secured and unsecured backend connections.
+ *
+ * The following nevironment value is mandatory:
+ * proxyTo - the full URL to the backend server (including protocol and context path if relevant)
+ *
+ * In case of a secured connection (proxyTo starting with https) the following may be set:
+ * sslTrustAll - set to true if all secure connection are accepted
+ * maxPoolConnections - number of connection in the pool, only when overriding the jetty default
+ *
+ * In case of SSL and nto trusting all certificates:
+ * keystorePath - path to the keystore
+ * keystoreType - type of the keystore
+ * keystorePassword - keystore password
+ *
+ * truststorePath - path to the truststore
+ * truststoreType - type of the truststore
+ * truststorePassword - truststore password
+
+ */
+
+public class SSLProxyServlet extends ProxyServlet {
+
+
+    public static final int TIMEOUT = 600000;
+    protected static final String PROXY_TO = "proxyTo";
+    protected static final String TRUST_ALL = "sslTrustAll";
+    protected static final String MAX_POOL_CONNECTIONS = "maxPoolConnections";
+    protected static final String KEYSTORE_PATH = "keystorePath";
+    protected static final String KEYSTORE_TYPE = "keystoreType";
+    protected static final String KEYSTORE_P = "keystorePassword";
+    protected static final String KEYMANAGER_P = "keyManagerPassword";
+    protected static final String KEYSTORE_CYPHER = "keystoreCypher";
+    protected static final String TRUSTSTORE_PATH = "truststorePath";
+    protected static final String TRUSTSTORE_TYPE = "truststoreType";
+    protected static final String TRUSTSTORE_P = "truststorePassword";
+    protected static final String ENDPOINT_IDENTIFICATION_ALGORITHM = "endpointIdentificationAlgorithm";
+    private static final long serialVersionUID = 1L;
+    private static URL proxyUrl = null;
+
+
+    private static void setProxyUrl(URL proxy) {
+        SSLProxyServlet.proxyUrl = proxy;
+    }
+
+    private void initProxyUrl() throws ServletException, MalformedURLException {
+
+        if (SSLProxyServlet.proxyUrl != null)
+            return;
+        String proxyUrlStr = System.getProperty(PROXY_TO);
+        if (proxyUrlStr == null) {
+            throw new ServletException("-D" + PROXY_TO + " must be specified");
+        }
+        setProxyUrl(new URL(proxyUrlStr));
+    }
+
+
+    @Override
+    public void init() throws ServletException {
+        super.init();
+        try {
+            initProxyUrl();
+        } catch (MalformedURLException e) {
+            throw new ServletException(e);
+        }
+    }
+
+
+    @Override
+    public void sendProxyRequest(HttpServletRequest request, HttpServletResponse response, Request proxyRequest) {
+
+        @SuppressWarnings("unchecked")
+        Enumeration<String> headerNames = request.getHeaderNames();
+        while (headerNames.hasMoreElements()) {
+            String headerName = headerNames.nextElement();
+            if (!proxyRequest.getHeaders().containsKey(headerName)) {
+                String headerVal = request.getHeader(headerName);
+                proxyRequest.header(headerName, headerVal);
+            }
+        }
+        proxyRequest.getHeaders().remove(HttpHeader.HOST);
+        super.sendProxyRequest(request, response, proxyRequest);
+
+    }
+
+    @Override
+    protected HttpClient newHttpClient() {
+        // ioverride parent method to be able to create a secured client as well.
+        boolean isSecureClient = (
+                proxyUrl.getProtocol() != null &&
+                        proxyUrl.getProtocol().equalsIgnoreCase(HttpScheme.HTTPS.toString()));
+        if ((isSecureClient)) {
+            String trustAll = System.getProperty(TRUST_ALL);
+            SslContextFactory sslContextFactory = null;
+            if (trustAll != null && Boolean.parseBoolean(trustAll) == Boolean.TRUE) {
+                sslContextFactory = new SslContextFactory.Client(true);
+            } else {
+                sslContextFactory = new SslContextFactory.Client(false);
+                // setting up truststore
+                sslContextFactory.setTrustStorePath(System.getProperty(TRUSTSTORE_PATH));
+                sslContextFactory.setTrustStorePassword(System.getProperty(TRUSTSTORE_P));
+                sslContextFactory.setTrustStoreType(System.getProperty(TRUSTSTORE_TYPE));
+                // setting up keystore
+                sslContextFactory.setKeyStorePath(System.getProperty(KEYSTORE_PATH));
+                sslContextFactory.setKeyStorePassword(System.getProperty(KEYSTORE_P));
+                sslContextFactory.setKeyStoreType(System.getProperty(KEYSTORE_TYPE));
+                sslContextFactory.setKeyManagerPassword(System.getProperty(KEYMANAGER_P));
+
+                if (System.getProperty(ENDPOINT_IDENTIFICATION_ALGORITHM) != null &&
+                        !System.getProperty(ENDPOINT_IDENTIFICATION_ALGORITHM).equals("")) {
+                    sslContextFactory
+                            .setEndpointIdentificationAlgorithm(System.getProperty(ENDPOINT_IDENTIFICATION_ALGORITHM));
+                }
+
+                if (System.getProperty(KEYSTORE_CYPHER) != null &&
+                        !System.getProperty(KEYSTORE_CYPHER).equals("")) {
+                    sslContextFactory.setIncludeCipherSuites(System.getProperty(KEYSTORE_CYPHER));
+                }
+            }
+
+            return new HttpClient(sslContextFactory);
+
+        } else {
+            return super.newHttpClient();
+        }
+
+    }
+
+    @Override
+    protected HttpClient createHttpClient() throws ServletException {
+
+        try {
+            initProxyUrl();
+        } catch (MalformedURLException e) {
+            throw new ServletException(e);
+        }
+        // calling the parent and setting the configuration for our implementation
+        HttpClient client = super.createHttpClient();
+        setTimeout(TIMEOUT);
+        client.setIdleTimeout(TIMEOUT);
+        client.setStopTimeout(TIMEOUT);
+        if (System.getProperty(MAX_POOL_CONNECTIONS) != null) {
+            client.setMaxConnectionsPerDestination(
+                    Integer.valueOf(System.getProperty(MAX_POOL_CONNECTIONS)));
+        }
+        return client;
+
+    }
+
+
+
+    @Override
+    protected String rewriteTarget(HttpServletRequest request) {
+
+        String path = proxyUrl.getPath();
+        if (request.getServletPath() != null) {
+            path += request.getServletPath();
+        }
+        if (request.getPathInfo() != null) {
+            path += request.getPathInfo();
+        }
+
+        return URIUtil.newURI(
+                proxyUrl.getProtocol(),
+                proxyUrl.getHost(),
+                proxyUrl.getPort(),
+                path,
+                request.getQueryString());
+    }
+
+}
index a58e127..279b405 100644 (file)
@@ -5,14 +5,13 @@
          version="4.0">
 
     <servlet>
-        <servlet-name>Transparent Proxy</servlet-name>
-        <servlet-class>org.onap.workflow.web.TransparentProxy</servlet-class>
+        <servlet-name>Backend Proxy</servlet-name>
+        <servlet-class>org.onap.workflow.web.SSLProxyServlet</servlet-class>
         <load-on-startup>1</load-on-startup>
         <async-supported>true</async-supported>
     </servlet>
-
     <servlet-mapping>
-        <servlet-name>Transparent Proxy</servlet-name>
+        <servlet-name>Backend Proxy</servlet-name>
         <url-pattern>/wf/*</url-pattern>
         <url-pattern>/v1.0/activity-spec/*</url-pattern>
     </servlet-mapping>