diff options
Diffstat (limited to 'src/main/java/org')
7 files changed, 102 insertions, 69 deletions
diff --git a/src/main/java/org/onap/policy/clamp/clds/ClampServlet.java b/src/main/java/org/onap/policy/clamp/clds/ClampServlet.java index dcaa2acf3..ccde7cf11 100644 --- a/src/main/java/org/onap/policy/clamp/clds/ClampServlet.java +++ b/src/main/java/org/onap/policy/clamp/clds/ClampServlet.java @@ -1,6 +1,6 @@ /*- * ============LICENSE_START======================================================= - * ONAP CLAMP + * ONAP POLICY-CLAMP * ================================================================================ * Copyright (C) 2018, 2021 AT&T Intellectual Property. All rights * reserved. @@ -31,12 +31,14 @@ import java.io.IOException; import java.security.Principal; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.camel.component.servlet.CamelHttpTransportServlet; +import org.apache.commons.lang3.StringUtils; import org.onap.policy.clamp.authorization.SecureServicePermission; import org.springframework.context.ApplicationContext; import org.springframework.http.HttpStatus; @@ -46,6 +48,7 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.User; +import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; public class ClampServlet extends CamelHttpTransportServlet { @@ -70,9 +73,22 @@ public class ClampServlet extends CamelHttpTransportServlet { private static List<SecureServicePermission> permissionList; private synchronized List<String> loadDynamicAuthenticationClasses() { - return Arrays.stream(WebApplicationContextUtils.getWebApplicationContext(getServletContext()) - .getEnvironment().getProperty(AUTHENTICATION_CLASS).split(",")).map(String::trim) - .collect(Collectors.toList()); + WebApplicationContext webAppContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); + if (webAppContext != null) { + String authClassProperty = webAppContext.getEnvironment().getProperty(AUTHENTICATION_CLASS); + if (!StringUtils.isBlank(authClassProperty)) { + return Arrays.stream(authClassProperty.split(",")).map(String::trim) + .collect(Collectors.toList()); + } + logger.warn( + "No authentication classes defined in Clamp BE config " + AUTHENTICATION_CLASS + + " AAF authentication could be broken due to that"); + } else { + logger.error( + "WebApplicationContext is NULL, no authentication classes will be loaded in clamp BE" + + ", AAF authentication could be broken"); + } + return Collections.emptyList(); } private synchronized List<SecureServicePermission> getPermissionList() { diff --git a/src/main/java/org/onap/policy/clamp/clds/config/DefaultUserConfiguration.java b/src/main/java/org/onap/policy/clamp/clds/config/DefaultUserConfiguration.java index 015868141..bb7b76af3 100644 --- a/src/main/java/org/onap/policy/clamp/clds/config/DefaultUserConfiguration.java +++ b/src/main/java/org/onap/policy/clamp/clds/config/DefaultUserConfiguration.java @@ -1,8 +1,8 @@ /*- * ============LICENSE_START======================================================= - * ONAP CLAMP + * ONAP POLICY-CLAMP * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights + * Copyright (C) 2017-2018, 2021 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Modifications Copyright (c) 2019 Samsung @@ -73,6 +73,8 @@ public class DefaultUserConfiguration extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) { try { + // Do no remove the csrf as recommended by Sonar otherwise Put/post will not work + // Moreover this default user class is only used by dev, on prod we use AAF and this code will be disabled http.csrf().disable().httpBasic().and().authorizeRequests().antMatchers("/restservices/clds/v1/user/**") .authenticated().anyRequest().permitAll().and().sessionManagement() .maximumSessions(1); diff --git a/src/main/java/org/onap/policy/clamp/clds/sdc/controller/SdcSingleController.java b/src/main/java/org/onap/policy/clamp/clds/sdc/controller/SdcSingleController.java index 4ca6b1cf4..39e64e46b 100644 --- a/src/main/java/org/onap/policy/clamp/clds/sdc/controller/SdcSingleController.java +++ b/src/main/java/org/onap/policy/clamp/clds/sdc/controller/SdcSingleController.java @@ -1,8 +1,8 @@ /*- * ============LICENSE_START======================================================= - * ONAP CLAMP + * ONAP POLICY-CLAMP * ================================================================================ - * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights + * Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights * reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -26,9 +26,9 @@ package org.onap.policy.clamp.clds.sdc.controller; import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; +import java.security.SecureRandom; import java.util.Date; import java.util.Map.Entry; -import java.util.concurrent.ThreadLocalRandom; import org.onap.policy.clamp.clds.config.ClampProperties; import org.onap.policy.clamp.clds.config.sdc.SdcSingleControllerConfiguration; import org.onap.policy.clamp.clds.exception.sdc.controller.BlueprintParserException; @@ -261,7 +261,7 @@ public class SdcSingleController { try { // wait for a random time, so that 2 running Clamp will not treat // the same Notification at the same time - Thread.sleep(ThreadLocalRandom.current().nextInt(1, 10) * 1000L); + Thread.sleep((new SecureRandom().nextInt(10) + 1) * 1000L); logger.info("Notification received for service UUID:" + notificationData.getServiceUUID()); this.changeControllerStatus(SdcSingleControllerStatus.BUSY); csar = new CsarHandler(notificationData, this.sdcConfig.getSdcControllerName(), @@ -383,23 +383,28 @@ public class SdcSingleController { try { IComponentDoneStatusMessage message = new IComponentDoneStatusMessage() { - @Override public String getDistributionID() { + @Override + public String getDistributionID() { return notificationData.getDistributionID(); } - @Override public String getConsumerID() { + @Override + public String getConsumerID() { return sdcConfig.getConsumerID(); } - @Override public long getTimestamp() { + @Override + public long getTimestamp() { return System.currentTimeMillis(); } - @Override public DistributionStatusEnum getStatus() { + @Override + public DistributionStatusEnum getStatus() { return status; } - @Override public String getComponentName() { + @Override + public String getComponentName() { return sdcConfig.getUser(); } }; diff --git a/src/main/java/org/onap/policy/clamp/clds/util/LoggingUtils.java b/src/main/java/org/onap/policy/clamp/clds/util/LoggingUtils.java index b5f9837b0..4145844a2 100644 --- a/src/main/java/org/onap/policy/clamp/clds/util/LoggingUtils.java +++ b/src/main/java/org/onap/policy/clamp/clds/util/LoggingUtils.java @@ -58,13 +58,19 @@ public class LoggingUtils { private static final String DATE_FORMATTER_ISO = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX"; - /** String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. */ + /** + * String constant for messages <tt>ENTERING</tt>, <tt>EXITING</tt>, etc. + */ private static final String EMPTY_MESSAGE = ""; - /** Logger delegate. */ + /** + * Logger delegate. + */ private final Logger mlogger; - /** Automatic UUID, overrideable per adapter or per invocation. */ + /** + * Automatic UUID, overrideable per adapter or per invocation. + */ private static final UUID sInstanceUUID = UUID.randomUUID(); /** @@ -98,7 +104,7 @@ public class LoggingUtils { * Set time related logging variables in thread local data via MDC. * * @param beginTimeStamp Start time - * @param endTimeStamp End time + * @param endTimeStamp End time */ public static void setTimeContext(@NotNull Date beginTimeStamp, @NotNull Date endTimeStamp) { MDC.put("EntryTimestamp", generateTimestampStr(beginTimeStamp)); @@ -109,9 +115,9 @@ public class LoggingUtils { /** * Set response related logging variables in thread local data via MDC. * - * @param code Response code ("0" indicates success) + * @param code Response code ("0" indicates success) * @param description Response description - * @param className class name of invoking class + * @param className class name of invoking class */ public static void setResponseContext(String code, String description, String className) { MDC.put("ResponseCode", code); @@ -123,7 +129,7 @@ public class LoggingUtils { /** * Set target related logging variables in thread local data via MDC. * - * @param targetEntity Target entity (an external/sub component, for ex. "sdc") + * @param targetEntity Target entity (an external/sub component, for ex. "sdc") * @param targetServiceName Target service name (name of API invoked on target) */ public static void setTargetContext(String targetEntity, String targetServiceName) { @@ -134,7 +140,7 @@ public class LoggingUtils { /** * Set error related logging variables in thread local data via MDC. * - * @param code Error code + * @param code Error code * @param description Error description */ public static void setErrorContext(String code, String description) { @@ -175,7 +181,7 @@ public class LoggingUtils { /** * Report <tt>ENTERING</tt> marker. * - * @param request non-null incoming request (wrapper) + * @param request non-null incoming request (wrapper) * @param serviceName service name */ public void entering(HttpServletRequest request, String serviceName) { @@ -183,16 +189,16 @@ public class LoggingUtils { checkNotNull(request); // Extract MDC values from standard HTTP headers. final String requestId = - defaultToUuid(request.getHeader(OnapLogConstants.Headers.REQUEST_ID)); + defaultToUuid(request.getHeader(OnapLogConstants.Headers.REQUEST_ID)); final String invocationId = - defaultToUuid(request.getHeader(OnapLogConstants.Headers.INVOCATION_ID)); + defaultToUuid(request.getHeader(OnapLogConstants.Headers.INVOCATION_ID)); final String partnerName = - defaultToEmpty(request.getHeader(OnapLogConstants.Headers.PARTNER_NAME)); + defaultToEmpty(request.getHeader(OnapLogConstants.Headers.PARTNER_NAME)); // Default the partner name to the user name used to login to clamp if (partnerName.equalsIgnoreCase(EMPTY_MESSAGE)) { MDC.put(OnapLogConstants.Mdcs.PARTNER_NAME, - AuthorizationController.getPrincipalName(SecurityContextHolder.getContext())); + AuthorizationController.getPrincipalName(SecurityContextHolder.getContext())); } // Set standard MDCs. Override this entire method if you want to set @@ -200,7 +206,7 @@ public class LoggingUtils { // depending on where you need them to appear, OR extend the // ServiceDescriptor to add them. MDC.put(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC) - .format(DateTimeFormatter.ofPattern(DATE_FORMATTER_ISO))); + .format(DateTimeFormatter.ofPattern(DATE_FORMATTER_ISO))); MDC.put(OnapLogConstants.Mdcs.REQUEST_ID, requestId); MDC.put(OnapLogConstants.Mdcs.INVOCATION_ID, invocationId); MDC.put(OnapLogConstants.Mdcs.CLIENT_IP_ADDRESS, defaultToEmpty(request.getRemoteAddr())); @@ -217,7 +223,7 @@ public class LoggingUtils { // Set the Response Status code to in progress MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE, - OnapLogConstants.ResponseStatus.INPROGRESS.toString()); + OnapLogConstants.ResponseStatus.INPROGRESS.toString()); setElapsedTime(); this.mlogger.info(OnapLogConstants.Markers.ENTRY, "Entering"); @@ -226,18 +232,17 @@ public class LoggingUtils { /** * Report <tt>EXITING</tt> marker. * - * - * @param code response code - * @param descrption response description - * @param severity response severity - * @param status response status code + * @param code response code + * @param description response description + * @param severity response severity + * @param status response status code */ - public void exiting(int code, String descrption, Level severity, - OnapLogConstants.ResponseStatus status) { + public void exiting(int code, String description, Level severity, + OnapLogConstants.ResponseStatus status) { try { MDC.put(OnapLogConstants.Mdcs.RESPONSE_CODE, defaultToEmpty(code)); - MDC.put(OnapLogConstants.Mdcs.RESPONSE_DESCRIPTION, defaultToEmpty(descrption)); + MDC.put(OnapLogConstants.Mdcs.RESPONSE_DESCRIPTION, defaultToEmpty(description)); MDC.put(OnapLogConstants.Mdcs.RESPONSE_SEVERITY, defaultToEmpty(severity)); MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE, defaultToEmpty(status)); @@ -249,12 +254,11 @@ public class LoggingUtils { } private void setElapsedTime() { - ZonedDateTime startTime = - ZonedDateTime.parse(MDC.get(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP), - DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneOffset.UTC)); - ZonedDateTime endTime = ZonedDateTime.now(ZoneOffset.UTC); - long duration = ChronoUnit.MILLIS.between(startTime, endTime); - MDC.put(OnapLogConstants.Mdcs.ELAPSED_TIME, String.valueOf(duration)); + String entryTimestamp = MDC.get(OnapLogConstants.Mdcs.ENTRY_TIMESTAMP); + MDC.put(OnapLogConstants.Mdcs.ELAPSED_TIME, String.valueOf(ChronoUnit.MILLIS + .between(ZonedDateTime.parse(entryTimestamp != null ? entryTimestamp : ZonedDateTime.now(ZoneOffset.UTC) + .format(DateTimeFormatter.ofPattern(DATE_FORMATTER_ISO)), + DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneOffset.UTC)), ZonedDateTime.now(ZoneOffset.UTC)))); } /** @@ -271,13 +275,13 @@ public class LoggingUtils { * Report pending invocation with <tt>INVOKE</tt> marker, * setting standard ONAP logging headers automatically. * - * @param con The HTTP url connection - * @param targetEntity The target entity + * @param con The HTTP url connection + * @param targetEntity The target entity * @param targetServiceName The target service name * @return The HTTP url connection */ public HttpURLConnection invoke(final HttpURLConnection con, String targetEntity, - String targetServiceName) { + String targetServiceName) { return this.invokeGeneric(con, targetEntity, targetServiceName); } @@ -285,7 +289,7 @@ public class LoggingUtils { * Report pending invocation with <tt>INVOKE</tt> marker, * setting standard ONAP logging headers automatically. * - * @param targetEntity The target entity + * @param targetEntity The target entity * @param targetServiceName The target service name */ public void invoke(String targetEntity, String targetServiceName) { @@ -304,13 +308,13 @@ public class LoggingUtils { * Report pending invocation with <tt>INVOKE</tt> marker, * setting standard ONAP logging headers automatically. * - * @param con The HTTPS url connection - * @param targetEntity The target entity + * @param con The HTTPS url connection + * @param targetEntity The target entity * @param targetServiceName The target service name * @return The HTTPS url connection */ public HttpsURLConnection invokeHttps(final HttpsURLConnection con, String targetEntity, - String targetServiceName) { + String targetServiceName) { return this.invokeGeneric(con, targetEntity, targetServiceName); } @@ -319,7 +323,7 @@ public class LoggingUtils { */ public void invokeReturn() { MDC.put(OnapLogConstants.Mdcs.RESPONSE_STATUS_CODE, - OnapLogConstants.ResponseStatus.COMPLETE.toString()); + OnapLogConstants.ResponseStatus.COMPLETE.toString()); // Add the Invoke-return marker and clear the needed MDC this.mlogger.info(OnapLogConstants.Markers.INVOKE_RETURN, "INVOKE-RETURN"); invokeReturnContext(); @@ -328,7 +332,7 @@ public class LoggingUtils { /** * Dependency-free nullcheck. * - * @param in to be checked + * @param in to be checked * @param <T> argument (and return) type * @return input arg */ @@ -368,16 +372,16 @@ public class LoggingUtils { /** * Set target related logging variables in thread local data via MDC. * - * @param targetEntity Target entity (an external/sub component, for ex. "sdc") + * @param targetEntity Target entity (an external/sub component, for ex. "sdc") * @param targetServiceName Target service name (name of API invoked on target) - * @param invocationId The invocation ID + * @param invocationId The invocation ID */ private void invokeContext(String targetEntity, String targetServiceName, String invocationId) { MDC.put(OnapLogConstants.Mdcs.TARGET_ENTITY, defaultToEmpty(targetEntity)); MDC.put(OnapLogConstants.Mdcs.TARGET_SERVICE_NAME, defaultToEmpty(targetServiceName)); MDC.put(OnapLogConstants.Mdcs.INVOCATIONID_OUT, invocationId); MDC.put(OnapLogConstants.Mdcs.INVOKE_TIMESTAMP, ZonedDateTime.now(ZoneOffset.UTC) - .format(DateTimeFormatter.ofPattern(DATE_FORMATTER_ISO))); + .format(DateTimeFormatter.ofPattern(DATE_FORMATTER_ISO))); } /** @@ -392,15 +396,15 @@ public class LoggingUtils { } private <T extends URLConnection> T invokeGeneric(final T con, String targetEntity, - String targetServiceName) { + String targetServiceName) { final String invocationId = UUID.randomUUID().toString(); // Set standard HTTP headers on (southbound request) builder. con.setRequestProperty(OnapLogConstants.Headers.REQUEST_ID, - defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.REQUEST_ID))); + defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.REQUEST_ID))); con.setRequestProperty(OnapLogConstants.Headers.INVOCATION_ID, invocationId); con.setRequestProperty(OnapLogConstants.Headers.PARTNER_NAME, - defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.PARTNER_NAME))); + defaultToEmpty(MDC.get(OnapLogConstants.Mdcs.PARTNER_NAME))); invokeContext(targetEntity, targetServiceName, invocationId); diff --git a/src/main/java/org/onap/policy/clamp/policy/microservice/MicroServicePolicy.java b/src/main/java/org/onap/policy/clamp/policy/microservice/MicroServicePolicy.java index 2e5db8e24..be5e7917c 100644 --- a/src/main/java/org/onap/policy/clamp/policy/microservice/MicroServicePolicy.java +++ b/src/main/java/org/onap/policy/clamp/policy/microservice/MicroServicePolicy.java @@ -26,6 +26,7 @@ package org.onap.policy.clamp.policy.microservice; import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import java.io.Serializable; +import java.security.SecureRandom; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; @@ -130,7 +131,7 @@ public class MicroServicePolicy extends Policy implements Serializable { this(Policy.generatePolicyName("MICROSERVICE", service.getName(), service.getVersion(), loopElementModel.getPolicyModels().first().getPolicyAcronym() + '_' + loopElementModel.getPolicyModels().first().getVersion(), - RandomStringUtils.randomAlphanumeric(3)), + RandomStringUtils.random(3, 0, 0, true, true, null, new SecureRandom())), loopElementModel.getPolicyModels().first(), false, new JsonObject(), loopElementModel, null, null); this.updateJsonRepresentation(toscaConverter, service); } diff --git a/src/main/java/org/onap/policy/clamp/policy/operational/OperationalPolicy.java b/src/main/java/org/onap/policy/clamp/policy/operational/OperationalPolicy.java index 5b29f319c..1646a7cc7 100644 --- a/src/main/java/org/onap/policy/clamp/policy/operational/OperationalPolicy.java +++ b/src/main/java/org/onap/policy/clamp/policy/operational/OperationalPolicy.java @@ -30,6 +30,7 @@ import com.google.gson.JsonObject; import com.google.gson.annotations.Expose; import java.io.Serializable; import java.io.UnsupportedEncodingException; +import java.security.SecureRandom; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; @@ -114,7 +115,7 @@ public class OperationalPolicy extends Policy implements Serializable { this(Policy.generatePolicyName("OPERATIONAL", service.getName(), service.getVersion(), loopElementModel.getPolicyModels().first().getPolicyAcronym() + '_' + loopElementModel.getPolicyModels().first().getVersion(), - RandomStringUtils.randomAlphanumeric(3)), new JsonObject(), + RandomStringUtils.random(3, 0, 0, true, true, null, new SecureRandom())), new JsonObject(), new JsonObject(), loopElementModel.getPolicyModels().first(), loopElementModel, null, null); this.setLoop(loop); this.updateJsonRepresentation(toscaConverter, service); @@ -132,7 +133,7 @@ public class OperationalPolicy extends Policy implements Serializable { ToscaConverterWithDictionarySupport toscaConverter) { this(Policy.generatePolicyName("OPERATIONAL", service.getName(), service.getVersion(), policyModel.getPolicyAcronym() + '_' + policyModel.getVersion(), - RandomStringUtils.randomAlphanumeric(3)), + RandomStringUtils.random(3, 0, 0, true, true, null, new SecureRandom())), new JsonObject(), new JsonObject(), policyModel, null, null, null); this.setLoop(loop); diff --git a/src/main/java/org/onap/policy/clamp/policy/pdpgroup/PdpGroupPayload.java b/src/main/java/org/onap/policy/clamp/policy/pdpgroup/PdpGroupPayload.java index a10f6df7d..c6b44076f 100644 --- a/src/main/java/org/onap/policy/clamp/policy/pdpgroup/PdpGroupPayload.java +++ b/src/main/java/org/onap/policy/clamp/policy/pdpgroup/PdpGroupPayload.java @@ -62,7 +62,7 @@ public class PdpGroupPayload { * Constructor that takes a list of actions in input. * * @param listOfPdpActions The list of actions that needs to be done. - * e.g: {"Pdpactions":["DELETE/PdpGroup1/PdpSubGroup1/PolicyName1/1.0.0",....]} + * e.g: {"Pdpactions":["DELETE/PdpGroup1/PdpSubGroup1/PolicyName1/1.0.0",....]} * @throws PdpGroupPayloadException in case of issues to read the listOfActions */ public PdpGroupPayload(final JsonElement listOfPdpActions) throws PdpGroupPayloadException { @@ -74,7 +74,7 @@ public class PdpGroupPayload { * This method converts the list of actions directly to the pdp payload query as String. * * @param listOfPdpActions The list of actions that needs to be done. - * e.g: {"Pdpactions":["DELETE/PdpGroup1/PdpSubGroup1/PolicyName1/1.0.0",....]} + * e.g: {"Pdpactions":["DELETE/PdpGroup1/PdpSubGroup1/PolicyName1/1.0.0",....]} * @return The string containing the PDP payload that can be sent directly * @throws PdpGroupPayloadException in case of issues to read the listOfActions */ @@ -115,12 +115,16 @@ public class PdpGroupPayload { newSubGroup.setPdpType(pdpSubGroup); newSubGroup.setAction(DeploymentSubGroup.Action.valueOf(action)); newSubGroup.setPolicies(Arrays.asList(new ToscaConceptIdentifier(policyName, policyVersion))); - // Then the group - DeploymentGroup newGroup = new DeploymentGroup(); - newGroup.setName(pdpGroup); - newGroup.setDeploymentSubgroups(Arrays.asList(newSubGroup)); // Add to deployment Groups structure - this.deploymentGroups.getGroups().add(newGroup); + this.deploymentGroups.getGroups().stream().filter(group -> + group.getName().equals(pdpGroup)).findFirst() + .ifPresentOrElse(group -> group.getDeploymentSubgroups().add(newSubGroup), + () -> { + DeploymentGroup newGroup = new DeploymentGroup(); + newGroup.setName(pdpGroup); + newGroup.setDeploymentSubgroups(new ArrayList<>(Arrays.asList(newSubGroup))); + this.deploymentGroups.getGroups().add(newGroup); + }); } /** |