2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.webseal.simulator;
23 import org.apache.http.Header;
24 import org.apache.http.client.methods.*;
25 import org.apache.http.config.Registry;
26 import org.apache.http.config.RegistryBuilder;
27 import org.apache.http.conn.socket.ConnectionSocketFactory;
28 import org.apache.http.conn.socket.PlainConnectionSocketFactory;
29 import org.apache.http.conn.ssl.NoopHostnameVerifier;
30 import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
31 import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
32 import org.apache.http.entity.ContentType;
33 import org.apache.http.entity.InputStreamEntity;
34 import org.apache.http.impl.client.CloseableHttpClient;
35 import org.apache.http.impl.client.HttpClients;
36 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
37 import org.apache.http.ssl.SSLContextBuilder;
38 import org.apache.logging.log4j.LogManager;
39 import org.apache.logging.log4j.Logger;
40 import org.openecomp.sdc.webseal.simulator.conf.Conf;
42 import javax.net.ssl.SSLContext;
43 import javax.servlet.RequestDispatcher;
44 import javax.servlet.ServletConfig;
45 import javax.servlet.ServletException;
46 import javax.servlet.ServletInputStream;
47 import javax.servlet.http.Cookie;
48 import javax.servlet.http.HttpServlet;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.io.OutputStream;
54 import java.io.UnsupportedEncodingException;
55 import java.net.MalformedURLException;
57 import java.net.URLEncoder;
58 import java.security.KeyStoreException;
59 import java.security.NoSuchAlgorithmException;
61 import java.util.stream.Collectors;
62 import java.util.zip.GZIPInputStream;
64 public class SdcProxy extends HttpServlet {
66 private static final long serialVersionUID = 1L;
67 private static URL url;
68 private CloseableHttpClient httpClient;
70 private final String SDC1 = "/sdc1";
71 private final String ONBOARDING = "/onboarding/";
72 private final String SCRIPTS = "/scripts";
73 private final String STYLES = "/styles";
74 private final String LANGUAGES = "/languages";
75 private final String CONFIGURATIONS = "/configurations";
76 private static final Set<String> RESERVED_HEADERS = Arrays.stream(ReservedHeaders.values()).map(h -> h.getValue()).collect(Collectors.toSet());
79 private final static Logger logger = LogManager.getLogger(SdcProxy.class);
81 public void init(ServletConfig config) throws ServletException {
83 conf = Conf.getInstance();
85 String feHost = conf.getFeHost();
86 url = new URL(feHost);
87 } catch (MalformedURLException me) {
88 throw new ServletException("Proxy URL is invalid", me);
92 httpClient = buildRestClient();
93 } catch (Exception e) {
94 throw new ServletException("Build rest client failed", e);
98 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
99 proxy(request, response, MethodEnum.GET);
102 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
104 String userId = request.getParameter("userId");
105 String password = request.getParameter("password");
108 if (userId == null) {
109 userId = request.getHeader("USER_ID");
112 System.out.println("SdcProxy -> doPost userId=" + userId);
113 request.setAttribute("message", "OK");
114 if (password != null && getUser(userId, password) == null) {
115 MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
116 RequestDispatcher view = request.getRequestDispatcher("login");
117 request.setAttribute("message", "ERROR: userid or password incorect");
118 view.forward(mutableRequest, response);
120 System.out.println("SdcProxy -> doPost going to doGet");
121 request.setAttribute("HTTP_IV_USER", userId);
122 proxy(request, response, MethodEnum.POST);
126 public void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
127 proxy(request, response, MethodEnum.PUT);
130 public void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
131 proxy(request, response, MethodEnum.DELETE);
134 private synchronized void proxy(HttpServletRequest request, HttpServletResponse response, MethodEnum methodEnum) throws IOException, UnsupportedEncodingException {
136 Map<String, String[]> requestParameters = request.getParameterMap();
137 String userIdHeader = getUseridFromRequest(request);
138 User user = getUser(userIdHeader);
140 // new request - forward to login page
141 if (userIdHeader == null) {
142 System.out.print("Going to login");
143 response.sendRedirect("/login");
147 String uri = getUri(request, requestParameters);
148 HttpRequestBase httpMethod = createHttpMethod(request, methodEnum, uri);
149 addHeadersToMethod(httpMethod, user, request);
151 try (CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpMethod)){;
152 response.setStatus(closeableHttpResponse.getStatusLine().getStatusCode());
153 if (request.getRequestURI().indexOf(".svg") > -1) {
154 response.setContentType("image/svg+xml");
157 if(closeableHttpResponse.getEntity() != null) {
158 InputStream responseBodyStream = closeableHttpResponse.getEntity().getContent();
159 Header contentEncodingHeader = closeableHttpResponse.getLastHeader("Content-Encoding");
160 if (contentEncodingHeader != null && contentEncodingHeader.getValue().equalsIgnoreCase("gzip")) {
161 responseBodyStream = new GZIPInputStream(responseBodyStream);
163 write(responseBodyStream, response.getOutputStream());
168 private User getUser(String userId, String password) {
169 User user = getUser(userId);
170 if (user.getPassword().equals(password)) {
176 private User getUser(String userId) {
177 return conf.getUsers().get(userId);
181 private List<String> getContextPaths() {
182 List<String> contextPaths = new ArrayList<>();
183 contextPaths.add(SDC1);
184 contextPaths.add(ONBOARDING);
185 contextPaths.add(STYLES);
186 contextPaths.add(SCRIPTS);
187 contextPaths.add(LANGUAGES);
188 contextPaths.add(CONFIGURATIONS);
192 private String getUri(HttpServletRequest request, Map<String, String[]> requestParameters) throws UnsupportedEncodingException {
193 String suffix = request.getRequestURI();
194 if (getContextPaths().stream().anyMatch(request.getRequestURI()::contains)) {
195 suffix = alignUrlProxy(suffix);
197 StringBuilder query = alignUrlParameters(requestParameters);
198 String uri = String.format("%s%s", new Object[]{this.url.toString() + suffix, query.toString()});
202 private HttpRequestBase createHttpMethod(HttpServletRequest request, MethodEnum methodEnum, String uri) throws IOException {
203 HttpRequestBase proxyMethod = null;
204 ServletInputStream inputStream = null;
205 InputStreamEntity entity = null;
207 switch (methodEnum) {
209 proxyMethod = new HttpGet(uri);
212 proxyMethod = new HttpPost(uri);
213 inputStream = request.getInputStream();
214 entity = new InputStreamEntity(inputStream, getContentType(request));
215 ((HttpPost) proxyMethod).setEntity(entity);
218 proxyMethod = new HttpPut(uri);
219 inputStream = request.getInputStream();
220 entity = new InputStreamEntity(inputStream, getContentType(request));
221 ((HttpPut) proxyMethod).setEntity(entity);
224 proxyMethod = new HttpDelete(uri);
230 private ContentType getContentType(HttpServletRequest request) {
231 String contentTypeStr = request.getContentType();
232 if (contentTypeStr == null ){
233 contentTypeStr = request.getHeader("contentType");
235 ContentType contentType = ContentType.parse(contentTypeStr);
236 return ContentType.create(contentType.getMimeType());
239 private String getUseridFromRequest(HttpServletRequest request) {
241 String userIdHeader = request.getHeader("USER_ID");
242 if (userIdHeader != null) {
245 Object o = request.getAttribute("HTTP_IV_USER");
249 Cookie[] cookies = request.getCookies();
251 if (cookies != null) {
252 for (int i = 0; i < cookies.length; ++i) {
253 if (cookies[i].getName().equals("USER_ID")) {
254 userIdHeader = cookies[i].getValue();
261 private static void addHeadersToMethod(HttpUriRequest proxyMethod, User user, HttpServletRequest request) {
263 proxyMethod.setHeader(ReservedHeaders.HTTP_IV_USER.name(), user.getUserId());
264 proxyMethod.setHeader(ReservedHeaders.USER_ID.name(), user.getUserId());
265 proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_FIRSTNAME.name(), user.getFirstName());
266 proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), user.getEmail());
267 proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_LASTNAME.name(), user.getLastName());
268 proxyMethod.setHeader(ReservedHeaders.HTTP_IV_REMOTE_ADDRESS.name(), "0.0.0.0");
269 proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_WSTYPE.name(), "Intranet");
270 proxyMethod.setHeader(ReservedHeaders.HTTP_CSP_EMAIL.name(), "me@mail.com");
272 Enumeration<String> headerNames = request.getHeaderNames();
273 while (headerNames.hasMoreElements()) {
274 String headerName = headerNames.nextElement();
275 if (!RESERVED_HEADERS.contains(headerName)) {
276 Enumeration<String> headers = request.getHeaders(headerName);
277 while (headers.hasMoreElements()) {
278 String headerValue = headers.nextElement();
279 proxyMethod.setHeader(headerName, headerValue);
285 private String alignUrlProxy(String requestURI) {
287 int i = requestURI.indexOf(ONBOARDING);
289 return requestURI.substring(i);
292 i = requestURI.indexOf(SDC1 + SDC1);
294 return requestURI.substring(SDC1.length());
297 i = requestURI.indexOf(SDC1);
302 return SDC1 + requestURI;
305 private static StringBuilder alignUrlParameters(Map<String, String[]> requestParameters) throws UnsupportedEncodingException {
306 StringBuilder query = new StringBuilder();
307 for (String name : requestParameters.keySet()) {
308 for (String value : (String[]) requestParameters.get(name)) {
309 if (query.length() == 0) {
314 name = URLEncoder.encode(name, "UTF-8");
315 value = URLEncoder.encode(value, "UTF-8");
317 query.append(String.format("&%s=%s", new Object[]{name, value}));
323 private void write(InputStream inputStream, OutputStream outputStream) throws IOException {
325 while (inputStream != null && (b = inputStream.read()) != -1) {
326 outputStream.write(b);
328 outputStream.flush();
331 public String getServletInfo() {
332 return "Http Proxy Servlet";
335 enum ReservedHeaders {
336 HTTP_IV_USER("HTTP_IV_USER"), USER_ID("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");
338 private String value;
340 ReservedHeaders(String value) {
344 public String getValue() {
350 private static CloseableHttpClient buildRestClient() throws NoSuchAlgorithmException, KeyStoreException {
351 SSLContextBuilder builder = new SSLContextBuilder();
352 builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
353 SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
354 NoopHostnameVerifier.INSTANCE);
355 Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
356 .register("http", new PlainConnectionSocketFactory())
357 .register("https", sslsf)
359 PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
360 return HttpClients.custom()
361 .setSSLSocketFactory(sslsf)
362 .setConnectionManager(cm)