HealthCheckController up
[portal.git] / portal-BE / src / main / java / org / onap / portal / service / MicroserviceProxyService.java
1 package org.onap.portal.service;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Optional;
6 import javax.servlet.http.HttpServletRequest;
7 import org.apache.commons.codec.binary.Base64;
8 import org.onap.portal.domain.db.ep.EpMicroservice;
9 import org.onap.portal.domain.db.ep.EpMicroserviceParameter;
10 import org.onap.portal.domain.db.ep.EpWidgetCatalogParameter;
11 import org.onap.portal.domain.db.fn.FnUser;
12 import org.onap.portal.restTemplates.PortalWMSTemplate;
13 import org.onap.portal.service.microservice.EpMicroserviceService;
14 import org.onap.portal.service.widgetCatalogParameter.EpWidgetCatalogParameterService;
15 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
16 import org.onap.portalsdk.core.onboarding.util.CipherUtil;
17 import org.onap.portalsdk.core.util.SystemProperties;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.http.HttpEntity;
20 import org.springframework.http.HttpHeaders;
21 import org.springframework.http.HttpMethod;
22 import org.springframework.http.MediaType;
23 import org.springframework.http.ResponseEntity;
24 import org.springframework.stereotype.Service;
25 import org.springframework.web.client.HttpClientErrorException;
26 import org.springframework.web.client.RestTemplate;
27
28 @Service
29 public class MicroserviceProxyService {
30
31     private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyService.class);
32
33     private static final String BASIC_AUTH = "Basic Authentication";
34     private static final String NO_AUTH = "No Authentication";
35     private static final String COOKIE_AUTH = "Cookie based Authentication";
36     private static final String QUESTION_MARK = "?";
37     private static final String ADD_MARK = "&";
38
39     private RestTemplate template = new RestTemplate();
40
41     private final EpMicroserviceService microserviceService;
42     private final EpWidgetCatalogParameterService widgetParameterService;
43
44     private final PortalWMSTemplate portalWMSTemplate;
45
46     @Autowired
47     public MicroserviceProxyService(EpMicroserviceService microserviceService,
48         EpWidgetCatalogParameterService widgetParameterService, WidgetMService widgetMService,
49         PortalWMSTemplate portalWMSTemplate) {
50         this.microserviceService = microserviceService;
51         this.widgetParameterService = widgetParameterService;
52         this.portalWMSTemplate = portalWMSTemplate;
53     }
54
55     public String proxyToDestination(long serviceId, FnUser user, HttpServletRequest request) throws Exception {
56         // get the microservice object by the id
57         Optional<EpMicroservice> data = microserviceService.getById(serviceId);
58         // No such microservice available
59         // can we return a better response than null?
60         return data
61             .map(epMicroservice -> authenticateAndRespond(epMicroservice, request, composeParams(epMicroservice, user)))
62             .orElse(null);
63     }
64
65     public String proxyToDestinationByWidgetId(long widgetId, FnUser user, HttpServletRequest request)
66         throws Exception {
67         ResponseEntity<Long> ans = portalWMSTemplate.proxyToDestinationByWidgetId(widgetId);
68         Long serviceId = ans.getBody();
69         // get the microservice object by the id
70         Optional<EpMicroservice> data = microserviceService.getById(serviceId);
71         // No such microservice available
72         if (!data.isPresent()) {
73             return null;
74         }
75         List<EpMicroserviceParameter> params = composeParams(data.get(), user);
76         for (EpMicroserviceParameter p : params) {
77             EpWidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
78                 p.getId());
79             if (userValue != null) {
80                 p.setParaValue(userValue.getUserValue());
81             }
82         }
83         return authenticateAndRespond(data.get(), request, params);
84     }
85
86     private String authenticateAndRespond(EpMicroservice data, HttpServletRequest request,
87         List<EpMicroserviceParameter> params) throws HttpClientErrorException, IllegalArgumentException {
88         String response = null;
89         switch (data.getSecurityType()) {
90             case NO_AUTH: {
91                 HttpEntity<String> entity = new HttpEntity<>(headersForNoAuth());
92                 String url = microserviceUrlConverter(data, params);
93                 logger.debug(EELFLoggerDelegate.debugLogger,
94                     "authenticateAndRespond: Before making no authentication call: {}", url);
95                 response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
96                 logger.debug(EELFLoggerDelegate.debugLogger,
97                     "authenticateAndRespond: No authentication call response: {}",
98                     response);
99                 break;
100             }
101             case BASIC_AUTH: {
102                 // encoding the username and password
103                 String plainCreds;
104                 try {
105                     plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
106                 } catch (Exception e) {
107                     logger.error("authenticateAndRespond failed to decrypt password", e);
108                     throw new IllegalArgumentException("Failed to decrypt password", e);
109                 }
110                 byte[] plainCredsBytes = plainCreds.getBytes();
111                 byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
112                 String base64Creds = new String(base64CredsBytes);
113
114                 HttpEntity<String> entity = new HttpEntity<>(headersForBasicAuth(request, base64Creds));
115
116                 String url = microserviceUrlConverter(data, params);
117                 try {
118                     response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
119                 } catch (HttpClientErrorException e) {
120                     logger.error("authenticateAndRespond failed for basic security url " + url, e);
121                     throw e;
122                 }
123                 break;
124             }
125             case COOKIE_AUTH: {
126                 HttpEntity<String> entity = new HttpEntity<>(headersForCookieAuth(request));
127                 String url = microserviceUrlConverter(data, params);
128                 try {
129                     response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
130                 } catch (HttpClientErrorException e) {
131                     logger.error("authenticateAndRespond failed for cookie auth url " + url, e);
132                     throw e;
133                 }
134                 break;
135             }
136         }
137
138         return response;
139     }
140
141     private String decryptedPassword(String encryptedPwd) throws Exception {
142         String result = "";
143         if (encryptedPwd != null && encryptedPwd.length() > 0) {
144             try {
145                 result = CipherUtil.decryptPKC(encryptedPwd,
146                     SystemProperties.getProperty(SystemProperties.Decryption_Key));
147             } catch (Exception e) {
148                 logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
149                 throw e;
150             }
151         }
152
153         return result;
154     }
155
156     private String microserviceUrlConverter(EpMicroservice data, List<EpMicroserviceParameter> params) {
157         String url = data.getEndpointUrl();
158         for (int i = 0; i < params.size(); i++) {
159             if (i == 0) {
160                 url += QUESTION_MARK;
161             }
162             url += params.get(i).getParaKey() + "=" + params.get(i).getParaValue();
163             if (i != (params.size() - 1)) {
164                 url += ADD_MARK;
165             }
166         }
167
168         return url;
169     }
170
171     private HttpHeaders headersForNoAuth() {
172         HttpHeaders headers = new HttpHeaders();
173         headers.setContentType(MediaType.APPLICATION_JSON);
174
175         return headers;
176     }
177
178     // TODO: why is this generically named cookie used?
179     private final static String Cookie = "Cookie";
180
181     private HttpHeaders headersForBasicAuth(HttpServletRequest request, String base64Creds) {
182         HttpHeaders headers = new HttpHeaders();
183         headers.add("Authorization", "Basic " + base64Creds);
184         headers.setContentType(MediaType.APPLICATION_JSON);
185         String rawCookie = request.getHeader(Cookie);
186         if (rawCookie != null) {
187             headers.add(Cookie, rawCookie);
188         }
189         return headers;
190     }
191
192     private HttpHeaders headersForCookieAuth(HttpServletRequest request) {
193         HttpHeaders headers = new HttpHeaders();
194         headers.setContentType(MediaType.APPLICATION_JSON);
195         String rawCookie = request.getHeader(Cookie);
196         if (rawCookie != null) {
197             headers.add(Cookie, rawCookie);
198         }
199         return headers;
200     }
201
202     private List<EpMicroserviceParameter> composeParams(EpMicroservice data, FnUser user) {
203         List<EpMicroserviceParameter> params = new ArrayList<>(data.getEpMicroserviceParameters());
204         EpMicroserviceParameter userIdParam = new EpMicroserviceParameter();
205         userIdParam.setParaKey("userId");
206         userIdParam.setParaValue(user.getOrgUserId());
207         params.add(userIdParam);
208         return params;
209     }
210 }