2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ===================================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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.
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
26 * https://creativecommons.org/licenses/by/4.0/
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.
34 * ============LICENSE_END============================================
38 package org.onap.portalapp.portal.interceptor;
40 import java.nio.charset.Charset;
41 import java.util.ArrayList;
42 import java.util.Base64;
43 import java.util.List;
45 import java.util.regex.Matcher;
46 import java.util.regex.Pattern;
47 import java.util.stream.Collectors;
49 import javax.servlet.http.HttpServletRequest;
50 import javax.servlet.http.HttpServletResponse;
52 import org.onap.portalapp.controller.sessionmgt.SessionCommunicationController;
53 import org.onap.portalapp.portal.controller.BasicAuthenticationController;
54 import org.onap.portalapp.portal.controller.ExternalAppsRestfulController;
55 import org.onap.portalapp.portal.controller.SharedContextRestController;
56 import org.onap.portalapp.portal.controller.WebAnalyticsExtAppController;
57 import org.onap.portalapp.portal.domain.BasicAuthCredentials;
58 import org.onap.portalapp.portal.domain.EPApp;
59 import org.onap.portalapp.portal.domain.EPEndpoint;
60 import org.onap.portalapp.portal.domain.EPUser;
61 import org.onap.portalapp.portal.logging.aop.EPEELFLoggerAdvice;
62 import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum;
63 import org.onap.portalapp.portal.logging.logic.EPLogUtil;
64 import org.onap.portalapp.portal.service.BasicAuthenticationCredentialService;
65 import org.onap.portalapp.portal.service.ExternalAccessRolesService;
66 import org.onap.portalapp.portal.utils.EcompPortalUtils;
67 import org.onap.portalapp.service.RemoteWebServiceCallService;
68 import org.onap.portalapp.service.sessionmgt.ManageService;
69 import org.onap.portalapp.util.EPUserUtils;
70 import org.onap.portalsdk.core.controller.FusionBaseController;
71 import org.onap.portalsdk.core.exception.UrlAccessRestrictedException;
72 import org.onap.portalsdk.core.interceptor.ResourceInterceptor;
73 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
74 import org.onap.portalsdk.core.onboarding.listener.PortalTimeoutHandler;
75 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
76 import org.onap.portalsdk.core.util.SystemProperties;
77 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
78 import org.springframework.beans.factory.annotation.Autowired;
79 import org.springframework.web.method.HandlerMethod;
81 public class PortalResourceInterceptor extends ResourceInterceptor {
82 private static final String APP_KEY = "uebkey";
84 private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalResourceInterceptor.class);
87 private RemoteWebServiceCallService remoteWebServiceCallService;
90 private ManageService manageService;
93 private EPEELFLoggerAdvice epAdvice;
96 private BasicAuthenticationCredentialService basicAuthService;
98 private ExternalAccessRolesService externalAccessRolesService;
100 @SuppressWarnings("unchecked")
102 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
105 if (handler instanceof HandlerMethod) {
106 HandlerMethod method = (HandlerMethod) handler;
109 * These classes provide REST endpoints used by other application
110 * servers, NOT by an end user's browser.
112 if (method.getBean() instanceof FusionBaseController) {
113 FusionBaseController controller = (FusionBaseController) method.getBean();
114 if (!controller.isAccessible()) {
116 // authorize portalApi requests by user role
117 String requestURI = request.getRequestURI();
118 if (requestURI != null) {
119 String[] uriArray = requestURI.split("/portalApi/");
120 if (uriArray.length > 1) {
121 String portalApiPath = uriArray[1];
123 Set<? extends String> roleFunctions = (Set<? extends String>) request.getSession()
124 .getAttribute(SystemProperties
125 .getProperty(SystemProperties.ROLE_FUNCTIONS_ATTRIBUTE_NAME));
126 Set<? extends String> allRoleFunctions = (Set<? extends String>) request.getSession()
127 .getAttribute(EPUserUtils.ALL_ROLE_FUNCTIONS);
128 // Defend against code error to avoid throwing NPE
129 if (roleFunctions == null || allRoleFunctions == null) {
130 logger.error(EELFLoggerDelegate.errorLogger,
131 "preHandle: failed to get role functions attribute(s) from session!!");
132 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeInitializationError);
135 // check to see if roleFunctions of the user is in
137 // list of all role functions
138 // if not, ignore to prevent restricting every
140 // call; otherwise, if it is, then check for the
142 if (matchRoleFunctions(portalApiPath, allRoleFunctions)
143 && !matchRoleFunctions(portalApiPath, roleFunctions)) {
144 EPUser user = (EPUser) request.getSession().getAttribute(
145 SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));
146 logger.error(EELFLoggerDelegate.errorLogger,
147 "preHandle: User {} not authorized for path {} ", user.getOrgUserId(),
149 EcompPortalUtils.setBadPermissions(user, response, portalApiPath);
150 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError);
159 else if (method.getBean() instanceof BasicAuthenticationController) {
160 return checkBasicAuth(request, response);
162 Object controllerObj = method.getBean();
163 if (controllerObj instanceof SessionCommunicationController
164 || controllerObj instanceof SharedContextRestController
165 || controllerObj instanceof ExternalAppsRestfulController) {
166 // check user authentication for RESTful calls
167 String secretKey = null;
169 epAdvice.loadServletRequestBasedDefaults(request, SecurityEventTypeEnum.INCOMING_REST_MESSAGE);
170 if (!remoteWebServiceCallService.verifyRESTCredential(secretKey, request.getHeader(APP_KEY),
171 request.getHeader("username"), request.getHeader("password"))) {
172 throw new UrlAccessRestrictedException();
174 } catch (Exception e) {
175 logger.error(EELFLoggerDelegate.errorLogger, "preHandle: failed to authenticate RESTful service",
177 EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeRestApiAuthenticationError, e);
178 throw new UrlAccessRestrictedException();
182 if (controllerObj instanceof WebAnalyticsExtAppController) {
183 if (!remoteWebServiceCallService.verifyAppKeyCredential(request.getHeader(APP_KEY))) {
184 logger.error(EELFLoggerDelegate.errorLogger,
185 "preHandle: failed to verify app key for web analytics call");
186 throw new UrlAccessRestrictedException();
191 handleSessionUpdates(request);
196 * Sets the status code and sends a response. Factors code out of many
200 * HttpServletResponse
202 * HTTP status code like 404
204 * Message to send in a JSON error object
206 private void sendErrorResponse(HttpServletResponse response, final int statusCode, final String message)
208 response.setStatus(statusCode);
209 response.setContentType("application/json");
210 response.getWriter().write("{\"error\":\"" + message + "\"}");
211 response.getWriter().flush();
215 * Gets HTTP basic authentication information from the request and checks
216 * whether those credentials are authorized for the request path.
221 * HttpServletResponse
222 * @return True if the request is authorized, else false
225 private boolean checkBasicAuth(HttpServletRequest request, HttpServletResponse response) throws Exception {
226 String uri = request.getRequestURI().toString();
227 uri = uri.substring(uri.indexOf("/", 1));
229 final String authHeader = request.getHeader("Authorization");
230 final String uebkey = request.getHeader("uebkey");
232 // Unauthorized access due to missing HTTP Authorization request header
233 if (authHeader == null) {
234 final String msg = "no authorization found";
235 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
236 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
240 String[] accountNamePassword = getUserNamePassword(authHeader);
241 if (accountNamePassword == null || accountNamePassword.length != 2) {
242 final String msg = "failed to get username and password from Atuhorization header";
243 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
244 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
248 if(uebkey !=null && !uebkey.isEmpty())
250 List<EPApp> app = externalAccessRolesService.getApp(uebkey);
251 EPApp application = null;
253 throw new Exception("Invalid uebkey!");
255 if (app.size() != 0 && !app.isEmpty()) {
256 application = app.get(0);
258 if (application != null) {
259 final String appUsername = application.getUsername();
260 final String dbDecryptedPwd = CipherUtil.decryptPKC(application.getAppPassword());
261 if (appUsername.equals(accountNamePassword[0]) && dbDecryptedPwd.equals(accountNamePassword[1])) {
268 BasicAuthCredentials creds;
270 creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0],
271 accountNamePassword[1]);
272 } catch (Exception e) {
273 logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e);
274 final String msg = "Failed while getting basic authentication credential: ";
275 sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
279 // Unauthorized access due to invalid credentials (username and
281 if (creds == null || !creds.getUsername().equals(accountNamePassword[0])) {
282 final String msg = "Unauthorized: Access denied";
283 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
284 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
288 // Unauthorized access due to inactive account
289 if (creds.getIsActive().equals("N")) {
290 final String msg = "Unauthorized: The account is inactive";
291 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
292 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
295 boolean isAllowedEp = false;
296 for (EPEndpoint ep : creds.getEndpoints()) {
297 if (ep.getName().equals(uri)) {
303 // If user doesn't specify any endpoint, allow all endpoints for that
305 if (creds.getEndpoints().size() == 0)
308 // Unauthorized access due to the invalid endpoints
310 final String msg = "Unauthorized: Endpoint access denied";
311 logger.debug(EELFLoggerDelegate.debugLogger, "checkBasicAuth: {}", msg);
312 sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, msg);
316 // Made it to the end!
320 private String[] getUserNamePassword(String authValue) {
321 String base64Credentials = authValue.substring("Basic".length()).trim();
322 String credentials = new String(Base64.getDecoder().decode(base64Credentials), Charset.forName("UTF-8"));
323 final String[] values = credentials.split(":", 2);
327 @SuppressWarnings("unused")
328 private String decrypted(String encrypted) throws Exception {
330 if (encrypted != null & encrypted.length() > 0) {
332 result = CipherUtil.decryptPKC(encrypted, SystemProperties.getProperty(SystemProperties.Decryption_Key));
333 } catch (Exception e) {
334 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
341 private String encrypted(String decryptedPwd) throws Exception {
343 if (decryptedPwd != null & decryptedPwd.length() > 0) {
345 result = CipherUtil.encryptPKC(decryptedPwd,
346 SystemProperties.getProperty(SystemProperties.Decryption_Key));
347 } catch (Exception e) {
348 logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword() failed", e);
355 private Boolean matchRoleFunctions(String portalApiPath, Set<? extends String> roleFunctions) {
356 String[] path = portalApiPath.split("/");
357 List<String> roleFunList = new ArrayList<>();
358 if (path.length > 1) {
359 roleFunList = roleFunctions.stream().filter(item -> item.startsWith(path[0])).collect(Collectors.toList());
360 if (roleFunList.size() >= 1) {
361 for (String roleFunction : roleFunList) {
362 String[] roleFunctionArray = roleFunction.split("/");
364 if (roleFunctionArray.length == path.length) {
365 for (int i = 0; i < roleFunctionArray.length; i++) {
367 if (!roleFunctionArray[i].equals("*")) {
368 Pattern p = Pattern.compile(Pattern.quote(path[i]), Pattern.CASE_INSENSITIVE);
369 Matcher m = p.matcher(roleFunctionArray[i]);
381 for (String roleFunction : roleFunctions) {
382 if (portalApiPath.matches(roleFunction))
389 protected void handleSessionUpdates(HttpServletRequest request) {
390 PortalTimeoutHandler.handleSessionUpdatesNative(request, null, null, null, null, manageService);