diff options
Diffstat (limited to 'utils')
8 files changed, 346 insertions, 547 deletions
diff --git a/utils/webseal-simulator/pom.xml b/utils/webseal-simulator/pom.xml index b9f541bd5f..c55044c7cd 100644 --- a/utils/webseal-simulator/pom.xml +++ b/utils/webseal-simulator/pom.xml @@ -37,12 +37,18 @@ <scope>compile</scope> </dependency> + <!--<dependency>--> + <!--<groupId>commons-httpclient</groupId>--> + <!--<artifactId>commons-httpclient</artifactId>--> + <!--<version>3.1</version>--> + <!--</dependency>--> <dependency> - <groupId>commons-httpclient</groupId> - <artifactId>commons-httpclient</artifactId> - <version>3.1</version> + <groupId>org.apache.httpcomponents</groupId> + <artifactId>httpclient</artifactId> + <version>4.5.2</version> </dependency> + <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging-api</artifactId> @@ -84,6 +90,14 @@ <scope>compile</scope> </dependency> + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <version>1.2.17</version> + <scope>compile</scope> + </dependency> + + </dependencies> <build> <finalName>WSSimulator-${project.version}</finalName> @@ -168,11 +182,6 @@ </includes> <followSymlinks>false</followSymlinks> </fileset> - <fileset> - <directory>${project.basedir}/sdc-simulator/chef-repo/cookbooks/sdc-simulator/files/default</directory> - <includes>logback.xml</includes> - <followSymlinks>false</followSymlinks> - </fileset> </filesets> </configuration> </execution> @@ -200,24 +209,6 @@ </resources> </configuration> </execution> - <execution> - <id>copy-configurations-simulator</id> - <phase>verify</phase> - <goals> - <goal>copy-resources</goal> - </goals> - <configuration> - <outputDirectory>${basedir}/sdc-simulator/chef-repo/cookbooks/sdc-simulator/files/default</outputDirectory> - <resources> - <resource> - <directory>${basedir}/src/main/resources</directory> - <includes> - <include>logback.xml</include> - </includes> - </resource> - </resources> - </configuration> - </execution> </executions> </plugin> diff --git a/utils/webseal-simulator/sdc-simulator/Dockerfile b/utils/webseal-simulator/sdc-simulator/Dockerfile index ca74a81484..d88d01a053 100644 --- a/utils/webseal-simulator/sdc-simulator/Dockerfile +++ b/utils/webseal-simulator/sdc-simulator/Dockerfile @@ -4,7 +4,7 @@ COPY chef-solo /root/chef-solo/ COPY chef-repo/cookbooks /root/chef-solo/cookbooks/ -RUN cp ${JETTY_HOME}/resources/log4j.properties ${JETTY_BASE}/resources/log4j.properties +#RUN cp ${JETTY_HOME}/resources/log4j.properties ${JETTY_BASE}/resources/log4j.properties ADD WSSimulator*.war ${JETTY_BASE}/webapps/ diff --git a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/files/default/log4j.properties b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/files/default/log4j.properties new file mode 100644 index 0000000000..4bf9084d14 --- /dev/null +++ b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/files/default/log4j.properties @@ -0,0 +1,26 @@ +# Define the root logger with appender file +log4j.rootLogger = INFO, FILE, stdout + +# Define the file appender +log4j.appender.FILE=org.apache.log4j.RollingFileAppender +log4j.appender.FILE.File=logs/ws-log.out + +# Define the layout for file appender +log4j.appender.FILE.layout=org.apache.log4j.PatternLayout +log4j.appender.FILE.layout.conversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p [%10c] : %m%n + +# Set the maximum file size before rollover +log4j.appender.FILE.maxFileSize=5MB + +# Set the the backup index +log4j.appender.FILE.maxBackupIndex=10 + + +############################################################# + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +#log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n +log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %10c:%L - %m%n diff --git a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_3_logback.rb b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_3_logback.rb index 0d9282b28a..7a2069ddfb 100644 --- a/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_3_logback.rb +++ b/utils/webseal-simulator/sdc-simulator/chef-repo/cookbooks/sdc-simulator/recipes/SDC_Simulator_3_logback.rb @@ -1,9 +1,8 @@ jetty_base="/var/lib/jetty" - -cookbook_file "logback.xml" do - path "#{jetty_base}/config/sdc-simulator/logback.xml" - source "logback.xml" +cookbook_file "log4j.properties" do + path "#{jetty_base}/config/sdc-simulator/log4j.properties" + source "log4j.properties" owner "jetty" group "jetty" mode "0755" diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java deleted file mode 100644 index 30d98146c2..0000000000 --- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummySSLProtocolSocketFactory.java +++ /dev/null @@ -1,115 +0,0 @@ - -package org.openecomp.sdc.webseal.simulator.SSL; - -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.commons.httpclient.HttpClientError; -import org.apache.commons.httpclient.params.HttpConnectionParams; -import org.apache.commons.httpclient.protocol.ControllerThreadSocketFactory; -import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import java.io.IOException; -import java.net.InetAddress; -import java.net.Socket; -import java.net.UnknownHostException; - -public class DummySSLProtocolSocketFactory implements SecureProtocolSocketFactory { - - - private SSLContext sslcontext = null; - - /** - * Constructor for DummySSLProtocolSocketFactory. - */ - public DummySSLProtocolSocketFactory() { - super(); - } - - private static SSLContext createEasySSLContext() { - try { - SSLContext context = SSLContext.getInstance("SSL"); - context.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null); - return context; - } catch (Exception e) { - throw new HttpClientError(e.toString()); - } - } - - private SSLContext getSSLContext() { - if (this.sslcontext == null) { - this.sslcontext = createEasySSLContext(); - } - return this.sslcontext; - } - - /** - * @see org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory#createSocket(String,int,InetAddress,int) - */ - public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, - UnknownHostException { - - return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort); - } - - /** - * Attempts to get a new socket connection to the given host within the given - * time limit. - * <p> - * To circumvent the limitations of older JREs that do not support connect - * timeout a controller thread is executed. The controller thread attempts to - * create a new socket within the given limit of time. If socket constructor - * does not return until the timeout expires, the controller terminates and - * throws an {@link ConnectTimeoutException} - * </p> - * - * @param host the host name/IP - * @param port the port on the host - * @param localAddress the local host name/IP to bind the socket to - * @param localPort the port on the local machine - * @param params {@link HttpConnectionParams Http connection parameters} - * - * @return Socket a new socket - * - * @throws IOException if an I/O error occurs while creating the socket - * @throws UnknownHostException if the IP address of the host cannot be - * determined - */ - public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, - final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { - if (params == null) { - throw new IllegalArgumentException("Parameters may not be null"); - } - int timeout = params.getConnectionTimeout(); - if (timeout == 0) { - return createSocket(host, port, localAddress, localPort); - } else { - // To be eventually deprecated when migrated to Java 1.4 or above - return ControllerThreadSocketFactory.createSocket(this, host, port, localAddress, localPort, timeout); - } - } - - /** - * @see org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory#createSocket(String,int) - */ - public Socket createSocket(String host, int port) throws IOException, UnknownHostException { - return getSSLContext().getSocketFactory().createSocket(host, port); - } - - /** - * @see org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory#createSocket(Socket,String,int,boolean) - */ - public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, - UnknownHostException { - return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); - } - - public boolean equals(Object obj) { - return ((obj != null) && obj.getClass().equals(DummySSLProtocolSocketFactory.class)); - } - - public int hashCode() { - return DummySSLProtocolSocketFactory.class.hashCode(); - } - -}
\ No newline at end of file diff --git a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java b/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java deleted file mode 100644 index df7a1d2b65..0000000000 --- a/utils/webseal-simulator/src/main/java/org/openecomp/sdc/webseal/simulator/SSL/DummyX509TrustManager.java +++ /dev/null @@ -1,62 +0,0 @@ - -package org.openecomp.sdc.webseal.simulator.SSL; - -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -public class DummyX509TrustManager implements X509TrustManager -{ - private X509TrustManager standardTrustManager = null; - - /** - * Constructor for DummyX509TrustManager. - */ - public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { - super(); - String algo = TrustManagerFactory.getDefaultAlgorithm(); - TrustManagerFactory factory = TrustManagerFactory.getInstance(algo); - factory.init(keystore); - TrustManager[] trustmanagers = factory.getTrustManagers(); - if (trustmanagers.length == 0) { - throw new NoSuchAlgorithmException(algo + " trust manager not supported"); - } - this.standardTrustManager = (X509TrustManager)trustmanagers[0]; - } - - /** - * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[], String) - */ - public boolean isClientTrusted(X509Certificate[] certificates) { - return true; - } - - /** - * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], String) - */ - public boolean isServerTrusted(X509Certificate[] certificates) { - return true; - } - - /** - * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() - */ - public X509Certificate[] getAcceptedIssuers() { - return this.standardTrustManager.getAcceptedIssuers(); - } - - public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - // do nothing - - } - - public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { - // do nothing - - } -}
\ No newline at end of file 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 7a3b9bc692..7fbc8ac99f 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 @@ -1,239 +1,244 @@ package org.openecomp.sdc.webseal.simulator; -import java.io.BufferedReader; +import org.apache.http.Header; +import org.apache.http.client.methods.*; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +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.entity.ContentType; +import org.apache.http.entity.InputStreamEntity; +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.apache.log4j.Logger; +import org.openecomp.sdc.webseal.simulator.conf.Conf; + +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.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Enumeration; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.util.*; import java.util.stream.Collectors; import java.util.zip.GZIPInputStream; -import javax.net.ssl.X509TrustManager; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethodBase; -import org.apache.commons.httpclient.methods.DeleteMethod; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.commons.httpclient.methods.InputStreamRequestEntity; -import org.apache.commons.httpclient.methods.PostMethod; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.protocol.Protocol; -import org.openecomp.sdc.webseal.simulator.SSL.DummySSLProtocolSocketFactory; -import org.openecomp.sdc.webseal.simulator.conf.Conf; public class SdcProxy extends HttpServlet { - private static final long serialVersionUID = 1L; - private URL url; - private HttpClient proxy; - private Conf conf; - - private final String SDC1 = "/sdc1"; - private final String ONBOARDING = "/onboarding/"; - private final String SCRIPTS = "/scripts"; - private final String STYLES = "/styles"; - private final String LANGUAGES = "/languages"; - private final String CONFIGURATIONS = "/configurations"; - - private static final Set<String> RESERVED_HEADERS = Arrays.stream(ReservedHeaders.values()).map(h -> h.name()).collect(Collectors.toSet()); - - public void init(ServletConfig config) throws ServletException { - super.init(config); - conf = Conf.getInstance(); - try { - String feHost = conf.getFeHost(); - this.url = new URL(feHost); - } catch (MalformedURLException me) { - throw new ServletException("Proxy URL is invalid", me); - } - // Set up an HTTPS socket factory that accepts self-signed certs. - Protocol https = new Protocol("https", - new DummySSLProtocolSocketFactory(), 9443); - Protocol.registerProtocol("https", https); - - this.proxy = new HttpClient(); - this.proxy.getHostConfiguration().setHost(this.url.getHost()); - - - - } - - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - proxy(request, response, MethodEnum.GET); - } - - public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - String userId = request.getParameter("userId"); - String password = request.getParameter("password"); - - // Already sign-in - if (userId == null){ - userId = request.getHeader("USER_ID"); - } - - System.out.println("SdcProxy -> doPost userId=" + userId); - request.setAttribute("message", "OK"); - if (password != null && getUser(userId, password) == null) { - MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request); - RequestDispatcher view = request.getRequestDispatcher("login"); - request.setAttribute("message", "ERROR: userid or password incorect"); - view.forward(mutableRequest, response); - } else { - System.out.println("SdcProxy -> doPost going to doGet"); - request.setAttribute("HTTP_IV_USER", userId); - proxy(request, response, MethodEnum.POST); - } - } - - public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - proxy(request, response, MethodEnum.PUT); - } - - public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - proxy(request, response, MethodEnum.DELETE); - } - - private synchronized void proxy(HttpServletRequest request, HttpServletResponse response, MethodEnum methodEnum) throws IOException, UnsupportedEncodingException, HttpException { - Map<String, String[]> requestParameters = request.getParameterMap(); - System.out.print(request.getRequestURI() + " -> "); - - String userIdHeader = getUseridFromRequest(request); - - // new request - forward to login page - if (userIdHeader == null) { - System.out.print("Going to login"); - response.sendRedirect("/login"); - return; - } - - String uri = getUri(request, requestParameters); - HttpMethodBase proxyMethod = createHttpMethod(request, methodEnum, uri); - System.out.println(uri); - - User user = getUser(userIdHeader); - addHeadersToMethod(proxyMethod, user, request); - this.proxy.executeMethod(proxyMethod); - response.setStatus(proxyMethod.getStatusCode()); - - if (request.getRequestURI().indexOf(".svg") > -1) { - response.setContentType("image/svg+xml"); - } - - InputStream responseBodyStream = proxyMethod.getResponseBodyAsStream(); - Header contentEncodingHeader = proxyMethod.getResponseHeader("Content-Encoding"); - if (contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip")) { - responseBodyStream = new GZIPInputStream(responseBodyStream); - } - write(responseBodyStream, response.getOutputStream()); - } - - private User getUser(String userId, String password) { - User user = getUser(userId); - if (user.getPassword().equals(password)) { - return user; - } - return null; - } - - private User getUser(String userId) { - return conf.getUsers().get(userId); - - } - - private List<String> getContextPaths(){ - List<String> contextPaths = new ArrayList<>(); - contextPaths.add(SDC1); - contextPaths.add(ONBOARDING); - contextPaths.add(STYLES); - contextPaths.add(SCRIPTS); - contextPaths.add(LANGUAGES); - contextPaths.add(CONFIGURATIONS); - return contextPaths; - } - - private String getUri(HttpServletRequest request, Map<String, String[]> requestParameters) throws UnsupportedEncodingException { - String suffix = request.getRequestURI(); - if (getContextPaths().stream().anyMatch(request.getRequestURI()::contains)) { - suffix = alignUrlProxy(suffix); - } - StringBuilder query = alignUrlParameters(requestParameters); - String uri = String.format("%s%s", new Object[] {this.url.toString() + suffix, query.toString() }); - return uri; - } - - private HttpMethodBase createHttpMethod(HttpServletRequest request, MethodEnum methodEnum, String uri) throws IOException { - HttpMethodBase proxyMethod = null; - switch (methodEnum) { - case GET: - proxyMethod = new GetMethod(uri); - break; - case POST: - proxyMethod = new PostMethod(uri); - ((PostMethod) proxyMethod).setRequestEntity(new InputStreamRequestEntity(request.getInputStream())); - break; - case PUT: - proxyMethod = new PutMethod(uri); - ((PutMethod) proxyMethod).setRequestBody(getBody(request)); - break; - case DELETE: - proxyMethod = new DeleteMethod(uri); - break; - } - return proxyMethod; - } - - private String getUseridFromRequest(HttpServletRequest request) { - - String userIdHeader = request.getHeader("USER_ID"); - if (userIdHeader != null){ - return userIdHeader; - } - Object o = request.getAttribute("HTTP_IV_USER"); - if (o != null) { - return o.toString(); - } - Cookie[] cookies = request.getCookies(); - - if (cookies != null){ - for (int i=0; i<cookies.length; ++i){ - if (cookies[i].getName().equals("USER_ID")){ - userIdHeader = cookies[i].getValue(); - } - } - } - return userIdHeader; - } - - private void addHeadersToMethod(HttpMethodBase proxyMethod, User user, HttpServletRequest request) { - - proxyMethod.addRequestHeader(ReservedHeaders.HTTP_IV_USER.name(), user.getUserId()); - proxyMethod.addRequestHeader(ReservedHeaders.USER_ID.name(), user.getUserId()); - proxyMethod.addRequestHeader(ReservedHeaders.HTTP_CSP_FIRSTNAME.name(), user.getFirstName()); - proxyMethod.addRequestHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), user.getEmail()); - proxyMethod.addRequestHeader(ReservedHeaders.HTTP_CSP_LASTNAME.name(), user.getLastName()); - proxyMethod.addRequestHeader(ReservedHeaders.HTTP_IV_REMOTE_ADDRESS.name(), "0.0.0.0"); - proxyMethod.addRequestHeader(ReservedHeaders.HTTP_CSP_WSTYPE.name(), "Intranet"); - proxyMethod.addRequestHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), "me@mail.com"); + private static final long serialVersionUID = 1L; + private static URL url; + private CloseableHttpClient httpClient; + private Conf conf; + private final String SDC1 = "/sdc1"; + private final String ONBOARDING = "/onboarding/"; + private final String SCRIPTS = "/scripts"; + private final String STYLES = "/styles"; + private final String LANGUAGES = "/languages"; + private final String CONFIGURATIONS = "/configurations"; + private static final Set<String> RESERVED_HEADERS = Arrays.stream(ReservedHeaders.values()).map(h -> h.name()).collect(Collectors.toSet()); + + + private final static Logger logger = Logger.getLogger(SdcProxy.class); + + public void init(ServletConfig config) throws ServletException { + super.init(config); + conf = Conf.getInstance(); + try { + String feHost = conf.getFeHost(); + url = new URL(feHost); + } catch (MalformedURLException me) { + throw new ServletException("Proxy URL is invalid", me); + } + + try { + httpClient = buildRestClient(); + } catch (Exception e) { + throw new ServletException("Build rest client failed", e); + } + } + + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + proxy(request, response, MethodEnum.GET); + } + + public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + + String userId = request.getParameter("userId"); + String password = request.getParameter("password"); + + // Already sign-in + if (userId == null) { + userId = request.getHeader("USER_ID"); + } + + System.out.println("SdcProxy -> doPost userId=" + userId); + request.setAttribute("message", "OK"); + if (password != null && getUser(userId, password) == null) { + MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request); + RequestDispatcher view = request.getRequestDispatcher("login"); + request.setAttribute("message", "ERROR: userid or password incorect"); + view.forward(mutableRequest, response); + } else { + System.out.println("SdcProxy -> doPost going to doGet"); + request.setAttribute("HTTP_IV_USER", userId); + proxy(request, response, MethodEnum.POST); + } + } + + public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + proxy(request, response, MethodEnum.PUT); + } + + public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + proxy(request, response, MethodEnum.DELETE); + } + + private synchronized void proxy(HttpServletRequest request, HttpServletResponse response, MethodEnum methodEnum) throws IOException, UnsupportedEncodingException { + + Map<String, String[]> requestParameters = request.getParameterMap(); + String userIdHeader = getUseridFromRequest(request); + User user = getUser(userIdHeader); + + // new request - forward to login page + if (userIdHeader == null) { + System.out.print("Going to login"); + response.sendRedirect("/login"); + return; + } + + String uri = getUri(request, requestParameters); + HttpRequestBase httpMethod = createHttpMethod(request, methodEnum, uri); + addHeadersToMethod(httpMethod, user, request); + + try (CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpMethod)){; + response.setStatus(closeableHttpResponse.getStatusLine().getStatusCode()); + if (request.getRequestURI().indexOf(".svg") > -1) { + response.setContentType("image/svg+xml"); + } + + InputStream responseBodyStream = closeableHttpResponse.getEntity().getContent(); + Header contentEncodingHeader = closeableHttpResponse.getLastHeader("Content-Encoding"); + if (contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip")) { + responseBodyStream = new GZIPInputStream(responseBodyStream); + } + write(responseBodyStream, response.getOutputStream()); + + } + } + + private User getUser(String userId, String password) { + User user = getUser(userId); + if (user.getPassword().equals(password)) { + return user; + } + return null; + } + + private User getUser(String userId) { + return conf.getUsers().get(userId); + + } + + private List<String> getContextPaths() { + List<String> contextPaths = new ArrayList<>(); + contextPaths.add(SDC1); + contextPaths.add(ONBOARDING); + contextPaths.add(STYLES); + contextPaths.add(SCRIPTS); + contextPaths.add(LANGUAGES); + contextPaths.add(CONFIGURATIONS); + return contextPaths; + } + + private String getUri(HttpServletRequest request, Map<String, String[]> requestParameters) throws UnsupportedEncodingException { + String suffix = request.getRequestURI(); + if (getContextPaths().stream().anyMatch(request.getRequestURI()::contains)) { + suffix = alignUrlProxy(suffix); + } + StringBuilder query = alignUrlParameters(requestParameters); + String uri = String.format("%s%s", new Object[]{this.url.toString() + suffix, query.toString()}); + return uri; + } + + private HttpRequestBase createHttpMethod(HttpServletRequest request, MethodEnum methodEnum, String uri) throws IOException { + HttpRequestBase proxyMethod = null; + ServletInputStream inputStream = null; + InputStreamEntity entity = null; + + String contentType = request.getContentType(); + ContentType myContent = ContentType.create(contentType); + switch (methodEnum) { + case GET: + proxyMethod = new HttpGet(uri); + break; + case POST: + proxyMethod = new HttpPost(uri); + inputStream = request.getInputStream(); + entity = new InputStreamEntity(inputStream, myContent); + ((HttpPost) proxyMethod).setEntity(entity); + break; + case PUT: + proxyMethod = new HttpPut(uri); + inputStream = request.getInputStream(); + entity = new InputStreamEntity(inputStream, myContent); + ((HttpPut) proxyMethod).setEntity(entity); + break; + case DELETE: + proxyMethod = new HttpDelete(uri); + break; + } + return proxyMethod; + } + + private String getUseridFromRequest(HttpServletRequest request) { + + String userIdHeader = request.getHeader("USER_ID"); + if (userIdHeader != null) { + return userIdHeader; + } + Object o = request.getAttribute("HTTP_IV_USER"); + if (o != null) { + return o.toString(); + } + Cookie[] cookies = request.getCookies(); + + if (cookies != null) { + for (int i = 0; i < cookies.length; ++i) { + if (cookies[i].getName().equals("USER_ID")) { + userIdHeader = cookies[i].getValue(); + } + } + } + return userIdHeader; + } + + private static void addHeadersToMethod(HttpUriRequest proxyMethod, User user, HttpServletRequest request) { + + proxyMethod.setHeader(ReservedHeaders.HTTP_IV_USER.name(), user.getUserId()); + proxyMethod.setHeader(ReservedHeaders.USER_ID.name(), user.getUserId()); + proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_FIRSTNAME.name(), user.getFirstName()); + proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), user.getEmail()); + proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_LASTNAME.name(), user.getLastName()); + proxyMethod.setHeader(ReservedHeaders.HTTP_IV_REMOTE_ADDRESS.name(), "0.0.0.0"); + proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_WSTYPE.name(), "Intranet"); + proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), "me@mail.com"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { @@ -242,112 +247,79 @@ public class SdcProxy extends HttpServlet { Enumeration<String> headers = request.getHeaders(headerName); while (headers.hasMoreElements()) { String headerValue = headers.nextElement(); - proxyMethod.addRequestHeader(headerName, headerValue); +// proxyMethod.setHeader(headerName, headerValue); } } } - } - - private String alignUrlProxy(String requestURI) { - - int i = requestURI.indexOf(ONBOARDING); - if (-1 != i){ - return requestURI.substring(i); - } - - i = requestURI.indexOf(SDC1+SDC1); - if (-1 != i){ - return requestURI.substring(SDC1.length()); - } - - i = requestURI.indexOf(SDC1); - if (-1 != i){ - return requestURI; - } - - return SDC1+requestURI; - } - - private StringBuilder alignUrlParameters(Map<String, String[]> requestParameters) throws UnsupportedEncodingException { - StringBuilder query = new StringBuilder(); - for (String name : requestParameters.keySet()) { - for (String value : (String[]) requestParameters.get(name)) { - if (query.length() == 0) { - query.append("?"); - } else { - query.append("&"); - } - name = URLEncoder.encode(name, "UTF-8"); - value = URLEncoder.encode(value, "UTF-8"); - - query.append(String.format("&%s=%s", new Object[] { name, value })); - } - } - return query; - } - - private void write(InputStream inputStream, OutputStream outputStream) throws IOException { - int b; - while (inputStream != null && (b = inputStream.read()) != -1) { - outputStream.write(b); - } - outputStream.flush(); - } - - public String getServletInfo() { - return "Http Proxy Servlet"; - } - - - public String getBody(HttpServletRequest request) throws IOException { - - String body = null; - StringBuilder stringBuilder = new StringBuilder(); - BufferedReader bufferedReader = null; - - try { - InputStream inputStream = request.getInputStream(); - if (inputStream != null) { - bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); - char[] charBuffer = new char[128]; - int bytesRead = -1; - while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { - stringBuilder.append(charBuffer, 0, bytesRead); - } - } else { - stringBuilder.append(""); - } - } catch (IOException ex) { - throw ex; - } finally { - if (bufferedReader != null) { - try { - bufferedReader.close(); - } catch (IOException ex) { - throw ex; - } - } - } - - body = stringBuilder.toString(); - return body; - } - - private enum ReservedHeaders { - HTTP_IV_USER, USER_ID, HTTP_CSP_FIRSTNAME, HTTP_CSP_EMAIL, HTTP_CSP_LASTNAME, HTTP_IV_REMOTE_ADDRESS, HTTP_CSP_WSTYPE - } - - private class DefaultTrustManager implements X509TrustManager { - - @Override - public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} - - @Override - public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} - - @Override - public X509Certificate[] getAcceptedIssuers() { - return null; - } - } + } + + private String alignUrlProxy(String requestURI) { + + int i = requestURI.indexOf(ONBOARDING); + if (-1 != i) { + return requestURI.substring(i); + } + + i = requestURI.indexOf(SDC1 + SDC1); + if (-1 != i) { + return requestURI.substring(SDC1.length()); + } + + i = requestURI.indexOf(SDC1); + if (-1 != i) { + return requestURI; + } + + return SDC1 + requestURI; + } + + private static StringBuilder alignUrlParameters(Map<String, String[]> requestParameters) throws UnsupportedEncodingException { + StringBuilder query = new StringBuilder(); + for (String name : requestParameters.keySet()) { + for (String value : (String[]) requestParameters.get(name)) { + if (query.length() == 0) { + query.append("?"); + } else { + query.append("&"); + } + name = URLEncoder.encode(name, "UTF-8"); + value = URLEncoder.encode(value, "UTF-8"); + + query.append(String.format("&%s=%s", new Object[]{name, value})); + } + } + return query; + } + + private void write(InputStream inputStream, OutputStream outputStream) throws IOException { + int b; + while (inputStream != null && (b = inputStream.read()) != -1) { + outputStream.write(b); + } + outputStream.flush(); + } + + public String getServletInfo() { + return "Http Proxy Servlet"; + } + + private enum ReservedHeaders { + HTTP_IV_USER, USER_ID, HTTP_CSP_FIRSTNAME, HTTP_CSP_EMAIL, HTTP_CSP_LASTNAME, HTTP_IV_REMOTE_ADDRESS, HTTP_CSP_WSTYPE + } + + private static CloseableHttpClient buildRestClient() throws NoSuchAlgorithmException, KeyStoreException { + SSLContextBuilder builder = new SSLContextBuilder(); + builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); + SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(), + NoopHostnameVerifier.INSTANCE); + Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() + .register("http", new PlainConnectionSocketFactory()) + .register("https", sslsf) + .build(); + PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); + return HttpClients.custom() + .setSSLSocketFactory(sslsf) + .setConnectionManager(cm) + .build(); + } } diff --git a/utils/webseal-simulator/src/main/resources/logback.xml b/utils/webseal-simulator/src/main/resources/logback.xml deleted file mode 100644 index 540645f821..0000000000 --- a/utils/webseal-simulator/src/main/resources/logback.xml +++ /dev/null @@ -1,12 +0,0 @@ -<configuration > - <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> - <encoder> - <Pattern> - %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n - </Pattern> - </encoder> - </appender> - <root level="INFO"> - <appender-ref ref="STDOUT" /> - </root> -</configuration> |