[PORTAL-16 PORTAL-18] Widget ms; staging
[portal.git] / ecomp-portal-BE-common / src / main / java / org / openecomp / portalapp / portal / interceptor / PortalResourceInterceptor.java
1 /*-
2  * ================================================================================
3  * ECOMP Portal
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property
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  * ================================================================================*/
19 package org.openecomp.portalapp.portal.interceptor;
20
21 import java.nio.charset.Charset;
22 import java.util.Base64;
23 import java.util.Set;
24
25 import javax.servlet.http.HttpServletRequest;
26 import javax.servlet.http.HttpServletResponse;
27
28 import org.openecomp.portalapp.controller.sessionmgt.SessionCommunicationController;
29 import org.openecomp.portalapp.portal.controller.BasicAuthenticationController;
30 import org.openecomp.portalapp.portal.controller.ExternalAppsRestfulController;
31 import org.openecomp.portalapp.portal.controller.SharedContextRestController;
32 import org.openecomp.portalapp.portal.controller.WebAnalyticsExtAppController;
33 import org.openecomp.portalapp.portal.domain.BasicAuthCredentials;
34 import org.openecomp.portalapp.portal.domain.EPEndpoint;
35 import org.openecomp.portalapp.portal.domain.EPUser;
36 import org.openecomp.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
37 import org.openecomp.portalapp.portal.logging.format.EPAppMessagesEnum;
38 import org.openecomp.portalapp.portal.logging.logic.EPLogUtil;
39 import org.openecomp.portalapp.portal.service.BasicAuthenticationCredentialService;
40 import org.openecomp.portalapp.portal.utils.EcompPortalUtils;
41 import org.openecomp.portalapp.service.RemoteWebServiceCallService;
42 import org.openecomp.portalapp.service.sessionmgt.ManageService;
43 import org.openecomp.portalapp.util.EPUserUtils;
44 import org.openecomp.portalsdk.core.controller.FusionBaseController;
45 import org.openecomp.portalsdk.core.exception.UrlAccessRestrictedException;
46 import org.openecomp.portalsdk.core.interceptor.ResourceInterceptor;
47 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;
48 import org.openecomp.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
49 import org.openecomp.portalsdk.core.onboarding.util.CipherUtil;
50 import org.openecomp.portalsdk.core.util.SystemProperties;
51 import org.openecomp.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.web.method.HandlerMethod;
54
55 public class PortalResourceInterceptor extends ResourceInterceptor {
56         private static final String APP_KEY = "uebkey";
57
58         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
59
60         @Autowired
61         private RemoteWebServiceCallService remoteWebServiceCallService;
62
63         @Autowired
64         private ManageService manageService;
65
66         @Autowired
67         private EPEELFLoggerAdvice epAdvice;
68
69         @Autowired
70         private BasicAuthenticationCredentialService basicAuthService;
71
72         @SuppressWarnings("unchecked")
73         @Override
74         public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
75                         throws Exception {
76
77                 if (handler instanceof HandlerMethod) {
78                         HandlerMethod method = (HandlerMethod) handler;
79
80                         /**
81                          * These classes provide REST endpoints used by other application
82                          * servers, NOT by an end user's browser.
83                          */
84                         if (method.getBean() instanceof FusionBaseController) {
85                                 FusionBaseController controller = (FusionBaseController) method.getBean();
86                                 if (!controller.isAccessible()) {
87
88                                         // authorize portalApi requests by user role
89                                         String requestURI = request.getRequestURI();
90                                         if (requestURI != null) {
91                                                 String[] uriArray = requestURI.split("/portalApi/");
92                                                 if (uriArray.length > 1) {
93                                                         String portalApiPath = uriArray[1];
94
95                                                         Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
96                                                                         .getAttribute(SystemProperties
97                                                                                         .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
98                                                         Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
99                                                                         .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
100                                                         // Defend against code error to avoid throwing NPE
101                                                         if (roleFunctions == null || allRoleFunctions == null) {
102                                                                 logger.error(EELFLoggerDelegate.errorLogger,
103                                                                                 "preHandle: failed to get role functions attribute(s) from session!!");
104                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
105                                                                 return false;
106                                                         }
107                                                         // check to see if roleFunctions of the user is in
108                                                         // the
109                                                         // list of all role functions
110                                                         // if not, ignore to prevent restricting every
111                                                         // trivial
112                                                         // call; otherwise, if it is, then check for the
113                                                         // access
114                                                         if (matchRoleFunctions(portalApiPath, allRoleFunctions)
115                                                                         && !matchRoleFunctions(portalApiPath, roleFunctions)) {
116                                                                 EPUser user = (EPUser) request.getSession().getAttribute(
117                                                                                 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
118                                                                 logger.error(EELFLoggerDelegate.errorLogger,
119                                                                                 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
120                                                                                 portalApiPath);
121                                                                 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
122                                                                 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
123                                                                 return false;
124                                                         } // failed to match
125
126                                                 } // is portalApi
127
128                                         } // requestURI
129                                 } // instance check
130                         } // not accessible
131                         else if (method.getBean() instanceof BasicAuthenticationController) {
132                                 return checkBasicAuth(request, response);
133                         }
134                         Object controllerObj = method.getBean();
135                         if (controllerObj instanceof SessionCommunicationController
136                                         || controllerObj instanceof SharedContextRestController
137                                         || controllerObj instanceof ExternalAppsRestfulController) {
138                                 // check user authentication for RESTful calls
139                                 String secretKey = null;
140                                 try {
141                                         epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
142                                         if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(APP_KEY),
143                                                         request.getHeader("username"), request.getHeader("password"))) {
144                                                 throw new UrlAccessRestrictedException();
145                                         }
146                                 } catch (Exception e) {
147                                         logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
148                                                         e);
149                                         EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
150                                         throw new UrlAccessRestrictedException();
151                                 }
152                         }
153
154                         if (controllerObj instanceof WebAnalyticsExtAppController) {
155                                 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(APP_KEY))) {
156                                         logger.error(EELFLoggerDelegate.errorLogger,
157                                                         "preHandle: failed to verify app key for web analytics call");
158                                         throw new UrlAccessRestrictedException();
159                                 }
160                         }
161                 }
162
163                 handleSessionUpdates(request);
164                 return true;
165         }
166
167         /**
168          * Sets the status code and sends a response. Factors code out of many
169          * methods.
170          * 
171          * @param response
172          *            HttpServletResponse
173          * @param statusCode
174          *            HTTP status code like 404
175          * @param message
176          *            Message to send in a JSON error object
177          */
178         private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
179                         throws Exception {
180                 response.setStatus(statusCode);
181                 response.setContentType("application/json");
182                 response.getWriter().write("{\"error\":\"" + message + "\"}");
183                 response.getWriter().flush();
184         }
185
186         /**
187          * Gets HTTP basic authentication information from the request and checks
188          * whether those credentials are authorized for the request path.
189          * 
190          * @param request
191          *            HttpServletRequest
192          * @param response
193          *            HttpServletResponse
194          * @return True if the request is authorized, else false
195          * @throws Exception
196          */
197         private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
198                 String uri = request.getRequestURI().toString();
199                 uri = uri.substring(uri.indexOf("/", 1));
200
201                 final String authHeader = request.getHeader("Authorization");
202
203                 // Unauthorized access due to missing HTTP Authorization request header
204                 if (authHeader == null) {
205                         final String msg = "no authorization found";
206                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
207                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
208                         return false;
209                 }
210
211                 String[] accountNamePassword = getUserNamePassword(authHeader);
212                 if (accountNamePassword == null || accountNamePassword.length != 2) {
213                         final String msg = "failed to get username and password from Atuhorization header";
214                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
215                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
216                         return false;
217                 }
218
219                 BasicAuthCredentials creds;
220                 try {
221                         creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
222                                         encrypted(accountNamePassword[1]));
223                 } catch (Exception e) {
224                         logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
225                         final String msg = "Failed while getting basic authentication credential: " + e.toString();
226                         sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
227                         throw e;
228                 }
229
230                 // Unauthorized access due to invalid credentials (username and
231                 // password)
232                 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
233                         final String msg = "Unauthorized: Access denied";
234                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
235                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
236                         return false;
237                 }
238
239                 // Unauthorized access due to inactive account
240                 if (creds.getIsActive().equals("N")) {
241                         final String msg = "Unauthorized: The account is inactive";
242                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
243                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
244                         return false;
245                 }
246                 boolean isAllowedEp = false;
247                 for (EPEndpoint ep : creds.getEndpoints()) {
248                         if (ep.getName().equals(uri)) {
249                                 isAllowedEp = true;
250                                 break;
251                         }
252                 }
253
254                 // If user doesn't specify any endpoint, allow all endpoints for that
255                 // account
256                 if (creds.getEndpoints().size() == 0)
257                         isAllowedEp = true;
258
259                 // Unauthorized access due to the invalid endpoints
260                 if (!isAllowedEp) {
261                         final String msg = "Unauthorized: Endpoint access denied";
262                         logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
263                         sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
264                         return false;
265                 }
266
267                 // Made it to the end!
268                 return true;
269         }
270
271         private String[] getUserNamePassword(String authValue) {
272                 String base64Credentials = authValue.substring("Basic".length()).trim();
273                 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
274                 final String[] values = credentials.split(":", 2);
275                 return values;
276         }
277
278         private String decrypted(String encrypted) throws Exception {
279                 String result = "";
280                 if (encrypted != null & encrypted.length() > 0) {
281                         try {
282                                 result = CipherUtil.decrypt(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
283                         } catch (Exception e) {
284                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
285                                 throw e;
286                         }
287                 }
288                 return result;
289         }
290
291         private String encrypted(String decryptedPwd) throws Exception {
292                 String result = "";
293                 if (decryptedPwd != null & decryptedPwd.length() > 0) {
294                         try {
295                                 result = CipherUtil.encrypt(decryptedPwd,
296                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
297                         } catch (Exception e) {
298                                 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
299                                 throw e;
300                         }
301                 }
302                 return result;
303         }
304
305         private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
306                 for (String roleFunction : roleFunctions) {
307                         if (portalApiPath.matches(roleFunction))
308                                 return true;
309                 }
310                 return false;
311
312         }
313
314         protected void handleSessionUpdates(HttpServletRequest request) {
315                 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);
316         }
317 }