Remove dead code
[sdc.git] / catalog-fe / src / main / java / org / openecomp / sdc / fe / servlets / PortalServlet.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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=========================================================
19  */
20
21 package org.openecomp.sdc.fe.servlets;
22
23 import org.onap.portalsdk.core.onboarding.exception.CipherUtilException;
24 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
25 import org.onap.sdc.security.AuthenticationCookie;
26 import org.onap.sdc.security.RepresentationUtils;
27 import org.openecomp.sdc.common.impl.MutableHttpServletRequest;
28 import org.openecomp.sdc.common.log.wrappers.Logger;
29 import org.openecomp.sdc.fe.Constants;
30 import org.openecomp.sdc.fe.config.Configuration;
31 import org.openecomp.sdc.fe.config.ConfigurationManager;
32 import org.openecomp.sdc.fe.config.FeEcompErrorManager;
33
34 import javax.servlet.RequestDispatcher;
35 import javax.servlet.ServletException;
36 import javax.servlet.http.Cookie;
37 import javax.servlet.http.HttpServlet;
38 import javax.servlet.http.HttpServletRequest;
39 import javax.servlet.http.HttpServletResponse;
40 import javax.ws.rs.GET;
41 import javax.ws.rs.Path;
42 import javax.ws.rs.core.Context;
43 import java.io.IOException;
44 import java.util.Enumeration;
45 import java.util.List;
46
47 /**
48  * Root resource (exposed at "/" path)
49  */
50 @Path("/")
51 public class PortalServlet extends HttpServlet {
52
53     private static Logger log = Logger.getLogger(PortalServlet.class.getName());
54     private static final long serialVersionUID = 1L;
55
56     public static final String MISSING_HEADERS_MSG = "Missing Headers In Request";
57     private static final String AUTHORIZATION_ERROR_MSG = "Autherization error";
58     private static final String NEW_LINE = System.getProperty("line.separator");
59
60
61     /**
62      * Entry point from ECOMP portal
63      */
64     @GET
65     @Path("/portal")
66     @Override
67     public void doGet(@Context final HttpServletRequest request, @Context final HttpServletResponse response) {
68         try {
69             addRequestHeadersUsingWebseal(request, response);
70         } catch (Exception e) {
71             FeEcompErrorManager.getInstance().logFePortalServletError("Portal Servlet");
72             log.error("Error during getting portal page", e);
73         }
74     }
75
76     /**
77      * Building new HTTP request and setting headers for the request The request
78      * will dispatch to index.html
79      *
80      * @param request
81      * @param response
82      * @throws ServletException
83      * @throws IOException
84      */
85     private void addRequestHeadersUsingWebseal(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
86
87         response.setContentType("text/html");
88
89         // Create new request object to dispatch
90         MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
91
92         // Get configuration object (reads data from configuration.yaml)
93         Configuration configuration = getConfiguration(request);
94
95         // Check if we got header from webseal
96         String userId = request.getHeader(Constants.WEBSEAL_USER_ID_HEADER);
97         if (null == userId) {
98             // Authentication via ecomp portal
99             try {
100                 String userIdFromCookie = getUserIdFromCookie(request);
101                 if (("").equals(userIdFromCookie)) {
102                     // This is probably a webseal request, so missing header in request should be printed.
103                     response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
104                 }
105                 userId = userIdFromCookie;
106             } catch (Exception e) {
107                 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
108                 log.error("Error during adding request header", e);
109             }
110         }
111
112         // Replace webseal header with open source header
113         mutableRequest.putHeader(Constants.USER_ID, userId);
114
115
116
117
118                 
119         // Getting identification headers from configuration.yaml
120         // (identificationHeaderFields) and setting them to new request
121         // mutableRequest
122         List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
123         for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
124             String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
125             setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
126         }
127
128         // Getting optional headers from configuration.yaml
129         // (optionalHeaderFields) and setting them to new request mutableRequest
130         List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
131         for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
132             String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
133             setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
134         }
135
136         // Print headers from original request for debug purposes
137         printHeaders(request);
138
139         // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
140         // Via ecomp portal do not need to check the headers.
141         boolean allHeadersExist = true;
142         if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
143             allHeadersExist = checkHeaders(mutableRequest);
144         }
145
146         if (allHeadersExist) {
147             addCookies(response, mutableRequest, getMandatoryHeaders(request));
148             addCookies(response, mutableRequest, getOptionalHeaders(request));
149                         getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME );
150                         getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME);
151
152                         //To be fixed
153                         //addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie);
154             RequestDispatcher rd = request.getRequestDispatcher("index.html");
155             rd.forward(mutableRequest, response);
156         } else {
157             response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
158         }
159     }
160
161         boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException {
162                 boolean isBuildCookieCompleted = true;
163                 Cookie authCookie = null;
164                 Configuration.CookieConfig confCookie =
165                                 ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie();
166
167                 //create authentication and send it to encryption
168
169                 String encryptedCookie = "";
170                 try {
171             AuthenticationCookie authenticationCookie = new AuthenticationCookie(userId, firstName, lastName);
172                         String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie);
173                         encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey());
174                 } catch (Exception e) {
175                         isBuildCookieCompleted=false;
176                         log.error(" Cookie Encryption failed ", e);
177                 }
178
179                 authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie);
180                 authCookie.setPath(confCookie.getPath());
181                 authCookie.setDomain(confCookie.getDomain());
182                 authCookie.setHttpOnly(true);
183
184                 // add generated cookie to response
185                 if (isBuildCookieCompleted) {
186                         response.addCookie(authCookie);
187                         return true;
188                 }
189                 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG);
190                 return false;
191         }
192
193     /**
194      * Print all request headers to the log
195      *
196      * @param request
197      */
198     private void printHeaders(HttpServletRequest request) {
199
200         if (log.isDebugEnabled()) {
201             StringBuilder builder = new StringBuilder();
202             String sessionId = "";
203             if (request.getSession() != null) {
204                 String id = request.getSession().getId();
205                 if (id != null) {
206                     sessionId = id;
207                 }
208             }
209
210             builder.append("Receiving request with headers:" + NEW_LINE);
211             log.debug("{}", request.getHeaderNames());
212             @SuppressWarnings("unchecked")
213             Enumeration<String> headerNames = request.getHeaderNames();
214             if (headerNames != null) {
215                 while (headerNames.hasMoreElements()) {
216                     String headerName = headerNames.nextElement();
217                     String headerValue = request.getHeader(headerName);
218                     builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
219                 }
220             }
221
222             log.debug(builder.toString());
223         }
224
225     }
226
227     /**
228      * Add cookies (that where set in the new request headers) in the response
229      * Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP headers.
230      *
231      * @param response
232      * @param request
233      * @param headers
234      */
235     private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
236         for (int i = 0; i < headers.length; i++) {
237             String currHeader = headers[i];
238             String headerValue = request.getHeader(currHeader);
239             if (headerValue != null) {
240                 final Cookie cookie = new Cookie(currHeader, headerValue);
241                 cookie.setSecure(true);
242                 response.addCookie(cookie);
243             }
244         }
245     }
246
247     /**
248      * Get mandatory headers (identificationHeaderFields) String array, and
249      * checks that each header exists in the new request
250      *
251      * @param request
252      * @return boolean
253      */
254     private boolean checkHeaders(HttpServletRequest request) {
255         String[] mandatoryHeaders = getMandatoryHeaders(request);
256
257         boolean allHeadersExist = true;
258         for (int i = 0; i < mandatoryHeaders.length; i++) {
259             String headerValue = request.getHeader(mandatoryHeaders[i]);
260             if (headerValue == null) {
261                 allHeadersExist = false;
262                 break;
263             }
264         }
265         return allHeadersExist;
266     }
267
268     /**
269      * Get mandatory headers (identificationHeaderFields) from
270      * configuration.yaml file and return String[]
271      *
272      * @param request
273      * @return String[]
274      */
275     private String[] getMandatoryHeaders(HttpServletRequest request) {
276         Configuration configuration = getConfiguration(request);
277         List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
278         String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
279         for (int i = 0; i < identificationHeaderFields.size(); i++) {
280             mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
281         }
282         return mandatoryHeaders;
283     }
284
285     /**
286      * Get optional headers (optionalHeaderFields) from configuration.yaml file
287      * and return String[]
288      *
289      * @param request
290      * @return String[]
291      */
292     private String[] getOptionalHeaders(HttpServletRequest request) {
293         Configuration configuration = getConfiguration(request);
294         List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
295         String[] optionalHeaders = new String[optionalHeaderFields.size()];
296         for (int i = 0; i < optionalHeaderFields.size(); i++) {
297             optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
298         }
299         return optionalHeaders;
300     }
301
302     /**
303      * Return Configuration object to read from configuration.yaml
304      *
305      * @param request
306      * @return Configuration
307      */
308     private Configuration getConfiguration(HttpServletRequest request) {
309         ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
310         return configManager.getConfiguration();
311     }
312
313     private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
314         boolean newHeaderIsSet = false;
315         for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
316             String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
317             if (headerValue != null) {
318                 newRequest.putHeader(newHeaderToSet, headerValue);
319                 newHeaderIsSet = true;
320             }
321         }
322         return newHeaderIsSet;
323     }
324
325     private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
326         String userId = "";
327         Cookie[] cookies = request.getCookies();
328         Cookie userIdcookie = null;
329         if (cookies != null) {
330             for (Cookie cookie : cookies) {
331                 if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) {
332                     userIdcookie = cookie;
333                 }
334             }
335         }
336         if (userIdcookie != null) {
337             userId = CipherUtil.decrypt(userIdcookie.getValue());
338         }
339         return userId;
340         }
341
342         private static String getValueFromCookie(HttpServletRequest request, String cookieName) {
343                 String value = "";
344                 Cookie[] cookies = request.getCookies();
345                 Cookie valueFromCookie = null;
346                 if (cookies != null)
347                         for (Cookie cookie : cookies) {
348                                 if (cookie.getName().endsWith(cookieName)) {
349                                         valueFromCookie = cookie;
350                                 }
351                         }
352                 if (valueFromCookie != null) {
353                         value = valueFromCookie.getValue();
354                 }
355
356                 return value;
357     }
358 }