Catalog alignment
[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                 String firstNameFromCookie = "";
98                 String lastNameFromCookie  = "";
99         if (null == userId) {
100             // Authentication via ecomp portal
101             try {
102                 String userIdFromCookie = getUserIdFromCookie(request);
103                 if (("").equals(userIdFromCookie)) {
104                     // This is probably a webseal request, so missing header in request should be printed.
105                     response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
106                 }
107                 userId = userIdFromCookie;
108             } catch (Exception e) {
109                 response.sendError(HttpServletResponse.SC_USE_PROXY, AUTHORIZATION_ERROR_MSG);
110                 log.error("Error during adding request header", e);
111             }
112         }
113
114         // Replace webseal header with open source header
115         mutableRequest.putHeader(Constants.USER_ID, userId);
116
117
118
119
120                 
121         // Getting identification headers from configuration.yaml
122         // (identificationHeaderFields) and setting them to new request
123         // mutableRequest
124         List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
125         for (List<String> possibleHeadersToRecieve : identificationHeaderFields) {
126             String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
127             setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
128         }
129
130         // Getting optional headers from configuration.yaml
131         // (optionalHeaderFields) and setting them to new request mutableRequest
132         List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
133         for (List<String> possibleHeadersToRecieve : optionalHeaderFields) {
134             String allowedHeaderToPass = possibleHeadersToRecieve.get(0);
135             setNewHeader(possibleHeadersToRecieve, allowedHeaderToPass, request, mutableRequest);
136         }
137
138         // Print headers from original request for debug purposes
139         printHeaders(request);
140
141         // In case using webseal, validate all mandatory headers (identificationHeaderFields) are included in the new request (mutableRequest).
142         // Via ecomp portal do not need to check the headers.
143         boolean allHeadersExist = true;
144         if (null != request.getHeader(Constants.WEBSEAL_USER_ID_HEADER)) {
145             allHeadersExist = checkHeaders(mutableRequest);
146         }
147
148         if (allHeadersExist) {
149             addCookies(response, mutableRequest, getMandatoryHeaders(request));
150             addCookies(response, mutableRequest, getOptionalHeaders(request));
151                         firstNameFromCookie  = getValueFromCookie(request, Constants.HTTP_CSP_FIRSTNAME );
152                         lastNameFromCookie = getValueFromCookie(request, Constants.HTTP_CSP_LASTNAME);
153
154                         addAuthCookie(response, userId, firstNameFromCookie, lastNameFromCookie);
155             RequestDispatcher rd = request.getRequestDispatcher("index.html");
156             rd.forward(mutableRequest, response);
157         } else {
158             response.sendError(HttpServletResponse.SC_USE_PROXY, MISSING_HEADERS_MSG);
159         }
160     }
161
162         boolean addAuthCookie(HttpServletResponse response, String userId, String firstName, String lastName) throws IOException {
163                 boolean isBuildCookieCompleted = true;
164                 AuthenticationCookie authenticationCookie = null;
165                 Cookie authCookie = null;
166                 Configuration.CookieConfig confCookie =
167                                 ConfigurationManager.getConfigurationManager().getConfiguration().getAuthCookie();
168
169                 //create authentication and send it to encryption
170
171                 String encryptedCookie = "";
172                 try {
173                         authenticationCookie = new AuthenticationCookie(userId, firstName, lastName);
174                         String cookieAsJson = RepresentationUtils.toRepresentation(authenticationCookie);
175                         encryptedCookie = org.onap.sdc.security.CipherUtil.encryptPKC(cookieAsJson, confCookie.getSecurityKey());
176                 } catch (Exception e) {
177                         isBuildCookieCompleted=false;
178                         log.error(" Cookie Encryption failed ", e);
179                 }
180
181                 authCookie = new Cookie(confCookie.getCookieName(), encryptedCookie);
182                 authCookie.setPath(confCookie.getPath());
183                 authCookie.setDomain(confCookie.getDomain());
184                 authCookie.setHttpOnly(true);
185
186                 // add generated cookie to response
187                 if (isBuildCookieCompleted) {
188                         response.addCookie(authCookie);
189                         return true;
190                 }
191                 response.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTHORIZATION_ERROR_MSG);
192                 return false;
193         }
194
195     /**
196      * Print all request headers to the log
197      *
198      * @param request
199      */
200     private void printHeaders(HttpServletRequest request) {
201
202         if (log.isDebugEnabled()) {
203             StringBuilder builder = new StringBuilder();
204             String sessionId = "";
205             if (request.getSession() != null) {
206                 String id = request.getSession().getId();
207                 if (id != null) {
208                     sessionId = id;
209                 }
210             }
211
212             builder.append("Receiving request with headers:" + NEW_LINE);
213             log.debug("{}", request.getHeaderNames());
214             @SuppressWarnings("unchecked")
215             Enumeration<String> headerNames = request.getHeaderNames();
216             if (headerNames != null) {
217                 while (headerNames.hasMoreElements()) {
218                     String headerName = headerNames.nextElement();
219                     String headerValue = request.getHeader(headerName);
220                     builder.append("session " + sessionId + " header: name = " + headerName + ", value = " + headerValue + NEW_LINE);
221                 }
222             }
223
224             log.debug(builder.toString());
225         }
226
227     }
228
229     /**
230      * Add cookies (that where set in the new request headers) in the response
231      * Using DefaultHTTPUtilities Object to prevent CRLF injection in HTTP headers.
232      *
233      * @param response
234      * @param request
235      * @param headers
236      */
237     private void addCookies(HttpServletResponse response, HttpServletRequest request, String[] headers) {
238         for (int i = 0; i < headers.length; i++) {
239             String currHeader = headers[i];
240             String headerValue = request.getHeader(currHeader);
241             if (headerValue != null) {
242                 final Cookie cookie = new Cookie(currHeader, headerValue);
243                 cookie.setSecure(true);
244                 response.addCookie(cookie);
245             }
246         }
247     }
248
249     /**
250      * Get mandatory headers (identificationHeaderFields) String array, and
251      * checks that each header exists in the new request
252      *
253      * @param request
254      * @return boolean
255      */
256     private boolean checkHeaders(HttpServletRequest request) {
257         String[] mandatoryHeaders = getMandatoryHeaders(request);
258
259         boolean allHeadersExist = true;
260         for (int i = 0; i < mandatoryHeaders.length; i++) {
261             String headerValue = request.getHeader(mandatoryHeaders[i]);
262             if (headerValue == null) {
263                 allHeadersExist = false;
264                 break;
265             }
266         }
267         return allHeadersExist;
268     }
269
270     /**
271      * Get mandatory headers (identificationHeaderFields) from
272      * configuration.yaml file and return String[]
273      *
274      * @param request
275      * @return String[]
276      */
277     private String[] getMandatoryHeaders(HttpServletRequest request) {
278         Configuration configuration = getConfiguration(request);
279         List<List<String>> identificationHeaderFields = configuration.getIdentificationHeaderFields();
280         String[] mandatoryHeaders = new String[identificationHeaderFields.size()];
281         for (int i = 0; i < identificationHeaderFields.size(); i++) {
282             mandatoryHeaders[i] = identificationHeaderFields.get(i).get(0);
283         }
284         return mandatoryHeaders;
285     }
286
287     /**
288      * Get optional headers (optionalHeaderFields) from configuration.yaml file
289      * and return String[]
290      *
291      * @param request
292      * @return String[]
293      */
294     private String[] getOptionalHeaders(HttpServletRequest request) {
295         Configuration configuration = getConfiguration(request);
296         List<List<String>> optionalHeaderFields = configuration.getOptionalHeaderFields();
297         String[] optionalHeaders = new String[optionalHeaderFields.size()];
298         for (int i = 0; i < optionalHeaderFields.size(); i++) {
299             optionalHeaders[i] = optionalHeaderFields.get(i).get(0);
300         }
301         return optionalHeaders;
302     }
303
304     /**
305      * Return Configuration object to read from configuration.yaml
306      *
307      * @param request
308      * @return Configuration
309      */
310     private Configuration getConfiguration(HttpServletRequest request) {
311         ConfigurationManager configManager = (ConfigurationManager) request.getSession().getServletContext().getAttribute(org.openecomp.sdc.common.api.Constants.CONFIGURATION_MANAGER_ATTR);
312         return configManager.getConfiguration();
313     }
314
315     private boolean setNewHeader(List<String> possibleOldHeaders, String newHeaderToSet, HttpServletRequest oldRequest, MutableHttpServletRequest newRequest) {
316         boolean newHeaderIsSet = false;
317         for (int i = 0; i < possibleOldHeaders.size() && !newHeaderIsSet; i++) {
318             String headerValue = oldRequest.getHeader(possibleOldHeaders.get(i));
319             if (headerValue != null) {
320                 newRequest.putHeader(newHeaderToSet, headerValue);
321                 newHeaderIsSet = true;
322             }
323         }
324         return newHeaderIsSet;
325     }
326
327     private static String getUserIdFromCookie(HttpServletRequest request) throws CipherUtilException {
328         String userId = "";
329         Cookie[] cookies = request.getCookies();
330         Cookie userIdcookie = null;
331         if (cookies != null) {
332             for (Cookie cookie : cookies) {
333                 if (cookie.getName().equals(Constants.ECOMP_PORTAL_COOKIE)) {
334                     userIdcookie = cookie;
335                 }
336             }
337         }
338         if (userIdcookie != null) {
339             userId = CipherUtil.decrypt(userIdcookie.getValue());
340         }
341         return userId;
342         }
343
344         private static String getValueFromCookie(HttpServletRequest request, String cookieName) {
345                 String value = "";
346                 Cookie[] cookies = request.getCookies();
347                 Cookie valueFromCookie = null;
348                 if (cookies != null)
349                         for (Cookie cookie : cookies) {
350                                 if (cookie.getName().endsWith(cookieName)) {
351                                         valueFromCookie = cookie;
352                                 }
353                         }
354                 if (valueFromCookie != null) {
355                         value = valueFromCookie.getValue();
356                 }
357
358                 return value;
359     }
360 }