Resubmitting KeyProperty code change since tests failed
[portal.git] / ecomp-portal-BE-common / src / main / java / org / onap / portalapp / portal / service / MicroserviceProxyServiceImpl.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 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  * 
37  */
38 package org.onap.portalapp.portal.service;
39
40 import java.util.List;
41
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.onboarding.util.KeyConstants;
54 import org.onap.portalsdk.core.onboarding.util.KeyProperties;
55 import org.onap.portalsdk.core.util.SystemProperties;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.context.annotation.EnableAspectJAutoProxy;
58 import org.springframework.http.HttpEntity;
59 import org.springframework.http.HttpHeaders;
60 import org.springframework.http.HttpMethod;
61 import org.springframework.http.MediaType;
62 import org.springframework.http.ResponseEntity;
63 import org.springframework.stereotype.Service;
64 import org.springframework.web.client.HttpClientErrorException;
65 import org.springframework.web.client.RestTemplate;
66
67 @Service("microserviceProxyService")
68 @EnableAspectJAutoProxy
69 @EPMetricsLog
70 public class MicroserviceProxyServiceImpl implements MicroserviceProxyService {
71
72         private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyServiceImpl.class);
73
74         private static final String BASIC_AUTH = "Basic Authentication";
75         private static final String NO_AUTH = "No Authentication";
76         private static final String COOKIE_AUTH = "Cookie based Authentication";
77         private static final String QUESTION_MARK = "?";
78         private static final String ADD_MARK = "&";
79
80         @Autowired
81         private WidgetMService widgetMService;
82         @Autowired
83         MicroserviceService microserviceService;
84         @Autowired
85         WidgetParameterService widgetParameterService;
86
87         private String whatService = "widgets-service";
88
89         private RestTemplate template = new RestTemplate();
90
91         @Override
92         public String proxyToDestination(long serviceId, EPUser user, HttpServletRequest request) throws Exception {
93                 // get the microservice object by the id
94                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
95                 // No such microservice available
96                 if (data == null) {
97                         // can we return a better response than null?
98                         return null;
99                 }
100                 return authenticateAndRespond(data, request, composeParams(data, user));
101         }
102
103         @Override
104         public String proxyToDestinationByWidgetId(long widgetId, EPUser user, HttpServletRequest request)
105                         throws Exception {
106                 @SuppressWarnings({ "rawtypes", "unchecked" })
107                 ResponseEntity<Long> ans = (ResponseEntity<Long>) template.exchange(
108                                 EcompPortalUtils.widgetMsProtocol() + "://"
109                                                 + widgetMService.getServiceLocation(whatService,
110                                                                 SystemProperties.getProperty("microservices.widget.local.port"))
111                                                 + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
112                                 HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
113                 Long serviceId = ans.getBody();
114                 // get the microservice object by the id
115                 MicroserviceData data = microserviceService.getMicroserviceDataById(serviceId);
116                 // No such microservice available
117                 if (data == null)
118                         return null;
119
120                 List<MicroserviceParameter> params = composeParams(data, user);
121                 for (MicroserviceParameter p : params) {
122                         WidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
123                                         p.getId());
124                         if (userValue != null)
125                                 p.setPara_value(userValue.getUser_value());
126                 }
127                 return authenticateAndRespond(data, request, params);
128         }
129
130         private String authenticateAndRespond(MicroserviceData data, HttpServletRequest request,
131                         List<MicroserviceParameter> params) throws HttpClientErrorException, IllegalArgumentException {
132                 String response = null;
133                 if (data.getSecurityType().equals(NO_AUTH)) {
134                         HttpEntity<String> entity = new HttpEntity<String>(headersForNoAuth());
135                         String url = microserviceUrlConverter(data, params);
136                         logger.debug(EELFLoggerDelegate.debugLogger,
137                                         "authenticateAndRespond: Before making no authentication call: {}", url);
138                         response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
139                         logger.debug(EELFLoggerDelegate.debugLogger, "authenticateAndRespond: No authentication call response: {}",
140                                         response);
141                 } else if (data.getSecurityType().equals(BASIC_AUTH)) {
142                         // encoding the username and password
143                         String plainCreds = null;
144                         try {
145                                 plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
146                         } catch (Exception e) {
147                                 logger.error("authenticateAndRespond failed to decrypt password", e);
148                                 throw new IllegalArgumentException("Failed to decrypt password", e);
149                         }
150                         byte[] plainCredsBytes = plainCreds.getBytes();
151                         byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
152                         String base64Creds = new String(base64CredsBytes);
153
154                         HttpEntity<String> entity = new HttpEntity<String>(headersForBasicAuth(request, base64Creds));
155
156                         String url = microserviceUrlConverter(data, params);
157                         try {
158                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
159                         } catch (HttpClientErrorException e) {
160                                 logger.error("authenticateAndRespond failed for basic security url " + url, e);
161                                 throw e;
162                         }
163                 } else if (data.getSecurityType().equals(COOKIE_AUTH)) {
164                         HttpEntity<String> entity = new HttpEntity<String>(headersForCookieAuth(request));
165                         String url = microserviceUrlConverter(data, params);
166                         try {
167                                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
168                         } catch (HttpClientErrorException e) {
169                                 logger.error("authenticateAndRespond failed for cookie auth url " + url, e);
170                                 throw e;
171                         }
172                 }
173
174                 return response;
175         }
176
177         private String decryptedPassword(String encryptedPwd) throws Exception {
178                 String result = "";
179                 if (encryptedPwd != null && encryptedPwd.length() > 0) {
180                         try {
181                                 result = CipherUtil.decryptPKC(encryptedPwd,
182                                                 KeyProperties.getProperty(KeyConstants.CIPHER_ENCRYPTION_KEY));
183                         } catch (Exception e) {
184                                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
185                                 throw e;
186                         }
187                 }
188
189                 return result;
190         }
191
192         private String microserviceUrlConverter(MicroserviceData data, List<MicroserviceParameter> params) {
193                 String url = data.getUrl();
194                 for (int i = 0; i < params.size(); i++) {
195                         if (i == 0) {
196                                 url += QUESTION_MARK;
197                         }
198                         url += params.get(i).getPara_key() + "=" + params.get(i).getPara_value();
199                         if (i != (params.size() - 1)) {
200                                 url += ADD_MARK;
201                         }
202                 }
203
204                 return url;
205         }
206
207         private HttpHeaders headersForNoAuth() {
208                 HttpHeaders headers = new HttpHeaders();
209                 headers.setContentType(MediaType.APPLICATION_JSON);
210
211                 return headers;
212         }
213
214         // TODO: why is this generically named cookie used?
215         private final static String Cookie = "Cookie";
216         
217         private HttpHeaders headersForBasicAuth(HttpServletRequest request, String base64Creds) {
218                 HttpHeaders headers = new HttpHeaders();
219                 headers.add("Authorization", "Basic " + base64Creds);
220                 headers.setContentType(MediaType.APPLICATION_JSON);
221                 String rawCookie = request.getHeader(Cookie);
222                 if (rawCookie != null)
223                         headers.add(Cookie, rawCookie);
224                 return headers;
225         }
226
227         private HttpHeaders headersForCookieAuth(HttpServletRequest request) {
228                 HttpHeaders headers = new HttpHeaders();
229                 headers.setContentType(MediaType.APPLICATION_JSON);
230                 String rawCookie = request.getHeader(Cookie);
231                 if (rawCookie != null)
232                         headers.add(Cookie, rawCookie);
233                 return headers;
234         }
235
236         private List<MicroserviceParameter> composeParams(MicroserviceData data, EPUser user) {
237                 List<MicroserviceParameter> params = data.getParameterList();
238                 MicroserviceParameter userIdParam = new MicroserviceParameter();
239                 userIdParam.setPara_key("userId");
240                 userIdParam.setPara_value(user.getOrgUserId());
241                 params.add(userIdParam);
242                 return params;
243         }
244 }