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.service;
 
  40 import java.util.List;
 
  42 import javax.servlet.http.HttpServletRequest;
 
  43 import org.apache.commons.codec.binary.Base64;
 
  44 import org.onap.portalapp.portal.domain.EPUser;
 
  45 import org.onap.portalapp.portal.domain.MicroserviceData;
 
  46 import org.onap.portalapp.portal.domain.MicroserviceParameter;
 
  47 import org.onap.portalapp.portal.domain.WidgetCatalogParameter;
 
  48 import org.onap.portalapp.portal.domain.WidgetServiceHeaders;
 
  49 import org.onap.portalapp.portal.logging.aop.EPMetricsLog;
 
  50 import org.onap.portalapp.portal.utils.EcompPortalUtils;
 
  51 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 
  52 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
 
  53 import org.onap.portalsdk.core.util.SystemProperties;
 
  54 import org.springframework.beans.factory.annotation.Autowired;
 
  55 import org.springframework.context.annotation.EnableAspectJAutoProxy;
 
  56 import org.springframework.http.HttpEntity;
 
  57 import org.springframework.http.HttpHeaders;
 
  58 import org.springframework.http.HttpMethod;
 
  59 import org.springframework.http.MediaType;
 
  60 import org.springframework.http.ResponseEntity;
 
  61 import org.springframework.stereotype.Service;
 
  62 import org.springframework.web.client.HttpClientErrorException;
 
  63 import org.springframework.web.client.RestTemplate;
 
  65 @Service("microserviceProxyService")
 
  66 @EnableAspectJAutoProxy
 
  68 public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
 
  70         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class);
 
  72         private static final String BASIC_AUTH = "Basic Authentication";
 
  73         private static final String NO_AUTH = "No Authentication";
 
  74         private static final String COOKIE_AUTH = "Cookie based Authentication";
 
  75         private static final String QUESTION_MARK = "?";
 
  76         private static final String ADD_MARK = "&";
 
  79         private ConsulHealthService consulHealthService;
 
  81         MicroserviceService microserviceService;
 
  83         WidgetParameterService widgetParameterService;
 
  85         private String whatService = "widgets-service";
 
  87         private RestTemplate template = new RestTemplate();
 
  90         public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
 
  91                 // get the microservice object by the id
 
  92                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
 
  93                 // No such microservice available
 
  95                         // can we return a better response than null?
 
  98                 return authenticateAndRespond(data, request, composeParams(data, user));
 
 102         public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
 
 104                 @SuppressWarnings({ "rawtypes", "unchecked" })
 
 105                 ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
 
 106                                 EcompPortalUtils.widgetMsProtocol() + "://"
 
 107                                                 + consulHealthService.getServiceLocation(whatService,
 
 108                                                                 SystemProperties.getProperty("microservices.widget.local.port"))
 
 109                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
 
 110                                 HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
 
 111                 Long serviceId = ans.getBody();
 
 112                 // get the microservice object by the id
 
 113                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
 
 114                 // No such microservice available
 
 118                 List<MicroserviceParameter> params = composeParams(data, user);
 
 119                 for (MicroserviceParameter p : params) {
 
 120                         WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
 
 122                         if (userValue != null)
 
 123                                 p.setPara_value(userValue.getUser_value());
 
 125                 return authenticateAndRespond(data, request, params);
 
 128         private String authenticateAndRespond(MicroserviceData data, HttpServletRequest request,
 
 129                         List<MicroserviceParameter> params) throws HttpClientErrorException, IllegalArgumentException {
 
 130                 String response = null;
 
 131                 if (data.getSecurityType().equals(NO_AUTH)) {
 
 132                         HttpEntity<String> entity = new HttpEntity<String>(headersForNoAuth());
 
 133                         String url = microserviceUrlConverter(data, params);
 
 134                         logger.debug(EELFLoggerDelegate.debugLogger,
 
 135                                         "authenticateAndRespond: Before making no authentication call: {}", url);
 
 136                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
 
 137                         logger.debug(EELFLoggerDelegate.debugLogger, "authenticateAndRespond: No authentication call response: {}",
 
 139                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
 
 140                         // encoding the username and password
 
 141                         String plainCreds = null;
 
 143                                 plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
 
 144                         } catch (Exception e) {
 
 145                                 logger.error("authenticateAndRespond failed to decrypt password", e);
 
 146                                 throw new IllegalArgumentException("Failed to decrypt password", e);
 
 148                         byte[] plainCredsBytes = plainCreds.getBytes();
 
 149                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
 
 150                         String base64Creds = new String(base64CredsBytes);
 
 152                         HttpEntity<String> entity = new HttpEntity<String>(headersForBasicAuth(request, base64Creds));
 
 154                         String url = microserviceUrlConverter(data, params);
 
 156                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
 
 157                         } catch (HttpClientErrorException e) {
 
 158                                 logger.error("authenticateAndRespond failed for basic security url " + url, e);
 
 161                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
 
 162                         HttpEntity<String> entity = new HttpEntity<String>(headersForCookieAuth(request));
 
 163                         String url = microserviceUrlConverter(data, params);
 
 165                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
 
 166                         } catch (HttpClientErrorException e) {
 
 167                                 logger.error("authenticateAndRespond failed for cookie auth url " + url, e);
 
 175         private String decryptedPassword(String encryptedPwd) throws Exception {
 
 177                 if (encryptedPwd != null && encryptedPwd.length() > 0) {
 
 179                                 result = CipherUtil.decryptPKC(encryptedPwd,
 
 180                                                 SystemProperties.getProperty(SystemProperties.Decryption_Key));
 
 181                         } catch (Exception e) {
 
 182                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
 
 190         private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
 
 191                 String url = data.getUrl();
 
 192                 for (int i = 0; i < params.size(); i++) {
 
 194                                 url += QUESTION_MARK;
 
 196                         url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
 
 197                         if (i != (params.size() - 1)) {
 
 205         private HttpHeaders headersForNoAuth() {
 
 206                 HttpHeaders headers = new HttpHeaders();
 
 207                 headers.setContentType(MediaType.APPLICATION_JSON);
 
 212         // TODO: why is this generically named cookie used?
 
 213         private final static String Cookie = "Cookie";
 
 215         private HttpHeaders headersForBasicAuth(HttpServletRequest request, String base64Creds) {
 
 216                 HttpHeaders headers = new HttpHeaders();
 
 217                 headers.add("Authorization", "Basic " + base64Creds);
 
 218                 headers.setContentType(MediaType.APPLICATION_JSON);
 
 219                 String rawCookie = request.getHeader(Cookie);
 
 220                 if (rawCookie != null)
 
 221                         headers.add(Cookie, rawCookie);
 
 225         private HttpHeaders headersForCookieAuth(HttpServletRequest request) {
 
 226                 HttpHeaders headers = new HttpHeaders();
 
 227                 headers.setContentType(MediaType.APPLICATION_JSON);
 
 228                 String rawCookie = request.getHeader(Cookie);
 
 229                 if (rawCookie != null)
 
 230                         headers.add(Cookie, rawCookie);
 
 234         private List<MicroserviceParameter> composeParams(MicroserviceData data, EPUser user) {
 
 235                 List<MicroserviceParameter> params = data.getParameterList();
 
 236                 MicroserviceParameter userIdParam = new MicroserviceParameter();
 
 237                 userIdParam.setPara_key("userId");
 
 238                 userIdParam.setPara_value(user.getOrgUserId());
 
 239                 params.add(userIdParam);