diff options
Diffstat (limited to 'catalog-be/src/main/java/org/openecomp/sdc/be/filters')
10 files changed, 860 insertions, 126 deletions
diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java index 5166ef94d7..1747525417 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BasicAuthenticationFilter.java @@ -24,6 +24,7 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; import fj.data.Either; import org.apache.commons.codec.binary.Base64; +import org.onap.sdc.security.Passwords; import org.openecomp.sdc.be.components.impl.ConsumerBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -35,7 +36,6 @@ import org.openecomp.sdc.common.log.enums.Severity; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; import org.openecomp.sdc.exception.ResponseFormat; -import org.openecomp.sdc.security.Passwords; import org.springframework.web.context.WebApplicationContext; import javax.annotation.Priority; @@ -54,6 +54,7 @@ import java.util.StringTokenizer; @Priority(10) public class BasicAuthenticationFilter implements ContainerRequestFilter { + private static LoggerSdcAudit audit = new LoggerSdcAudit(BasicAuthenticationFilter.class); private static final Logger log = Logger.getLogger(BasicAuthenticationFilter.class); private static final String COMPONENT_UTILS_FAILED = "Authentication Filter Failed to get component utils."; @@ -219,12 +220,12 @@ public class BasicAuthenticationFilter implements ContainerRequestFilter { private void abortWith(ContainerRequestContext requestContext, String message, Response response) { - audit.log(sr.getRemoteAddr(), + audit.logEntry(sr.getRemoteAddr(), requestContext, - response.getStatusInfo(), +// response.getStatusInfo(), LogLevel.ERROR, Severity.WARNING, - message); + message, null); log.error(message); audit.clearMyData(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java new file mode 100644 index 0000000000..49b9fbf5d7 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeCadiServletFilter.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.filters; + +import org.onap.aaf.cadi.Access; +import org.onap.aaf.cadi.PropAccess; +import org.onap.aaf.cadi.config.Config; +import org.onap.aaf.cadi.filter.CadiFilter; +import org.openecomp.sdc.be.components.impl.CADIHealthCheck; +import org.openecomp.sdc.be.config.CadiFilterParams; +import org.openecomp.sdc.be.config.ConfigurationManager; +import org.openecomp.sdc.be.impl.WebAppContextWrapper; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.api.HealthCheckInfo; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.springframework.web.context.WebApplicationContext; + +import javax.annotation.Priority; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.util.function.Supplier; + +@Priority(2) +public class BeCadiServletFilter extends CadiFilter { + + private static final Logger log = Logger.getLogger(BeCadiServletFilter.class); + private ConfigurationManager configurationManager = ConfigurationManager.getConfigurationManager(); + private static final String BE_CADI_SERVICE_FILTER = "BeCadiServletFilter: "; + + + public BeCadiServletFilter() { + super(); + log.debug(BE_CADI_SERVICE_FILTER); + } + + /** + * This constructor to be used when directly constructing and placing in HTTP Engine + * + * @param access + * @param moreTafLurs + * @throws ServletException + */ + public BeCadiServletFilter(Access access, Object... moreTafLurs) throws ServletException { + super(access, moreTafLurs); + log.debug(BE_CADI_SERVICE_FILTER); + } + + + /** + * Use this to pass in a PreContructed CADI Filter, but with initializing... let Servlet do it + * + * @param init + * @param access + * @param moreTafLurs + * @throws ServletException + */ + public BeCadiServletFilter(boolean init, PropAccess access, Object... moreTafLurs) throws ServletException { + + super(init, access, moreTafLurs); + log.debug(BE_CADI_SERVICE_FILTER); + } + + private void checkIfNullProperty(String key, String value) { + /* When value is null, so not defined in application.properties + set nothing in System properties */ + if (value != null) { + /* Ensure that any properties already defined in System.prop by JVM params + won't be overwritten by Spring application.properties values */ + System.setProperty(key, System.getProperty(key, value)); + } + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + // set some properties in System so that Cadi filter will find its config + // The JVM values set will always overwrite the Spring ones. + CadiFilterParams cadiFilterParams = configurationManager.getConfiguration().getCadiFilterParams(); + checkIfNullProperty(Config.HOSTNAME, cadiFilterParams.getHostname()); + log.debug("BeCadiServletFilter: HOSTNAME", cadiFilterParams.getHostname()); + + checkIfNullProperty(Config.CADI_KEYFILE, cadiFilterParams.getCadi_keyfile()); + checkIfNullProperty(Config.CADI_LOGLEVEL, cadiFilterParams.getCadi_loglevel()); + + + checkIfNullProperty(Config.CADI_LATITUDE, cadiFilterParams.getAFT_LATITUDE()); + checkIfNullProperty(Config.CADI_LONGITUDE, cadiFilterParams.getAFT_LONGITUDE()); + + checkIfNullProperty(Config.AAF_URL, cadiFilterParams.getAaf_url()); + //checkIfNullProperty(Config.AAF_LOCATE_URL, cadiFilterParams.getAafLocateUrl()); + checkIfNullProperty(Config.AAF_APPID, cadiFilterParams.getAaf_id()); + checkIfNullProperty(Config.AAF_APPPASS, cadiFilterParams.getAaf_password()); + checkIfNullProperty(Config.AAF_ENV, cadiFilterParams.getAFT_ENVIRONMENT()); + + checkIfNullProperty(Config.CADI_X509_ISSUERS, cadiFilterParams.getCadiX509Issuers()); + checkIfNullProperty(Config.CADI_TRUSTSTORE, cadiFilterParams.getCadi_truststore()); + checkIfNullProperty(Config.CADI_TRUSTSTORE_PASSWORD, cadiFilterParams.getCadi_truststore_password()); + super.init(filterConfig); + log.debug("BeCadiServletFilter finishing init(), Current status of CADI would be UP"); + if (!isNeedAuth()) { + CADIHealthCheck.getCADIHealthCheckInstance().setIsCADIUp(HealthCheckInfo.HealthCheckStatus.DOWN); + } else { + CADIHealthCheck.getCADIHealthCheckInstance().setIsCADIUp(HealthCheckInfo.HealthCheckStatus.UP); + } + } + + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { + + if (ThreadLocalsHolder.isExternalRequest() && isNeedAuth()) { + log.debug("doFilter: {}", request.getContentType()); + HttpServletRequest hreq = (HttpServletRequest) request; + log.debug("Need aaf authentication : {}", hreq); + ThreadLocalUtils threadLocalUtils = getThreadLocalUtils(((HttpServletRequest) request).getSession().getServletContext()); + threadLocalUtils.setUserContext((HttpServletRequest) request); + super.doFilter(request, response, chain); + } else { + log.debug("No need aaf authentication"); + chain.doFilter(request, response); + } + } + + private boolean isNeedAuth() { + return configurationManager.getConfiguration().getAafAuthNeeded(); + } + + + ThreadLocalUtils getThreadLocalUtils(ServletContext context) { + return getClassFromWebAppContext(context, () -> ThreadLocalUtils.class); + } + + <T> T getClassFromWebAppContext(ServletContext context, Supplier<Class<T>> businessLogicClassGen) { + WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context.getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR); + WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context); + return webApplicationContext.getBean(businessLogicClassGen.get()); + } + + +} + + + + + + + + + + + + + + + diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java new file mode 100644 index 0000000000..de8969a310 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeRestrictionAccessFilter.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.filters; + +import org.onap.sdc.security.PortalClient; +import org.onap.sdc.security.filters.RestrictionAccessFilter; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.springframework.stereotype.Component; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import java.io.IOException; + +@Component("beRestrictionAccessFilter") +public class BeRestrictionAccessFilter extends RestrictionAccessFilter { + + private static final Logger log = Logger.getLogger(RestrictionAccessFilter.class.getName()); + + public BeRestrictionAccessFilter(FilterConfiguration configuration, ThreadLocalUtils threadLocalUtils, + PortalClient portalClient) { + super(configuration, threadLocalUtils, portalClient); + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + if (ThreadLocalsHolder.isInternalRequest()) { + super.doFilter(servletRequest, servletResponse, filterChain); + } else { + log.debug("Access Restriction cookie validation is not needed"); + filterChain.doFilter(servletRequest, servletResponse); + } + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java index c9430107df..c559751515 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/BeServletFilter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,6 +21,8 @@ package org.openecomp.sdc.be.filters; import com.google.gson.GsonBuilder; +import org.onap.logging.filter.base.AuditLogContainerFilter; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.Configuration; import org.openecomp.sdc.be.config.ConfigurationManager; @@ -29,11 +31,9 @@ import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao; import org.openecomp.sdc.be.impl.ComponentsUtils; import org.openecomp.sdc.be.impl.WebAppContextWrapper; import org.openecomp.sdc.common.api.Constants; -import org.openecomp.sdc.common.log.elements.LogFieldsMdcHandler; -import org.openecomp.sdc.common.log.enums.LogLevel; +import org.openecomp.sdc.common.log.api.ILogConfiguration; import org.openecomp.sdc.common.log.enums.Severity; import org.openecomp.sdc.common.log.wrappers.Logger; -import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; import org.openecomp.sdc.common.util.ThreadLocalsHolder; import org.openecomp.sdc.exception.ResponseFormat; import org.slf4j.MDC; @@ -43,104 +43,76 @@ import javax.annotation.Priority; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.container.ContainerResponseContext; -import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; import java.io.IOException; -import java.util.UUID; @Provider @Priority(1) -public class BeServletFilter implements ContainerRequestFilter, ContainerResponseFilter { +public class BeServletFilter extends AuditLogContainerFilter { @Context private HttpServletRequest sr; private static final Logger log = Logger.getLogger(BeServletFilter.class); - private static LoggerSdcAudit audit = new LoggerSdcAudit(BeServletFilter.class); @Override - public void filter(ContainerRequestContext requestContext) throws IOException { - try { - - MDC.clear(); - - audit.startLog(requestContext); - - // In case of 405 response code, this function is not entered, then - // we'll process - // the MDC fields and UUID during the response - ThreadLocalsHolder.setMdcProcessed(true); - - // Timing HTTP request - ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis()); - - String uuid = processMdcFields(requestContext); - - ThreadLocalsHolder.setUuid(uuid); - - inHttpRequest(); - - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); - log.debug("Error during request filter: {} ", e); + public void filter(ContainerRequestContext requestContext) { + if (isLoggedRequest()) { + try { + super.filter(requestContext); + // In case of 405 response code, this function is not entered, then + // we'll process + // the MDC fields and UUID during the response + ThreadLocalsHolder.setMdcProcessed(true); + // Timing HTTP request + ThreadLocalsHolder.setRequestStartTime(System.currentTimeMillis()); + processMdcFields(requestContext); + ThreadLocalsHolder.setUuid(MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + inHttpRequest(); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); + log.debug("Error during request filter: {} ", e); + } } } @Override - public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { - try { - // Formatting the response in case of 405 - if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) { - ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED); - responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError())); - } + protected void additionalPreHandling(ContainerRequestContext containerRequestContext) { + MDC.put(ILogConfiguration.MDC_REMOTE_HOST, sr.getRemoteAddr()); + MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, containerRequestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER)); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_SEVERITY, String.valueOf(Severity.OK.getSeverityType())); + } - if (ThreadLocalsHolder.isMdcProcessed()) { - // filter() was executed during request - this is the regular - // flow - responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid()); - Long startTime = ThreadLocalsHolder.getRequestStartTime(); - if (startTime != null) { - long endTime = System.currentTimeMillis(); - MDC.put("timer", Long.toString(endTime - startTime)); + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + if (isLoggedRequest()) { + try { + super.filter(requestContext, responseContext); + // Formatting the response in case of 405 + if (responseContext.getStatus() == Response.Status.METHOD_NOT_ALLOWED.getStatusCode()) { + ResponseFormat responseFormat = getComponentsUtils().getResponseFormat(ActionStatus.NOT_ALLOWED); + responseContext.setEntity(new GsonBuilder().setPrettyPrinting().create().toJson(responseFormat.getRequestError())); } - } else { - // this is the 405 response code case - // we have no MDC fields since filter() wasn't executed during - // request - String uuid = processMdcFields(requestContext); - - responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, uuid); - // call to start-log method to fill mandatory fields - audit.startLog(requestContext); - } - writeToJanusGraph(responseContext); - - //write to Audit log in case it's valuable action - // (e.g. ignoring healthCheck and any other unlogged urls as in yaml - if (isInfoLog()) { - audit.log(sr.getRemoteAddr(), - requestContext, - responseContext.getStatusInfo(), - LogLevel.INFO, - Severity.OK, - LogFieldsMdcHandler.getInstance() - .getAuditMessage()); - } + if (ThreadLocalsHolder.isMdcProcessed()) { + // filter() was executed during request - this is the regular + // flow + responseContext.getHeaders().add(Constants.X_ECOMP_REQUEST_ID_HEADER, ThreadLocalsHolder.getUuid()); + } + writeToJanusGraph(responseContext); - outHttpResponse(responseContext); + outHttpResponse(responseContext); - } catch (Exception e) { - BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); - log.debug("Error during response filter: {} ", e); - } finally { - // Cleaning up - MDC.clear(); - ThreadLocalsHolder.cleanup(); + } catch (Exception e) { + BeEcompErrorManager.getInstance().logBeRestApiGeneralError("Error during request filter"); + log.debug("Error during response filter: {} ", e); + } finally { + // Cleaning up + MDC.clear(); + ThreadLocalsHolder.cleanup(); + } } } @@ -161,37 +133,16 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons } } - private String processMdcFields(ContainerRequestContext requestContext) { + private void processMdcFields(ContainerRequestContext requestContext) { // UserId for logging String userId = requestContext.getHeaderString(Constants.USER_ID_HEADER); MDC.put("userId", userId); String serviceInstanceID = requestContext.getHeaderString(Constants.X_ECOMP_SERVICE_ID_HEADER); - MDC.put("serviceInstanceID", serviceInstanceID); + MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, serviceInstanceID); MDC.put("remoteAddr", sr.getRemoteAddr()); MDC.put("localAddr", sr.getLocalAddr()); - - // UUID - String uuid = requestContext.getHeaderString(Constants.X_ECOMP_REQUEST_ID_HEADER); - if (uuid == null) { - // Generate the UUID - uuid = UUID.randomUUID().toString(); - - // Add to MDC for logging - MDC.put("uuid", uuid); - - // This log message should already be with the UUID - uuidGeneration(uuid); - - } else { - // According to Ella, in case this header exists, we don't have to - // perform any validations - // since it's not our responsibilty, so we log the UUID just as it - // was received. - MDC.put("uuid", uuid); - } - return uuid; } private ComponentsUtils getComponentsUtils() { @@ -212,23 +163,15 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons // Extracted for purpose of clear method name, for logback %M parameter private void inHttpRequest() { - if (isInfoLog()) { - log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); - } else { - log.debug("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); - } + log.info("{} {} {}", sr.getMethod(), sr.getRequestURI(), sr.getProtocol()); } // Extracted for purpose of clear method name, for logback %M parameter private void outHttpResponse(ContainerResponseContext responseContext) { - if (isInfoLog()) { - log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); - } else { - log.debug("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); - } + log.info("{} {} {} SC=\"{}\"", sr.getMethod(), sr.getRequestURI(), sr.getProtocol(), responseContext.getStatus()); } - private boolean isInfoLog() { + private boolean isLoggedRequest() { boolean logRequest = true; Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration(); String requestURI = sr.getRequestURI(); @@ -237,9 +180,4 @@ public class BeServletFilter implements ContainerRequestFilter, ContainerRespons } return logRequest; } - - // Extracted for purpose of clear method name, for logback %M parameter - private void uuidGeneration(String uuid) { - log.info("No requestID provided -> Generated UUID {}", uuid); - } } diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java index 158cc2d842..5ccbb26f93 100644 --- a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ComponentsAvailabilityFilter.java @@ -22,6 +22,7 @@ package org.openecomp.sdc.be.filters; import com.google.gson.Gson; import com.google.gson.GsonBuilder; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.be.components.health.HealthCheckBusinessLogic; import org.openecomp.sdc.be.dao.api.ActionStatus; import org.openecomp.sdc.be.impl.ComponentsUtils; @@ -34,6 +35,7 @@ import org.openecomp.sdc.common.log.enums.Severity; import org.openecomp.sdc.common.log.wrappers.Logger; import org.openecomp.sdc.common.log.wrappers.LoggerSdcAudit; import org.openecomp.sdc.exception.ResponseFormat; +import org.slf4j.MarkerFactory; import org.springframework.web.context.WebApplicationContext; import javax.annotation.Priority; @@ -92,7 +94,7 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter { List<HealthCheckInfo> healthCheckInfos = new ArrayList<>(); HealthCheckBusinessLogic healthCheckBusinessLogic = getHealthCheckBL(servletContext); - healthCheckBusinessLogic.getJanusGraphHealthCheck(healthCheckInfos); // JanusGraph + healthCheckInfos.add(healthCheckBusinessLogic.getJanusGraphHealthCheck()); return healthCheckInfos; } @@ -124,12 +126,13 @@ public class ComponentsAvailabilityFilter implements ContainerRequestFilter { private void abortWith(ContainerRequestContext requestContext, String message, Response response) { - audit.log(sr.getRemoteAddr(), + audit.logExit(sr.getRemoteAddr(), requestContext, response.getStatusInfo(), LogLevel.ERROR, Severity.OK, - message); + message, + MarkerFactory.getMarker(ONAPLogConstants.Markers.EXIT.getName())); log.error(message); audit.clearMyData(); diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java new file mode 100644 index 0000000000..7bd9c46780 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/FilterConfiguration.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.filters; + +import org.onap.sdc.security.ISessionValidationFilterConfiguration; +import org.openecomp.sdc.be.config.Configuration; + +import java.util.List; + +public class FilterConfiguration implements ISessionValidationFilterConfiguration { + + protected Configuration config; + + public FilterConfiguration(org.openecomp.sdc.be.config.Configuration configuration) { + this.config = configuration; + } + + @Override + public String getSecurityKey() { + return config.getAuthCookie().getSecurityKey(); + } + + @Override + public long getMaxSessionTimeOut() { + return config.getAuthCookie().getMaxSessionTimeOut(); + } + + @Override + public long getSessionIdleTimeOut() { + return config.getAuthCookie().getSessionIdleTimeOut(); + } + + @Override + public String getRedirectURL() { + return config.getAuthCookie().getRedirectURL(); + } + + @Override + public List<String> getExcludedUrls() { + return config.getAuthCookie().getExcludedUrls(); + } + + @Override + public String getCookieName() { + return config.getAuthCookie().getCookieName(); + } + + @Override + public String getCookieDomain() { + return config.getAuthCookie().getDomain(); + } + + @Override + public String getCookiePath() { + return config.getAuthCookie().getPath(); + } + + @Override + public boolean isCookieHttpOnly() { + return config.getAuthCookie().isHttpOnly(); + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java new file mode 100644 index 0000000000..3ed14f139f --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/GatewayFilter.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.filters; + +import org.apache.http.HttpStatus; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.config.Configuration; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper; +import org.openecomp.sdc.common.api.FilterDecisionEnum; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.HttpHeaders; +import java.io.IOException; +import java.util.List; +import java.util.stream.Stream; + +@Component("gatewayFilter") +public class GatewayFilter implements Filter { + + private Configuration.CookieConfig authCookieConf; + private Configuration config; + private static final Logger log = Logger.getLogger(BeServletFilter.class); + + @Autowired + private ThreadLocalUtils threadLocalUtils; + @Autowired + private ComponentExceptionMapper componentExceptionMapper; + + + public GatewayFilter(org.openecomp.sdc.be.config.Configuration configuration) { + this.authCookieConf = configuration.getAuthCookie(); + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } + + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException { + + HttpServletRequest httpRequest = (HttpServletRequest) req; + HttpServletResponse httpResponse = (HttpServletResponse) res; + try { + if (isUrlFromWhiteList(httpRequest) || isConsumerBusinessLogic()) { + ThreadLocalsHolder.setApiType(FilterDecisionEnum.NA); + threadLocalUtils.setUserContextFromDB(httpRequest); + filterChain.doFilter(httpRequest, res); +// } else if (isCookieExist(httpRequest, authCookieConf.getCookieName())) { +// ThreadLocalsHolder.setApiType(FilterDecisionEnum.INTERNAL); +// filterChain.doFilter(httpRequest, res); +// } else { +// validateAuthHeaderExist(httpRequest); +// ThreadLocalsHolder.setApiType(FilterDecisionEnum.EXTERNAL); +// filterChain.doFilter(httpRequest, res); + } + } catch (ComponentException ce) { + componentExceptionMapper.writeToResponse(ce, httpResponse); + + } catch (WebApplicationException we) { + httpResponse.setStatus(we.getResponse().getStatus()); + setDefaultHttpParams(httpResponse); + httpResponse.getWriter().write(we.getMessage()); + + } catch (Exception ex) { + httpResponse.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR); + setDefaultHttpParams(httpResponse); + httpResponse.getWriter().write(ex.getMessage()); + } + } + + private void setDefaultHttpParams(HttpServletResponse httpResponse) { + httpResponse.setContentType("application/json"); + httpResponse.setCharacterEncoding("UTF-8"); + } + + private boolean isCookieExist(HttpServletRequest httpRequest, String cookieName) { + Cookie[] cookies = httpRequest.getCookies(); + if (cookies != null) { + for (Cookie cookie : cookies) { + if (cookie.getName().equals(cookieName)) { + return true; + } + } + } + return false; + } + + private boolean isHeaderExist(HttpServletRequest req, String headerName) { + return req.getHeader(headerName) != null; + } + + private void validateAuthHeaderExist(HttpServletRequest req) { + boolean authHeader = isHeaderExist(req, HttpHeaders.AUTHORIZATION); + if (!authHeader) throw new ByActionStatusComponentException(ActionStatus.AUTH_FAILED); + } + + private boolean isUrlFromWhiteList(HttpServletRequest httpRequest) { + String pathInfo; + List<String> excludedUrls = authCookieConf.getExcludedUrls(); + pathInfo = httpRequest.getPathInfo().toLowerCase(); + log.debug("SessionValidationFilter: white list validation -> PathInfo: {} ", pathInfo); + Stream<String> stream = excludedUrls.stream(); + pathInfo.getClass(); + return stream.anyMatch(pathInfo::matches); + } + + private Boolean isConsumerBusinessLogic() { + return config.getConsumerBusinessLogic(); + } + @Override + public void destroy() { + + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java new file mode 100644 index 0000000000..81920ce13c --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/PortalConfiguration.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.filters; + +import com.google.common.annotations.VisibleForTesting; +import org.apache.commons.lang.StringUtils; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.sdc.security.IPortalConfiguration; +import org.onap.sdc.security.PortalClient; + +import java.security.InvalidParameterException; + +public class PortalConfiguration implements IPortalConfiguration { + private static final String PROPERTY_NOT_SET = "%s property value is not set in portal.properties file"; + private String portalUser; + private String portalPassword; + private String ecompPortalRestURL; + private String portalAppName; + private String uebKey; + + public PortalConfiguration() throws org.onap.portalsdk.core.onboarding.exception.CipherUtilException { + this.portalUser = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.USER.value()); + this.portalPassword = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(PortalClient.PortalPropertiesEnum.PASSWORD.value()); + this.portalAppName = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(PortalClient.PortalPropertiesEnum.APP_NAME.value()); + this.ecompPortalRestURL = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.ECOMP_REST_URL.value()); + this.uebKey = org.onap.portalsdk.core.onboarding.util.PortalApiProperties.getProperty(org.onap.sdc.security.PortalClient.PortalPropertiesEnum.UEB_APP_KEY.value()); + } + + @VisibleForTesting + String getPortalProperty(String key) { + String value = PortalApiProperties.getProperty(key); + if (StringUtils.isEmpty(value)) { + throw new InvalidParameterException(String.format(PROPERTY_NOT_SET, key)); + } + return value; + } + + @Override + public String getPortalApiPrefix() { + return null; + } + + @Override + public long getMaxIdleTime() { + return 0; + } + + @Override + public String getUserAttributeName() { + return null; + } + + @Override + public boolean IsUseRestForFunctionalMenu() { + return false; + } + + @Override + public String getPortalApiImplClass() { + return null; + } + + @Override + public String getRoleAccessCentralized() { + return null; + } + + @Override + public boolean getUebListenersEnable() { + return false; + } + + @Override + public String getEcompRedirectUrl() { + return null; + } + + @Override + public String getEcompRestUrl() { + return ecompPortalRestURL; + } + + @Override + public String getPortalUser() { + return portalUser; + } + + @Override + public String getPortalPass() { + return portalPassword; + } + + @Override + public String getPortalAppName() { + return portalAppName; + } + + @Override + public String getUebAppKey() { + return uebKey; + } + + @Override + public String getAafNamespace() { + return null; + } + + @Override + public String getAuthNamespace() { + return null; + } + + @Override + public String getCspCookieName() { + return null; + } + + @Override + public String getCspGateKeeperProdKey() { + return null; + } + + @Override + public String getExtReqConnectionTimeout() { + return null; + } + + @Override + public String getExtReqReadTimeout() { + return null; + } +}
\ No newline at end of file diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java new file mode 100644 index 0000000000..4fc576b79d --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ReqValidationFilter.java @@ -0,0 +1,85 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.filters; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException; +import org.openecomp.sdc.be.components.impl.exceptions.ComponentException; +import org.openecomp.sdc.be.dao.api.ActionStatus; +import org.openecomp.sdc.be.servlets.exception.ComponentExceptionMapper; +import org.openecomp.sdc.common.api.UserRoleEnum; +import org.openecomp.sdc.common.datastructure.UserContext; +import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + +@Component("reqValidationFilter") +public class ReqValidationFilter implements Filter { + + private static final Logger log = Logger.getLogger(ReqValidationFilter.class); + @Autowired + public ComponentExceptionMapper componentExceptionMapper; + + @Override + public void init(FilterConfig filterConfig){ + + } + + @Override + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { + HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; + try { + log.debug("Validating User roles - filter"); + List<String> validRoles = Arrays.asList(UserRoleEnum.ADMIN.getName(), UserRoleEnum.DESIGNER.getName()); + UserContext userContext = ThreadLocalsHolder.getUserContext(); + + if (userContext != null && CollectionUtils.isNotEmpty(userContext.getUserRoles())) { + Set<String> userRoles = userContext.getUserRoles(); + if (!userRoles.stream().anyMatch(role -> validRoles.contains(role))) { + log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, "SDC", "User role is invalid: {}", userRoles); + throw new ByActionStatusComponentException(ActionStatus.AUTH_FAILED); + } + } + filterChain.doFilter(servletRequest, servletResponse); + } catch (ComponentException exp) { + componentExceptionMapper.writeToResponse(exp, httpResponse); + } + } + + @Override + public void destroy() { + + } +} diff --git a/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java new file mode 100644 index 0000000000..3eb067c8a9 --- /dev/null +++ b/catalog-be/src/main/java/org/openecomp/sdc/be/filters/ThreadLocalUtils.java @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.be.filters; + +import org.onap.sdc.security.AuthenticationCookie; +import org.onap.sdc.security.IUsersThreadLocalHolder; +import org.onap.sdc.security.PortalClient; +import org.onap.sdc.security.RestrictionAccessFilterException; +import org.openecomp.sdc.be.model.User; +import org.openecomp.sdc.be.user.UserBusinessLogic; +import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.datastructure.UserContext; +import org.openecomp.sdc.common.log.wrappers.Logger; +import org.openecomp.sdc.common.util.ThreadLocalsHolder; +import org.springframework.beans.factory.annotation.Autowired; + +import javax.servlet.http.HttpServletRequest; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; + +public class ThreadLocalUtils implements IUsersThreadLocalHolder { + + @Autowired + PortalClient portalClient; + + @Autowired + UserBusinessLogic userBusinessLogic; + + private static final Logger log = Logger.getLogger(ThreadLocalUtils.class); + + @Override + public void setUserContext(AuthenticationCookie authenticationCookie) { + UserContext userContext; + userContext = new UserContext(authenticationCookie.getUserID(), authenticationCookie.getRoles(), authenticationCookie.getFirstName(), authenticationCookie.getLastName()); + ThreadLocalsHolder.setUserContext(userContext); + } + + + protected void setUserContext(HttpServletRequest httpRequest) { + + String user_id = httpRequest.getHeader(Constants.USER_ID_HEADER); + if (user_id != null) { + String userRolesFromPortal = null; + Set<String> roles = null; + try { + userRolesFromPortal = portalClient.fetchUserRolesFromPortal(user_id); + roles = new HashSet<>(Arrays.asList(userRolesFromPortal)); + } catch (RestrictionAccessFilterException e) { + log.debug("Failed to fetch user ID - {} from portal", user_id); + log.debug(e.getMessage()); + } + UserContext userContext = new UserContext(user_id, roles, null, null); + ThreadLocalsHolder.setUserContext(userContext); + } else log.debug("user_id value in req header is null, userContext will not be initialized"); + } + + protected void setUserContextFromDB(HttpServletRequest httpRequest) { + String user_id = httpRequest.getHeader(Constants.USER_ID_HEADER); + //there are some internal request that have no user_id header e.g. healthcheck + if (user_id != null) { + updateUserContext(user_id); + } else log.debug("user_id value in req header is null, userContext will not be initialized"); + } + + protected void setUserContextFromDB(AuthenticationCookie authenticationCookie) { + String user_id = authenticationCookie.getUserID(); + updateUserContext(user_id); + } + + private void updateUserContext(String user_id) { + User user = userBusinessLogic.getUser(user_id, false); + Set<String> roles = new HashSet<>(Arrays.asList(user.getRole())); + UserContext userContext = new UserContext(user_id, roles, user.getFirstName(), user.getLastName()); + ThreadLocalsHolder.setUserContext(userContext); + } + +} |