2 * ============LICENSE_START==========================================
4 * ===================================================================
5 * Copyright (C) 2017-2018 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.logging.aop;
40 import java.net.InetAddress;
41 import java.text.SimpleDateFormat;
42 import java.util.Date;
43 import java.util.UUID;
45 import javax.servlet.http.HttpServletRequest;
47 import org.onap.portalapp.portal.domain.EPApp;
48 import org.onap.portalapp.portal.domain.EPUser;
49 import org.onap.portalapp.portal.service.AppsCacheService;
50 import org.onap.portalapp.portal.utils.EPCommonSystemProperties;
51 import org.onap.portalapp.portal.utils.EcompPortalUtils;
52 import org.onap.portalapp.util.EPUserUtils;
53 import org.onap.portalsdk.core.exception.SessionExpiredException;
54 import org.onap.portalsdk.core.logging.format.AlarmSeverityEnum;
55 import org.onap.portalsdk.core.logging.format.AuditLogFormatter;
56 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
57 import org.onap.portalsdk.core.util.SystemProperties;
58 import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum;
59 import org.onap.portalsdk.core.web.support.UserUtils;
61 import org.springframework.beans.factory.annotation.Autowired;
63 import com.att.eelf.configuration.Configuration;
65 @org.springframework.context.annotation.Configuration
66 public class EPEELFLoggerAdvice {
68 private EELFLoggerDelegate adviceLogger = EELFLoggerDelegate.getLogger(EPEELFLoggerAdvice.class);
71 AppsCacheService appCacheService;
74 * DateTime Format according to the ONAP Application Logging Guidelines.
78 * @return Current date and time in the format specified by the ONAP
79 * Application Logging Guidelines.
81 public static String getCurrentDateTimeUTC() {
82 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
83 String currentDateTime = ecompLogDateFormat.format(new Date());
84 return currentDateTime;
88 * Sets logging context with values from HttpServletRequest object.
92 * @param securityEventType
93 * SecurityEventTypeEnum
95 public void loadServletRequestBasedDefaults(HttpServletRequest req, SecurityEventTypeEnum securityEventType) {
97 setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, req.getServletPath());
98 } catch (Exception e) {
99 adviceLogger.error(EELFLoggerDelegate.errorLogger, "loadServletRequestBasedDefaults failed", e);
105 * @param securityEventType
108 * @return Object array
110 public Object[] before(SecurityEventTypeEnum securityEventType, Object[] args, Object[] passOnArgs) {
111 String className = "";
112 if (passOnArgs.length > 0 && passOnArgs[0] != null)
113 className = passOnArgs[0].toString();
114 String methodName = EPCommonSystemProperties.ECOMP_PORTAL_BE;
115 if (passOnArgs.length > 1 && passOnArgs[1] != null)
116 methodName = passOnArgs[1].toString();
118 // Initialize Request defaults only for controller methods.
119 MDC.put(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC());
120 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, EPCommonSystemProperties.ECOMP_PORTAL_BE);
121 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, methodName);
122 if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null||MDC.get(Configuration.MDC_KEY_REQUEST_ID).isEmpty()){
123 String requestId = UUID.randomUUID().toString();
124 MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId);
126 MDC.put(EPCommonSystemProperties.PARTNER_NAME, "Unknown");
127 MDC.put(Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
129 if (securityEventType != null) {
130 MDC.put(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
131 getCurrentDateTimeUTC());
132 HttpServletRequest req = null;
133 if (args.length > 0 && args[0] != null && args[0] instanceof HttpServletRequest) {
134 req = (HttpServletRequest) args[0];
135 this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, methodName);
139 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
140 logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#before: entering {}", methodName);
141 return new Object[] { "" };
146 * @param securityEventType
148 * @param responseCode
153 public void after(SecurityEventTypeEnum securityEventType, String statusCode, String responseCode, Object[] args,
154 Object[] returnArgs, Object[] passOnArgs) {
155 String className = "";
156 if (passOnArgs.length > 0 && passOnArgs[0] != null)
157 className = passOnArgs[0].toString();
159 String methodName = EPCommonSystemProperties.ECOMP_PORTAL_BE;
160 if (passOnArgs.length > 1 && passOnArgs[1] != null)
161 methodName = passOnArgs[1].toString();
163 if (MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME) == null
164 || MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME) == "")
165 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, methodName);
167 if (MDC.get(EPCommonSystemProperties.TARGET_ENTITY) == null
168 || MDC.get(EPCommonSystemProperties.TARGET_ENTITY) == "")
169 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, EPCommonSystemProperties.ECOMP_PORTAL_BE);
171 if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null||MDC.get(Configuration.MDC_KEY_REQUEST_ID).isEmpty()){
172 String requestId = UUID.randomUUID().toString();
173 MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId);
176 if (MDC.get(EPCommonSystemProperties.PARTNER_NAME) == null|| MDC.get(EPCommonSystemProperties.PARTNER_NAME).isEmpty()){
177 MDC.put(EPCommonSystemProperties.PARTNER_NAME, "Unknown");
180 MDC.put(Configuration.MDC_SERVICE_NAME, EPCommonSystemProperties.ECOMP_PORTAL_BE);
183 MDC.put(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP,
184 MDC.get(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP));
185 MDC.put(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
186 this.calculateDateTimeDifference(MDC.get(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP),
187 MDC.get(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP));
189 // Making sure to reload the INCOMING request MDC defaults if they have
190 // been wiped out by either Outgoing or LDAP Phone book search
192 if (securityEventType != null && args.length > 0 && args[0] != null && args[0] instanceof HttpServletRequest
193 && securityEventType == SecurityEventTypeEnum.INCOMING_REST_MESSAGE
194 && (MDC.get(EPCommonSystemProperties.FULL_URL) == null
195 || MDC.get(EPCommonSystemProperties.FULL_URL).isEmpty())) {
196 HttpServletRequest req = (HttpServletRequest) args[0];
197 this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, methodName);
200 // Use external API response code in case if it resulted in an error.
201 String externalAPIResponseCode = MDC.get(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
202 if (externalAPIResponseCode == null || externalAPIResponseCode == ""
203 || externalAPIResponseCode.trim().equalsIgnoreCase("200")) {
204 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, responseCode);
205 MDC.put(EPCommonSystemProperties.STATUS_CODE, statusCode);
207 MDC.put(EPCommonSystemProperties.RESPONSE_CODE, externalAPIResponseCode);
208 MDC.put(EPCommonSystemProperties.STATUS_CODE, "ERROR");
211 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(className);
212 logger.debug(EELFLoggerDelegate.debugLogger, "EPEELFLoggerAdvice#after: finished {}", methodName);
213 // add the metrics log
214 logger.info(EELFLoggerDelegate.metricsLogger, methodName + " operation is completed.");
216 // Log security message, if necessary
217 if (securityEventType != null) {
218 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
219 MDC.get(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP));
220 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, getCurrentDateTimeUTC());
221 this.calculateDateTimeDifference(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
222 MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
224 this.logSecurityMessage(logger, securityEventType, methodName);
226 // Outgoing & LDAP messages are part of Incoming requests so,
227 // keep "RequestId", "PartnerName", "ServiceName", "LoginId" &
228 // "ResponseCode" etc. in memory and remove it only when
229 // finished processing the parent incoming message.
230 if (securityEventType != SecurityEventTypeEnum.OUTGOING_REST_MESSAGE
231 && securityEventType != SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
232 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
233 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
234 MDC.remove(Configuration.MDC_SERVICE_NAME);
235 MDC.remove(EPCommonSystemProperties.MDC_LOGIN_ID);
236 MDC.remove(EPCommonSystemProperties.EXTERNAL_API_RESPONSE_CODE);
238 MDC.remove(Configuration.MDC_KEY_REQUEST_ID);
239 MDC.remove(EPCommonSystemProperties.PARTNER_NAME);
240 MDC.remove(Configuration.MDC_SERVICE_NAME);
243 // clear when finishes audit logging
244 MDC.remove(EPCommonSystemProperties.FULL_URL);
245 MDC.remove(EPCommonSystemProperties.PROTOCOL);
246 MDC.remove(EPCommonSystemProperties.STATUS_CODE);
247 MDC.remove(className + methodName + EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
248 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
249 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
250 MDC.remove(EPCommonSystemProperties.RESPONSE_CODE);
252 MDC.remove(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
253 MDC.remove(EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP);
254 MDC.remove(EPCommonSystemProperties.METRICSLOG_END_TIMESTAMP);
255 MDC.remove(EPCommonSystemProperties.MDC_TIMER);
256 MDC.remove(EPCommonSystemProperties.TARGET_ENTITY);
257 MDC.remove(EPCommonSystemProperties.TARGET_SERVICE_NAME);
264 * @param securityEventType
267 private void logSecurityMessage(EELFLoggerDelegate logger, SecurityEventTypeEnum securityEventType,
269 StringBuilder additionalInfoAppender = new StringBuilder();
270 String auditMessage = "";
272 if (securityEventType == SecurityEventTypeEnum.OUTGOING_REST_MESSAGE) {
273 additionalInfoAppender.append(String.format("%s '%s' request was initiated.", restMethod,
274 MDC.get(EPCommonSystemProperties.TARGET_SERVICE_NAME)));
275 } else if (securityEventType == SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
276 additionalInfoAppender.append("LDAP Phonebook search operation is performed.");
278 additionalInfoAppender.append(String.format("%s request was received.", restMethod));
280 if (securityEventType == SecurityEventTypeEnum.FE_LOGIN_ATTEMPT) {
282 String additionalMessage = " Successfully authenticated.";
283 loginId = MDC.get(EPCommonSystemProperties.MDC_LOGIN_ID);
284 if (loginId == null || loginId == "" || loginId == EPCommonSystemProperties.UNKNOWN) {
285 additionalMessage = " No cookies are found.";
287 additionalInfoAppender.append(additionalMessage);
288 } else if (securityEventType == SecurityEventTypeEnum.FE_LOGOUT) {
289 additionalInfoAppender.append(" User has been successfully logged out.");
293 String fullURL = MDC.get(EPCommonSystemProperties.FULL_URL);
294 if (fullURL != null && fullURL != "") {
295 additionalInfoAppender.append(" Request-URL:" + MDC.get(EPCommonSystemProperties.FULL_URL));
298 auditMessage = AuditLogFormatter.getInstance().createMessage(MDC.get(EPCommonSystemProperties.PROTOCOL),
299 securityEventType.name(), MDC.get(EPCommonSystemProperties.MDC_LOGIN_ID),
300 additionalInfoAppender.toString());
302 logger.info(EELFLoggerDelegate.auditLogger, auditMessage);
308 * @param securityEventType
311 private void setHttpRequestBasedDefaultsIntoGlobalLoggingContext(HttpServletRequest req,
312 SecurityEventTypeEnum securityEventType, String restMethod) {
314 * No need to load the request based defaults for the following security
315 * messages since either they are initiated by the Portal BE or not Http
319 if (securityEventType != SecurityEventTypeEnum.OUTGOING_REST_MESSAGE
320 && securityEventType != SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH
321 && securityEventType != SecurityEventTypeEnum.INCOMING_UEB_MESSAGE) {
322 // Load the RequestID (aka TrasactionId) into MDC context.
325 loadPartnerName(req);
329 loadUrlProtocol(req);
331 loadServicePath(req, restMethod);
333 loadClientAddress(req);
335 } else if (securityEventType == SecurityEventTypeEnum.LDAP_PHONEBOOK_USER_SEARCH) {
336 MDC.put(EPCommonSystemProperties.TARGET_ENTITY, "Phonebook");
337 MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, "search");
340 MDC.put(Configuration.MDC_SERVICE_NAME, restMethod);
341 MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE);
344 MDC.put(Configuration.MDC_SERVICE_INSTANCE_ID, "");
345 MDC.put(Configuration.MDC_ALERT_SEVERITY, AlarmSeverityEnum.INFORMATIONAL.severity());
347 MDC.put(Configuration.MDC_SERVER_FQDN, InetAddress.getLocalHost().getCanonicalHostName());
348 MDC.put(Configuration.MDC_SERVER_IP_ADDRESS, InetAddress.getLocalHost().getHostAddress());
349 MDC.put(Configuration.MDC_INSTANCE_UUID, SystemProperties.getProperty(SystemProperties.INSTANCE_UUID));
350 } catch (Exception e) {
351 adviceLogger.error(EELFLoggerDelegate.errorLogger,
352 "setHttpRequestBasedDefaultsIntoGlobalLoggingContext failed", e);
356 private void loadClientAddress(HttpServletRequest req) {
357 // Client IPAddress i.e. IPAddress of the remote host who is
358 // making this request.
359 String clientIPAddress = "";
360 clientIPAddress = req.getHeader("X-FORWARDED-FOR");
361 if (clientIPAddress == null) {
362 clientIPAddress = req.getRemoteAddr();
364 MDC.put(EPCommonSystemProperties.CLIENT_IP_ADDRESS, clientIPAddress);
367 private void loadServicePath(HttpServletRequest req, String restMethod) {
369 MDC.put(Configuration.MDC_SERVICE_NAME, restMethod);
370 String restPath = req.getServletPath();
371 //if (restPath != null && restPath != "") {
372 if (restPath != null && restPath.trim().length()>0) {
374 MDC.put(Configuration.MDC_SERVICE_NAME, restPath);
378 private void loadUrlProtocol(HttpServletRequest req) {
379 // Rest URL & Protocol
381 MDC.put(EPCommonSystemProperties.FULL_URL, EPCommonSystemProperties.UNKNOWN);
382 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTP);
383 restURL = UserUtils.getFullURL(req);
384 //if (restURL != null && restURL != "") {
385 if (restURL != null && restURL.trim().length()>0) {
386 MDC.put(EPCommonSystemProperties.FULL_URL, restURL);
387 if (restURL.toLowerCase().contains("https")) {
388 MDC.put(EPCommonSystemProperties.PROTOCOL, EPCommonSystemProperties.HTTPS);
393 private void loadRequestId(HttpServletRequest req) {
394 String requestId = UserUtils.getRequestId(req);
395 if (requestId == null||requestId.trim().length()==0) {
396 requestId = UUID.randomUUID().toString();
398 MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId);
401 private void loadLoginId(HttpServletRequest req) {
402 // Load loginId into MDC context.
403 String loginId = "NoUser";
406 EPUser user = EPUserUtils.getUserSession(req);
407 loginId = (user != null ? user.getOrgUserId(): loginId);
408 } catch (SessionExpiredException se) {
409 adviceLogger.debug(EELFLoggerDelegate.debugLogger,
410 "setHttpRequestBasedDefaultsIntoGlobalLoggingContext: No user found in session");
413 // try fetching from username in header
414 final String nameHeader = req.getHeader(EPCommonSystemProperties.USERNAME);
415 if (nameHeader != null) {
416 loginId = nameHeader;
419 // try fetching from BasicAuth info
420 final String authHeader = req.getHeader(EPCommonSystemProperties.AUTHORIZATION);
421 if (authHeader != null) {
422 String[] accountNamePassword = EcompPortalUtils.getUserNamePassword(authHeader);
423 if (accountNamePassword != null && accountNamePassword.length == 2) {
424 loginId = accountNamePassword[0];
429 MDC.put(EPCommonSystemProperties.MDC_LOGIN_ID, loginId );
433 private void loadPartnerName(HttpServletRequest req) {
436 // Load user agent into MDC context, if available.
437 String accessingClient = req.getHeader(SystemProperties.USERAGENT_NAME);
438 accessingClient = (accessingClient == null || accessingClient.trim().length()==0)?"Unknown":accessingClient;
439 if (accessingClient != null && accessingClient.trim().length()==0 && (accessingClient.contains("Mozilla")
440 || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) {
441 accessingClient = EPCommonSystemProperties.ECOMP_PORTAL_FE;
443 MDC.put(EPCommonSystemProperties.PARTNER_NAME, accessingClient);
445 // try get the Partner name from uebkey
446 String uebVal = req.getHeader(EPCommonSystemProperties.UEB_KEY);
448 EPApp appRecord = appCacheService.getAppFromUeb(uebVal);
449 MDC.put(EPCommonSystemProperties.PARTNER_NAME, appRecord.getName());
457 * @param beginDateTime
460 private void calculateDateTimeDifference(String beginDateTime, String endDateTime) {
461 if (beginDateTime != null && endDateTime != null && !beginDateTime.isEmpty()&&!endDateTime.isEmpty()) {
463 SimpleDateFormat ecompLogDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
464 Date beginDate = ecompLogDateFormat.parse(beginDateTime);
465 Date endDate = ecompLogDateFormat.parse(endDateTime);
466 String timeDifference = String.format("%d", endDate.getTime() - beginDate.getTime());
467 MDC.put(SystemProperties.MDC_TIMER, timeDifference);
468 } catch (Exception e) {
469 adviceLogger.error(EELFLoggerDelegate.errorLogger, "calculateDateTimeDifference failed", e);
474 public String getInternalResponseCode() {
475 return MDC.get(EPCommonSystemProperties.RESPONSE_CODE);