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