diff options
28 files changed, 557 insertions, 242 deletions
diff --git a/extra/sql/bulkload/create-tables.sql b/extra/sql/bulkload/create-tables.sql index 6d490c30..93c80cb3 100644 --- a/extra/sql/bulkload/create-tables.sql +++ b/extra/sql/bulkload/create-tables.sql @@ -16,7 +16,7 @@ create table loops ( name varchar(255) not null, - blueprint_yaml varchar(255) not null, + blueprint_yaml MEDIUMTEXT not null, dcae_blueprint_id varchar(255), dcae_deployment_id varchar(255), dcae_deployment_status_url varchar(255), @@ -36,7 +36,7 @@ create table micro_service_policies ( name varchar(255) not null, json_representation json not null, - policy_tosca varchar(255) not null, + policy_tosca MEDIUMTEXT not null, properties json, shared bit not null, primary key (name) diff --git a/src/main/java/org/onap/clamp/authorization/AuthorizationController.java b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java new file mode 100644 index 00000000..20610275 --- /dev/null +++ b/src/main/java/org/onap/clamp/authorization/AuthorizationController.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 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.onap.clamp.authorization; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.util.Date; + +import javax.ws.rs.NotAuthorizedException; + +import org.apache.camel.Exchange; +import org.onap.clamp.clds.config.ClampProperties; +import org.onap.clamp.clds.service.SecureServiceBase; +import org.onap.clamp.clds.service.SecureServicePermission; +import org.onap.clamp.clds.util.LoggingUtils; +import org.onap.clamp.util.PrincipalUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +/** + * Create CLDS Event. + */ +@Component +public class AuthorizationController { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(SecureServiceBase.class); + protected static final EELFLogger auditLogger = EELFManager.getInstance().getMetricsLogger(); + protected static final EELFLogger securityLogger = EELFManager.getInstance().getSecurityLogger(); + + // By default we'll set it to a default handler + @Autowired + private ClampProperties refProp; + + private SecurityContext securityContext = SecurityContextHolder.getContext(); + private final static String permPrefix = "security.permission.type."; + private final static String permInstance = "security.permission.instance"; + + public AuthorizationController() { + } + /** + * Insert event using process variables. + * + * @param camelExchange + * The Camel Exchange object containing the properties + * @param actionState + * The action state that is used instead of the one in exchange property + */ + + public void authorize (Exchange camelExchange, String typeVar, String instanceVar, String action) { + String type = refProp.getStringValue(permPrefix + typeVar); + String instance = refProp.getStringValue(permInstance); + + if (null == type || type.isEmpty()) { + //authorization is turned off, since the permission is not defined + return; + } + if (null != instanceVar && !instanceVar.isEmpty()) { + instance = instanceVar; + } + String principalName = PrincipalUtils.getPrincipalName(); + SecureServicePermission perm = SecureServicePermission.create(type, instance, action); + Date startTime = new Date(); + LoggingUtils.setTargetContext("Clamp", "authorize"); + LoggingUtils.setTimeContext(startTime, new Date()); + securityLogger.debug("checking if {} has permission: {}", principalName, perm); + try { + isUserPermitted(perm); + } catch (NotAuthorizedException nae) { + String msg = principalName + " does not have permission: " + perm; + LoggingUtils.setErrorContext("100", "Authorization Error"); + securityLogger.warn(msg); + throw new NotAuthorizedException(msg); + } + } + + private boolean isUserPermitted(SecureServicePermission inPermission) { + boolean authorized = false; + String principalName = PrincipalUtils.getPrincipalName(); + // check if the user has the permission key or the permission key with a + // combination of all instance and/or all action. + if (hasRole(inPermission.getKey())) { + auditLogger.info("{} authorized because user has permission with * for instance: {}", principalName, inPermission.getKey()); + authorized = true; + // the rest of these don't seem to be required - isUserInRole method + // appears to take * as a wildcard + } else if (hasRole(inPermission.getKeyAllInstance())) { + auditLogger.info("{} authorized because user has permission with * for instance: {}", principalName, inPermission.getKey()); + authorized = true; + } else if (hasRole(inPermission.getKeyAllInstanceAction())) { + auditLogger.info("{} authorized because user has permission with * for instance and * for action: {}", principalName, inPermission.getKey()); + authorized = true; + } else if (hasRole(inPermission.getKeyAllAction())) { + auditLogger.info("{} authorized because user has permission with * for action: {}", principalName, inPermission.getKey()); + authorized = true; + } else { + throw new NotAuthorizedException(""); + } + return authorized; + } + + public boolean isUserPermittedNoException(SecureServicePermission inPermission) { + try { + return isUserPermitted (inPermission); + } catch (NotAuthorizedException e) { + return false; + } + } + + protected boolean hasRole(String role) { + Authentication authentication = PrincipalUtils.getSecurityContext().getAuthentication(); + if (authentication == null) { + return false; + } + for (GrantedAuthority auth : authentication.getAuthorities()) { + if (role.equals(auth.getAuthority())) + return true; + } + return false; + } + +} diff --git a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java index 059cc2b2..8781fc34 100644 --- a/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java +++ b/src/main/java/org/onap/clamp/clds/client/DcaeHttpConnectionManager.java @@ -19,7 +19,7 @@ * ============LICENSE_END============================================ * Modifications copyright (c) 2018 Nokia * =================================================================== - * + * */ package org.onap.clamp.clds.client; @@ -42,20 +42,17 @@ import org.onap.clamp.clds.util.LoggingUtils; import org.springframework.stereotype.Component; /** - * + * * This class manages the HTTP and HTTPS connections to DCAE. * */ @Component public class DcaeHttpConnectionManager { - protected static final EELFLogger logger = EELFManager.getInstance() - .getLogger(DcaeHttpConnectionManager.class); - protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); - private static final String DCAE_REQUEST_FAILED_LOG = "Request Failed - response payload="; - + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(DcaeHttpConnectionManager.class); + protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger(); + private static final String DCAE_REQUEST_FAILED_LOG = "Request Failed - response payload="; - private String doHttpsQuery(URL url, String requestMethod, String payload, String contentType) - throws IOException { + private String doHttpsQuery(URL url, String requestMethod, String payload, String contentType) throws IOException { logger.info("Using HTTPS URL to contact DCAE:" + url.toString()); HttpsURLConnection secureConnection = (HttpsURLConnection) url.openConnection(); secureConnection.setRequestMethod(requestMethod); @@ -87,12 +84,11 @@ public class DcaeHttpConnectionManager { } } - private String doHttpQuery(URL url, String requestMethod, String payload, String contentType) - throws IOException { - LoggingUtils utils = new LoggingUtils (logger); + private String doHttpQuery(URL url, String requestMethod, String payload, String contentType) throws IOException { + LoggingUtils utils = new LoggingUtils(logger); logger.info("Using HTTP URL to contact DCAE:" + url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); - connection = utils.invoke(connection,"DCAE", requestMethod); + connection = utils.invoke(connection, "DCAE", requestMethod); connection.setRequestMethod(requestMethod); connection.setRequestProperty("X-ECOMP-RequestID", LoggingUtils.getRequestId()); if (payload != null && contentType != null) { @@ -126,21 +122,21 @@ public class DcaeHttpConnectionManager { /** * This method does a HTTP/HTTPS query to DCAE with parameters specified. - * + * * @param url - * The string HTTP or HTTPS that mustr be used to connect + * The string HTTP or HTTPS that mustr be used to connect * @param requestMethod - * The Request Method (PUT, POST, GET, DELETE, etc ...) + * The Request Method (PUT, POST, GET, DELETE, etc ...) * @param payload - * The payload if any, in that case an ouputstream is opened + * The payload if any, in that case an ouputstream is opened * @param contentType - * The "application/json or application/xml, or whatever" + * The "application/json or application/xml, or whatever" * @return The payload of the answer * @throws IOException - * In case of issue with the streams + * In case of issue with the streams */ public String doDcaeHttpQuery(String url, String requestMethod, String payload, String contentType) - throws IOException { + throws IOException { URL urlObj = new URL(url); if (url.contains("https://")) { // Support for HTTPS return doHttpsQuery(urlObj, requestMethod, payload, contentType); diff --git a/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java b/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java index d1beb956..8af1286c 100644 --- a/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java +++ b/src/main/java/org/onap/clamp/clds/config/CldsUserJsonDecoder.java @@ -5,32 +5,30 @@ * Copyright (C) 2017-2018 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. + * 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 + * + * 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.onap.clamp.clds.config; import com.google.gson.JsonParseException; -import com.google.gson.reflect.TypeToken; + import java.io.IOException; import java.io.InputStream; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; -import java.util.List; import org.apache.commons.io.IOUtils; import org.onap.clamp.clds.exception.CldsUsersException; import org.onap.clamp.clds.service.CldsUser; @@ -39,13 +37,13 @@ import org.onap.clamp.clds.util.JsonUtils; public class CldsUserJsonDecoder { /** - * This method decodes the JSON file provided to a CldsUser Array. The - * stream is closed after this call, this is not possible to reuse it. - * + * This method decodes the JSON file provided to a CldsUser Array. The stream is + * closed after this call, this is not possible to reuse it. + * * @param cldsUsersFile - * The inputStream containing the users json file - * @return CldsUser[] Array containing a list of the user defined in the - * JSON file + * The inputStream containing the users json file + * @return CldsUser[] Array containing a list of the user defined in the JSON + * file */ public static CldsUser[] decodeJson(InputStream cldsUsersFile) { try { diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java index b60f0728..b65a994a 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandler.java @@ -29,6 +29,7 @@ import com.att.eelf.configuration.EELFManager; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @@ -135,7 +136,7 @@ public class CsarHandler { blueprintArtifact .setBlueprintInvariantServiceUuid(this.getSdcNotification().getServiceInvariantUUID()); try (InputStream stream = zipFile.getInputStream(entry)) { - blueprintArtifact.setDcaeBlueprint(IOUtils.toString(stream)); + blueprintArtifact.setDcaeBlueprint(IOUtils.toString(stream, StandardCharsets.UTF_8)); } blueprintArtifact.setResourceAttached(searchForResourceByInstanceName(entry.getName().substring( entry.getName().indexOf(RESOURCE_INSTANCE_NAME_PREFIX) + RESOURCE_INSTANCE_NAME_PREFIX.length(), @@ -175,7 +176,7 @@ public class CsarHandler { try (ZipFile zipFile = new ZipFile(csarFilePath)) { ZipEntry entry = zipFile.getEntry(POLICY_DEFINITION_NAME_SUFFIX); if (entry != null) { - result = IOUtils.toString(zipFile.getInputStream(entry)); + result = IOUtils.toString(zipFile.getInputStream(entry), StandardCharsets.UTF_8); } else { logger.info("Policy model not found inside the CSAR file: " + csarFilePath); } diff --git a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java index a4ae14d0..6dc41834 100644 --- a/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/clds/sdc/controller/installer/CsarInstallerImpl.java @@ -28,6 +28,7 @@ import com.att.eelf.configuration.EELFLogger; import com.att.eelf.configuration.EELFManager; import com.google.gson.JsonObject; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -269,8 +270,8 @@ public class CsarInstallerImpl implements CsarInstaller { CldsTemplate template = new CldsTemplate(); template.setBpmnId("Sdc-Generated"); - template - .setBpmnText(IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream())); + template.setBpmnText(IOUtils.toString(appContext.getResource(configFiles.getBpmnXmlFilePath()).getInputStream(), + StandardCharsets.UTF_8)); template.setPropText( "{\"global\":[{\"name\":\"service\",\"value\":[\"" + blueprintArtifact.getDcaeBlueprint() + "\"]}]}"); template diff --git a/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java b/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java index 784d95e9..8a172abb 100644 --- a/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java +++ b/src/main/java/org/onap/clamp/clds/tosca/ToscaYamlToJsonConvertor.java @@ -82,13 +82,15 @@ public class ToscaYamlToJsonConvertor { this.cldsDao = cldsDao; } - @SuppressWarnings("unchecked") public String parseToscaYaml(String yamlString) { Yaml yaml = new Yaml(); - LinkedHashMap<String, Object> loadedYaml = (LinkedHashMap<String, Object>) yaml.load(yamlString); - LinkedHashMap<String, Object> nodeTypes = new LinkedHashMap<String, Object>(); - LinkedHashMap<String, Object> dataNodes = new LinkedHashMap<String, Object>(); + LinkedHashMap<String, Object> loadedYaml = yaml.load(yamlString); + if (loadedYaml == null) { + return ""; + } + LinkedHashMap<String, Object> nodeTypes = new LinkedHashMap<>(); + LinkedHashMap<String, Object> dataNodes = new LinkedHashMap<>(); JSONObject jsonEditorObject = new JSONObject(); JSONObject jsonParentObject = new JSONObject(); JSONObject jsonTempObject = new JSONObject(); diff --git a/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java b/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java index 9627445d..6e12f294 100644 --- a/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java +++ b/src/main/java/org/onap/clamp/loop/CsarInstallerImpl.java @@ -33,7 +33,6 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; -import java.util.Optional; import org.json.simple.parser.ParseException; import org.onap.clamp.clds.client.DcaeInventoryServices; @@ -53,6 +52,7 @@ import org.onap.clamp.policy.operational.OperationalPolicy; import org.onap.sdc.tosca.parser.enums.SdcTypes; import org.onap.sdc.toscaparser.api.NodeTemplate; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.yaml.snakeyaml.Yaml; @@ -71,63 +71,40 @@ public class CsarInstallerImpl implements CsarInstaller { public static final String MODEL_NAME_PREFIX = "Loop_"; @Autowired - protected LoopsRepository loopRepository; + LoopsRepository loopRepository; @Autowired - private BlueprintParser blueprintParser; + BlueprintParser blueprintParser; @Autowired - private ChainGenerator chainGenerator; + ChainGenerator chainGenerator; @Autowired DcaeInventoryServices dcaeInventoryService; - @Autowired - public void CsarInstallerImpl(LoopsRepository loopRepository, BlueprintParser blueprintParser, - ChainGenerator chainGenerator, DcaeInventoryServices dcaeInventoryService) { - this.loopRepository = loopRepository; - this.blueprintParser = blueprintParser; - this.chainGenerator = chainGenerator; - this.dcaeInventoryService = dcaeInventoryService; - } - @Override public boolean isCsarAlreadyDeployed(CsarHandler csar) throws SdcArtifactInstallerException { boolean alreadyInstalled = true; for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) { alreadyInstalled = alreadyInstalled - && loopRepository.existsById(buildModelName(csar, blueprint.getValue())); + && loopRepository.existsById(Loop.generateLoopName(csar.getSdcNotification().getServiceName(), + csar.getSdcNotification().getServiceVersion(), + blueprint.getValue().getResourceAttached().getResourceInstanceName(), + blueprint.getValue().getBlueprintArtifactName())); } return alreadyInstalled; } - public static String buildModelName(CsarHandler csar, BlueprintArtifact artifact) { - - return (MODEL_NAME_PREFIX + "_" + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v" - + csar.getSdcNotification().getServiceVersion() + "_" - + artifact.getResourceAttached().getResourceInstanceName().replaceAll(" ", "") + "_" - + artifact.getBlueprintArtifactName().replace(".yaml", "")).replace('.', '_'); - } - - public static String buildOperationalPolicyName(CsarHandler csar, BlueprintArtifact artifact) { - - return (MODEL_NAME_PREFIX + "_" + csar.getSdcCsarHelper().getServiceMetadata().getValue("name") + "_v" - + csar.getSdcNotification().getServiceVersion() + "_" - + artifact.getResourceAttached().getResourceInstanceName().replaceAll(" ", "") + "_" - + artifact.getBlueprintArtifactName().replace(".yaml", "")).replace('.', '_'); - } - @Override - @Transactional + @Transactional(propagation = Propagation.REQUIRED) public void installTheCsar(CsarHandler csar) throws SdcArtifactInstallerException, InterruptedException, PolicyModelException { try { logger.info("Installing the CSAR " + csar.getFilePath()); for (Entry<String, BlueprintArtifact> blueprint : csar.getMapOfBlueprints().entrySet()) { logger.info("Processing blueprint " + blueprint.getValue().getBlueprintArtifactName()); - createLoopFromBlueprint(csar, blueprint.getValue()); + loopRepository.save(createLoopFromBlueprint(csar, blueprint.getValue())); } - createPolicyModel(csar); logger.info("Successfully installed the CSAR " + csar.getFilePath()); } catch (IOException e) { throw new SdcArtifactInstallerException("Exception caught during the Csar installation in database", e); @@ -136,15 +113,6 @@ public class CsarInstallerImpl implements CsarInstaller { } } - private void createPolicyModel(CsarHandler csar) throws PolicyModelException { - try { - Optional<String> policyModelYaml = csar.getPolicyModelYaml(); - // save policy model into the database - } catch (IOException e) { - throw new PolicyModelException("TransformerException when decoding the YamlText", e); - } - } - private Loop createLoopFromBlueprint(CsarHandler csar, BlueprintArtifact blueprintArtifact) throws IOException, ParseException, InterruptedException { Loop newLoop = new Loop(); @@ -154,15 +122,8 @@ public class CsarInstallerImpl implements CsarInstaller { blueprintArtifact.getResourceAttached().getResourceInstanceName(), blueprintArtifact.getBlueprintArtifactName())); newLoop.setLastComputedState(LoopState.DESIGN); - for (MicroService microService : blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint())) { - newLoop.getMicroServicePolicies().add(new MicroServicePolicy(microService.getName(), - csar.getPolicyModelYaml().orElse(""), false, new JsonObject(), new HashSet<>(Arrays.asList(newLoop)))); - } - newLoop.setOperationalPolicies( - new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL", - csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(), - blueprintArtifact.getResourceAttached().getResourceInstanceName(), - blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject())))); + newLoop.setMicroServicePolicies(createMicroServicePolicies(csar, blueprintArtifact, newLoop)); + newLoop.setOperationalPolicies(createOperationalPolicies(csar, blueprintArtifact, newLoop)); // Set SVG XML computed // newLoop.setSvgRepresentation(svgRepresentation); newLoop.setGlobalPropertiesJson(createGlobalPropertiesJson(csar, blueprintArtifact)); @@ -172,6 +133,24 @@ public class CsarInstallerImpl implements CsarInstaller { return newLoop; } + private HashSet<OperationalPolicy> createOperationalPolicies(CsarHandler csar, BlueprintArtifact blueprintArtifact, + Loop newLoop) { + return new HashSet<>(Arrays.asList(new OperationalPolicy(Policy.generatePolicyName("OPERATIONAL", + csar.getSdcNotification().getServiceName(), csar.getSdcNotification().getServiceVersion(), + blueprintArtifact.getResourceAttached().getResourceInstanceName(), + blueprintArtifact.getBlueprintArtifactName()), newLoop, new JsonObject()))); + } + + private HashSet<MicroServicePolicy> createMicroServicePolicies(CsarHandler csar, + BlueprintArtifact blueprintArtifact, Loop newLoop) throws IOException { + HashSet<MicroServicePolicy> newSet = new HashSet<>(); + for (MicroService microService : blueprintParser.getMicroServices(blueprintArtifact.getDcaeBlueprint())) { + newSet.add(new MicroServicePolicy(microService.getName(), csar.getPolicyModelYaml().orElse(""), false, + new HashSet<>(Arrays.asList(newLoop)))); + } + return newSet; + } + private JsonObject createGlobalPropertiesJson(CsarHandler csar, BlueprintArtifact blueprintArtifact) { JsonObject globalProperties = new JsonObject(); globalProperties.add("dcaeDeployParameters", getAllBlueprintParametersInJson(blueprintArtifact)); diff --git a/src/main/java/org/onap/clamp/loop/Loop.java b/src/main/java/org/onap/clamp/loop/Loop.java index cc7f1803..a4cd86d0 100644 --- a/src/main/java/org/onap/clamp/loop/Loop.java +++ b/src/main/java/org/onap/clamp/loop/Loop.java @@ -91,7 +91,7 @@ public class Loop implements Serializable { @Column(columnDefinition = "json", name = "model_properties_json") private JsonObject modelPropertiesJson; - @Column(nullable = false, name = "blueprint_yaml") + @Column(columnDefinition = "MEDIUMTEXT", nullable = false, name = "blueprint_yaml") private String blueprint; @Expose diff --git a/src/main/java/org/onap/clamp/loop/LoopController.java b/src/main/java/org/onap/clamp/loop/LoopController.java index 7e451749..2bcce1e3 100644 --- a/src/main/java/org/onap/clamp/loop/LoopController.java +++ b/src/main/java/org/onap/clamp/loop/LoopController.java @@ -24,6 +24,8 @@ package org.onap.clamp.loop; import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; @@ -60,13 +62,17 @@ public class LoopController { public Loop updateOperationalPolicies(String loopName, JsonArray operationalPoliciesJson) { List<OperationalPolicy> operationalPolicies = JsonUtils.GSON .fromJson(operationalPoliciesJson, OPERATIONAL_POLICY_TYPE); - return loopService.updateOperationalPolicies(loopName, operationalPolicies); + return loopService.updateAndSaveOperationalPolicies(loopName, operationalPolicies); } public Loop updateMicroservicePolicies(String loopName, JsonArray microServicePoliciesJson) { List<MicroServicePolicy> microservicePolicies = JsonUtils.GSON .fromJson(microServicePoliciesJson, MICROSERVICE_POLICY_TYPE); - return loopService.updateMicroservicePolicies(loopName, microservicePolicies); + return loopService.updateAndSaveMicroservicePolicies(loopName, microservicePolicies); + } + + public Loop updateGlobalPropertiesJson(String loopName, JsonObject globalProperties){ + return loopService.updateAndSaveGlobalPropertiesJson(loopName, globalProperties); } public String getSVGRepresentation(String loopName) { diff --git a/src/main/java/org/onap/clamp/loop/LoopService.java b/src/main/java/org/onap/clamp/loop/LoopService.java index 91b4bdf8..cf2f4c66 100644 --- a/src/main/java/org/onap/clamp/loop/LoopService.java +++ b/src/main/java/org/onap/clamp/loop/LoopService.java @@ -26,6 +26,8 @@ package org.onap.clamp.loop; import java.util.List; import java.util.Set; import javax.persistence.EntityNotFoundException; + +import com.google.gson.JsonObject; import org.onap.clamp.policy.microservice.MicroservicePolicyService; import org.onap.clamp.policy.operational.OperationalPolicyService; import org.onap.clamp.policy.microservice.MicroServicePolicy; @@ -66,22 +68,42 @@ public class LoopService { return closedLoopByName.getSvgRepresentation(); } - Loop updateOperationalPolicies(String loopName, List<OperationalPolicy> newOperationalPolicies) { + Loop updateAndSaveOperationalPolicies(String loopName, List<OperationalPolicy> newOperationalPolicies) { Loop loop = findClosedLoopByName(loopName); - Set<OperationalPolicy> newPolicies = operationalPolicyService - .updatePolicies(loop, newOperationalPolicies); + updateOperationalPolicies(loop, newOperationalPolicies); + return loopsRepository.save(loop); + } - loop.setOperationalPolicies(newPolicies); + Loop updateAndSaveMicroservicePolicies(String loopName, List<MicroServicePolicy> newMicroservicePolicies) { + Loop loop = findClosedLoopByName(loopName); + updateMicroservicePolicies(loop, newMicroservicePolicies); return loopsRepository.save(loop); } - Loop updateMicroservicePolicies(String loopName, List<MicroServicePolicy> newMicroservicePolicies) { + Loop updateAndSaveGlobalPropertiesJson(String loopName, JsonObject newGlobalPropertiesJson) { Loop loop = findClosedLoopByName(loopName); - Set<MicroServicePolicy> newPolicies = microservicePolicyService - .updatePolicies(loop, newMicroservicePolicies); + updateGlobalPropertiesJson(loop, newGlobalPropertiesJson); + return loopsRepository.save(loop); + } + private Loop updateOperationalPolicies(Loop loop, List<OperationalPolicy> newOperationalPolicies) { + Set<OperationalPolicy> newPolicies = operationalPolicyService + .updatePolicies(loop, newOperationalPolicies); + + loop.setOperationalPolicies(newPolicies); + return loop; + } + + private Loop updateMicroservicePolicies(Loop loop, List<MicroServicePolicy> newMicroservicePolicies) { + Set<MicroServicePolicy> newPolicies = microservicePolicyService + .updatePolicies(loop, newMicroservicePolicies); loop.setMicroServicePolicies(newPolicies); - return loopsRepository.save(loop); + return loop; + } + + private Loop updateGlobalPropertiesJson(Loop loop, JsonObject newGlobalPropertiesJson) { + loop.setGlobalPropertiesJson(newGlobalPropertiesJson); + return loop; } private Loop findClosedLoopByName(String loopName) { diff --git a/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java b/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java index 7ebe0edb..857a3d74 100644 --- a/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java +++ b/src/main/java/org/onap/clamp/policy/microservice/MicroServicePolicy.java @@ -39,6 +39,8 @@ import javax.persistence.Table; import org.hibernate.annotations.Type; import org.hibernate.annotations.TypeDef; import org.hibernate.annotations.TypeDefs; +import org.onap.clamp.clds.tosca.ToscaYamlToJsonConvertor; +import org.onap.clamp.clds.util.JsonUtils; import org.onap.clamp.dao.model.jsontype.StringJsonUserType; import org.onap.clamp.loop.Loop; import org.onap.clamp.policy.Policy; @@ -66,7 +68,7 @@ public class MicroServicePolicy implements Serializable, Policy { @Column(name = "shared", nullable = false) private Boolean shared; - @Column(name = "policy_tosca", nullable = false) + @Column(columnDefinition = "MEDIUMTEXT", name = "policy_tosca", nullable = false) private String policyTosca; @Expose @@ -81,13 +83,22 @@ public class MicroServicePolicy implements Serializable, Policy { // serialization } + public MicroServicePolicy(String name, String policyTosca, Boolean shared, Set<Loop> usedByLoops) { + this.name = name; + this.policyTosca = policyTosca; + this.shared = shared; + this.jsonRepresentation = JsonUtils.GSON_JPA_MODEL + .fromJson(new ToscaYamlToJsonConvertor(null).parseToscaYaml(policyTosca), JsonObject.class); + this.usedByLoops = usedByLoops; + } + public MicroServicePolicy(String name, String policyTosca, Boolean shared, JsonObject jsonRepresentation, Set<Loop> usedByLoops) { this.name = name; this.policyTosca = policyTosca; this.shared = shared; - this.jsonRepresentation = jsonRepresentation; this.usedByLoops = usedByLoops; + this.jsonRepresentation = jsonRepresentation; } @Override diff --git a/src/main/java/org/onap/clamp/util/PrincipalUtils.java b/src/main/java/org/onap/clamp/util/PrincipalUtils.java new file mode 100644 index 00000000..ec089834 --- /dev/null +++ b/src/main/java/org/onap/clamp/util/PrincipalUtils.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 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============================================ + * Modifications copyright (c) 2018 Nokia + * =================================================================== + * + */ + +package org.onap.clamp.util; + +import java.util.Date; + +import org.onap.clamp.clds.service.DefaultUserNameHandler; +import org.onap.clamp.clds.service.UserNameHandler; +import org.onap.clamp.clds.util.LoggingUtils; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; + +public class PrincipalUtils { + private static UserNameHandler userNameHandler = new DefaultUserNameHandler(); + private static SecurityContext securityContext = SecurityContextHolder.getContext(); + + /** + * Get the Full name. + * + * @return + */ + public static String getUserName() { + String name = userNameHandler.retrieveUserName(securityContext); + Date startTime = new Date(); + LoggingUtils.setTargetContext("CLDS", "getUserName"); + LoggingUtils.setTimeContext(startTime, new Date()); + return name; + } + + /** + * Get the userId from AAF/CSP. + * + * @return + */ + public static String getUserId() { + return getUserName(); + } + + /** + * Get the principal name. + * + * @return + */ + public static String getPrincipalName() { + String principal = ((UserDetails)securityContext.getAuthentication().getPrincipal()).getUsername(); + String name = "Not found"; + if (principal != null) { + name = principal; + } + return name; + } + public static void setSecurityContext(SecurityContext securityContext) { + PrincipalUtils.securityContext = securityContext; + } + + public static SecurityContext getSecurityContext() { + return securityContext; + } +} diff --git a/src/main/resources/META-INF/resources/designer/index.html b/src/main/resources/META-INF/resources/designer/index.html index e30d7245..ec13e2a0 100644 --- a/src/main/resources/META-INF/resources/designer/index.html +++ b/src/main/resources/META-INF/resources/designer/index.html @@ -172,7 +172,6 @@ <script src="scripts/ExtraUserInfoCtrl.js"></script> <script src="scripts/ExtraUserInfoService.js"></script> <script src="scripts/saveConfirmationModalPopUpCtrl.js"></script> - <script src="scripts/CldsTemplateService.js"></script> <script src="scripts/GlobalPropertiesCtrl.js"></script> <script src="scripts/AlertService.js"></script> <script src="scripts/ToscaModelCtrl.js"></script> diff --git a/src/main/resources/META-INF/resources/designer/scripts/CldsOpenModelCtrl.js b/src/main/resources/META-INF/resources/designer/scripts/CldsOpenModelCtrl.js index a1625a93..0e3fce97 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/CldsOpenModelCtrl.js +++ b/src/main/resources/META-INF/resources/designer/scripts/CldsOpenModelCtrl.js @@ -32,9 +32,8 @@ app 'cldsModelService', '$location', 'dialogs', -'cldsTemplateService', function($scope, $rootScope, $modalInstance, $window, $uibModalInstance, cldsModelService, $location, - dialogs, cldsTemplateService) { + dialogs) { $scope.typeModel = 'template'; $scope.error = { flag : false, @@ -67,15 +66,6 @@ function($scope, $rootScope, $modalInstance, $window, $uibModalInstance, cldsMod $scope.close(); } } - cldsTemplateService.getSavedTemplate().then(function(pars) { - $scope.templateNamel = [] - for (var i = 0; i < pars.length; i++) { - $scope.templateNamel.push(pars[i].value); - } - setTimeout(function() { - setMultiSelect(); - }, 100); - }); function contains(a, obj) { var i = a && a.length > 0 ? a.length : 0; while (i--) { diff --git a/src/main/resources/META-INF/resources/designer/scripts/CldsTemplateService.js b/src/main/resources/META-INF/resources/designer/scripts/CldsTemplateService.js deleted file mode 100644 index 4a0e7147..00000000 --- a/src/main/resources/META-INF/resources/designer/scripts/CldsTemplateService.js +++ /dev/null @@ -1,67 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP CLAMP - * ================================================================================ - * Copyright (C) 2017-2018 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============================================ - * =================================================================== - * - */ - -app.service('cldsTemplateService', ['alertService', '$http', '$q', function (alertService, $http, $q) { - this.getTemplate = function(templateName){ - - - var def = $q.defer(); - var sets = []; - - var svcUrl = "/restservices/clds/v1/cldsTempate/template/" + templateName; - - $http.get(svcUrl) - .success(function(data){ - - def.resolve(data); - - }) - .error(function(data){ - - def.reject("Open Model not successful"); - }); - - return def.promise; - }; - this.getSavedTemplate=function(){ - - var def = $q.defer(); - var sets = []; - - var svcUrl = "/restservices/clds/v1/cldsTempate/template-names"; - - $http.get(svcUrl) - .success(function(data){ - - def.resolve(data); - - }) - .error(function(data){ - - def.reject("Open Model not successful"); - }); - - return def.promise; - }; - - }]); diff --git a/src/main/resources/META-INF/resources/designer/scripts/GlobalPropertiesCtrl.js b/src/main/resources/META-INF/resources/designer/scripts/GlobalPropertiesCtrl.js index 2ac959b4..e9ff4996 100644 --- a/src/main/resources/META-INF/resources/designer/scripts/GlobalPropertiesCtrl.js +++ b/src/main/resources/META-INF/resources/designer/scripts/GlobalPropertiesCtrl.js @@ -27,9 +27,8 @@ app.controller('GlobalPropertiesCtrl', [ 'cldsModelService', '$location', 'dialogs', -'cldsTemplateService', function($scope, $rootScope, $uibModalInstance, cldsModelService, $location, - dialogs, cldsTemplateService) { + dialogs) { $scope.$watch('name', function(newValue, oldValue) { var el = getGlobalProperty(); diff --git a/src/main/resources/application-noaaf.properties b/src/main/resources/application-noaaf.properties index 7dd0314a..632856e9 100644 --- a/src/main/resources/application-noaaf.properties +++ b/src/main/resources/application-noaaf.properties @@ -208,7 +208,7 @@ clamp.config.dcae.header.requestId = X-ECOMP-RequestID #Define user permission related parameters, the permission type can be changed but MUST be redefined in clds-users.properties in that case ! clamp.config.security.permission.type.cl=org.onap.clamp.clds.cl clamp.config.security.permission.type.cl.manage=org.onap.clamp.clds.cl.manage -clamp.config.security.permission.type.cl.event=org.onap.clds.cl.event +clamp.config.security.permission.type.cl.event=org.onap.clamp.clds.cl.event clamp.config.security.permission.type.filter.vf=org.onap.clamp.clds.filter.vf clamp.config.security.permission.type.template=org.onap.clamp.clds.template clamp.config.security.permission.type.tosca=org.onap.clamp.clds.tosca diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 8859c4b3..91c02ef7 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -223,7 +223,7 @@ clamp.config.dcae.header.requestId = X-ECOMP-RequestID #Define user permission related parameters, the permission type can be changed but MUST be redefined in clds-users.properties in that case ! clamp.config.security.permission.type.cl=org.onap.clamp.clds.cl clamp.config.security.permission.type.cl.manage=org.onap.clamp.clds.cl.manage -clamp.config.security.permission.type.cl.event=org.onap.clds.cl.event +clamp.config.security.permission.type.cl.event=org.onap.clamp.clds.cl.event clamp.config.security.permission.type.filter.vf=org.onap.clamp.clds.filter.vf clamp.config.security.permission.type.template=org.onap.clamp.clds.template clamp.config.security.permission.type.tosca=org.onap.clamp.clds.tosca diff --git a/src/main/resources/clds/camel/rest/clamp-api-v2.xml b/src/main/resources/clds/camel/rest/clamp-api-v2.xml index 44237527..6b6ec458 100644 --- a/src/main/resources/clds/camel/rest/clamp-api-v2.xml +++ b/src/main/resources/clds/camel/rest/clamp-api-v2.xml @@ -3,15 +3,19 @@ <get uri="/v2/loop/getAllNames" outType="java.lang.String[]" produces="application/json"> - <to - uri="bean:org.onap.clamp.loop.LoopController?method=getLoopNames()" /> + <route> + <to uri="bean:org.onap.clamp.authorization.AuthorizationController?method=authorize(*,'cl','','read')" /> + <to uri="bean:org.onap.clamp.loop.LoopController?method=getLoopNames()" /> + </route> </get> <get uri="/v2/loop/{loopName}" outType="org.onap.clamp.loop.Loop" produces="application/json"> - <to - uri="bean:org.onap.clamp.loop.LoopController?method=getLoop(${header.loopName})" /> + <route> + <to uri="bean:org.onap.clamp.authorization.AuthorizationController?method=authorize(*,'cl','','read')" /> + <to uri="bean:org.onap.clamp.loop.LoopController?method=getLoop(${header.loopName})" /> + </route> </get> <get uri="/v2/loop/svgRepresentation/{loopName}" outType="java.lang.String" @@ -20,29 +24,34 @@ <to uri="bean:org.onap.clamp.loop.LoopController?method=getSVGRepresentation(${header.loopName})" /> </get> - <post uri="/v2/loop/globalProperties/{loopName}" - type="com.google.gson.JsonArray" - consumes="application/json" - outType="org.onap.clamp.loop.Loop" - produces="application/json"> + + <post uri="/v2/loop/updateGlobalProperties/{loopName}" + type="com.google.gson.JsonObject" + consumes="application/json" + outType="org.onap.clamp.loop.Loop" + produces="application/json"> <to - uri="bean:org.onap.clamp.loop.LoopController?method=updateOperationalPolicies(${header.loopName},${body})" /> + uri="bean:org.onap.clamp.loop.LoopController?method=updateGlobalPropertiesJson(${header.loopName},${body})" /> </post> <post uri="/v2/loop/updateOperationalPolicies/{loopName}" type="com.google.gson.JsonArray" consumes="application/json" outType="org.onap.clamp.loop.Loop" produces="application/json"> - <to - uri="bean:org.onap.clamp.loop.LoopController?method=updateOperationalPolicies(${header.loopName},${body})" /> + <route> + <to uri="bean:org.onap.clamp.authorization.AuthorizationController?method=authorize(*,'cl','','update')" /> + <to uri="bean:org.onap.clamp.loop.LoopController?method=updateOperationalPolicies(${header.loopName},${body})" /> + </route> </post> <post uri="/v2/loop/updateMicroservicePolicies/{loopName}" type="com.google.gson.JsonArray" consumes="application/json" outType="org.onap.clamp.loop.Loop" produces="application/json"> - <to - uri="bean:org.onap.clamp.loop.LoopController?method=updateMicroservicePolicies(${header.loopName},${body})" /> + <route> + <to uri="bean:org.onap.clamp.authorization.AuthorizationController?method=authorize(*,'cl','','update')" /> + <to uri="bean:org.onap.clamp.loop.LoopController?method=updateMicroservicePolicies(${header.loopName},${body})" /> + </route> </post> </rest> </rests> diff --git a/src/main/resources/clds/clds-users.json b/src/main/resources/clds/clds-users.json index b4d73a29..fe305980 100644 --- a/src/main/resources/clds/clds-users.json +++ b/src/main/resources/clds/clds-users.json @@ -6,6 +6,7 @@ "org.onap.clamp.clds.cl|dev|read", "org.onap.clamp.clds.cl|dev|update", "org.onap.clamp.clds.cl.manage|dev|*", + "org.onap.clamp.clds.cl.event|dev|*", "org.onap.clamp.clds.filter.vf|dev|*", "org.onap.clamp.clds.template|dev|read", "org.onap.clamp.clds.template|dev|update", diff --git a/src/test/java/org/onap/clamp/clds/it/AuthorizationControllerItCase.java b/src/test/java/org/onap/clamp/clds/it/AuthorizationControllerItCase.java new file mode 100644 index 00000000..477c71a0 --- /dev/null +++ b/src/test/java/org/onap/clamp/clds/it/AuthorizationControllerItCase.java @@ -0,0 +1,94 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP CLAMP + * ================================================================================ + * Copyright (C) 2019 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.onap.clamp.clds.it; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; + +import java.io.IOException; +import java.util.LinkedList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.clamp.authorization.AuthorizationController; +import org.onap.clamp.clds.service.SecureServicePermission; +import org.onap.clamp.util.PrincipalUtils; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContext; +import org.springframework.security.core.userdetails.User; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * Test CldsDAO calls through CldsModel and CldsEvent. This really test the DB + * and stored procedures. + */ +@RunWith(SpringRunner.class) +@SpringBootTest +public class AuthorizationControllerItCase { + + protected static final EELFLogger logger = EELFManager.getInstance().getLogger(AuthorizationControllerItCase.class); + private Authentication authentication; + private List<GrantedAuthority> authList = new LinkedList<GrantedAuthority>(); + + /** + * Setup the variable before the tests execution. + * + * @throws IOException + * In case of issues when opening the files + */ + @Before + public void setupBefore() throws IOException { + authList.add(new SimpleGrantedAuthority("permission-type-cl-manage|dev|*")); + authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|read")); + authList.add(new SimpleGrantedAuthority("permission-type-cl|dev|update")); + authList.add(new SimpleGrantedAuthority("permission-type-template|dev|read")); + authList.add(new SimpleGrantedAuthority("permission-type-template|dev|update")); + authList.add(new SimpleGrantedAuthority("permission-type-filter-vf|dev|*")); + authList.add(new SimpleGrantedAuthority("permission-type-cl-event|dev|*")); + + authentication = new UsernamePasswordAuthenticationToken(new User("admin", "", authList), "", authList); + } + + @Test + public void testIsUserPermittedNoException() { + SecurityContext securityContext = Mockito.mock(SecurityContext.class); + Mockito.when(securityContext.getAuthentication()).thenReturn(authentication); + PrincipalUtils.setSecurityContext(securityContext); + + AuthorizationController auth = new AuthorizationController (); + assertTrue(auth.isUserPermittedNoException(new SecureServicePermission("permission-type-cl","dev","read"))); + assertTrue(auth.isUserPermittedNoException(new SecureServicePermission("permission-type-cl-manage","dev","DEPLOY"))); + assertTrue(auth.isUserPermittedNoException(new SecureServicePermission("permission-type-filter-vf","dev","12345-55555-55555-5555"))); + assertFalse(auth.isUserPermittedNoException(new SecureServicePermission("permission-type-cl","test","read"))); + } +} diff --git a/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java b/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java index 58b922e0..55657c97 100644 --- a/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/sdc/controller/SdcSingleControllerItCase.java @@ -49,13 +49,10 @@ import org.springframework.test.context.junit4.SpringRunner; @ActiveProfiles(profiles = "clamp-default,clamp-default-user,clamp-sdc-controller") public class SdcSingleControllerItCase { - private static final String SDC_FOLDER = "/tmp/csar-handler-tests"; private static final String CSAR_ARTIFACT_NAME = "testArtifact.csar"; private static final String SERVICE_UUID = "serviceUUID"; private static final String RESOURCE1_UUID = "resource1UUID"; private static final String RESOURCE1_INSTANCE_NAME = "sim-1802 0"; - private static final String RESOURCE1_INSTANCE_NAME_IN_CSAR = "sim18020"; - private static final String BLUEPRINT1_NAME = "FOI.Simfoimap223S0112.event_proc_bp.yaml"; @Autowired private ClampProperties clampProp; diff --git a/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java b/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java index ce8a493d..d3a823fb 100644 --- a/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java +++ b/src/test/java/org/onap/clamp/clds/it/sdc/controller/installer/CsarInstallerItCase.java @@ -30,6 +30,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -68,7 +69,6 @@ import org.springframework.test.context.junit4.SpringRunner; @ActiveProfiles(profiles = "clamp-default,clamp-default-user,clamp-sdc-controller") public class CsarInstallerItCase { - private static final String CSAR_ARTIFACT_NAME = "testArtifact.csar"; private static final String INVARIANT_SERVICE_UUID = "4cc5b45a-1f63-4194-8100-cd8e14248c92"; private static final String INVARIANT_RESOURCE1_UUID = "07e266fc-49ab-4cd7-8378-ca4676f1b9ec"; private static final String INVARIANT_RESOURCE2_UUID = "023a3f0d-1161-45ff-b4cf-8918a8ccf3ad"; @@ -89,7 +89,8 @@ public class CsarInstallerItCase { blueprintMap.put("resourceid", blueprintArtifact); Mockito.when(csarHandler.getMapOfBlueprints()).thenReturn(blueprintMap); Mockito.when(blueprintArtifact.getDcaeBlueprint()).thenReturn( - IOUtils.toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/not-recognized.yaml"))); + IOUtils.toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/not-recognized.yaml"), + StandardCharsets.UTF_8)); csarInstaller.installTheCsar(csarHandler); fail("Should have raised an SdcArtifactInstallerException"); } @@ -164,16 +165,17 @@ public class CsarInstallerItCase { csarInstaller.installTheCsar(csar); CldsModel cldsModel1 = verifyClosedLoopModelLoadedInDb(csar, "tca.yaml"); JSONAssert.assertEquals( - IOUtils.toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca.json")), + IOUtils.toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca.json"), + StandardCharsets.UTF_8), cldsModel1.getPropText(), true); CldsModel cldsModel2 = verifyClosedLoopModelLoadedInDb(csar, "tca_2.yaml"); - JSONAssert.assertEquals( - IOUtils - .toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca-2.json")), - cldsModel2.getPropText(), true); + JSONAssert.assertEquals(IOUtils.toString( + ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca-2.json"), + StandardCharsets.UTF_8), cldsModel2.getPropText(), true); CldsModel cldsModel3 = verifyClosedLoopModelLoadedInDb(csar, "tca_3.yaml"); JSONAssert.assertEquals( - IOUtils.toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca.json")), + IOUtils.toString(ResourceFileUtil.getResourceAsStream("example/sdc/blueprint-dcae/prop-text-for-tca.json"), + StandardCharsets.UTF_8), cldsModel3.getPropText(), true); } diff --git a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java index 544c8ca1..e0088747 100644 --- a/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java +++ b/src/test/java/org/onap/clamp/clds/sdc/controller/installer/CsarHandlerTest.java @@ -161,7 +161,7 @@ public class CsarHandlerTest { CsarHandler csar = new CsarHandler(buildFakeSdcNotification(), "test-controller", "/tmp/csar-handler-tests"); csar.save(buildFakeSdcResut()); String policyModelYaml = csar.getPolicyModelYaml().get(); - assertTrue(policyModelYaml.contains("tosca_simple_yaml_1_1")); + assertTrue(policyModelYaml.contains("tosca_simple_yaml_1_0_0")); } @Test diff --git a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java index 6bfee4c4..d1a4bdc5 100644 --- a/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java +++ b/src/test/java/org/onap/clamp/loop/CsarInstallerItCase.java @@ -23,8 +23,7 @@ package org.onap.clamp.loop; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.util.ArrayList; @@ -33,6 +32,8 @@ import java.util.List; import java.util.Map; import java.util.Optional; +import javax.transaction.Transactional; + import org.apache.commons.lang3.RandomStringUtils; import org.json.JSONException; import org.junit.Test; @@ -62,7 +63,7 @@ import org.springframework.test.context.junit4.SpringRunner; @ActiveProfiles(profiles = "clamp-default,clamp-default-user,clamp-sdc-controller-new") public class CsarInstallerItCase { - private static final String CSAR_ARTIFACT_NAME = "testArtifact.csar"; + private static final String CSAR_ARTIFACT_NAME = "example/sdc/service-Simsfoimap0112.csar"; private static final String INVARIANT_SERVICE_UUID = "4cc5b45a-1f63-4194-8100-cd8e14248c92"; private static final String INVARIANT_RESOURCE1_UUID = "07e266fc-49ab-4cd7-8378-ca4676f1b9ec"; private static final String INVARIANT_RESOURCE2_UUID = "023a3f0d-1161-45ff-b4cf-8918a8ccf3ad"; @@ -70,6 +71,9 @@ public class CsarInstallerItCase { private static final String RESOURCE_INSTANCE_NAME_RESOURCE2 = "ResourceInstanceName2"; @Autowired + private LoopsRepository loopsRepo; + + @Autowired private CsarInstaller csarInstaller; private BlueprintArtifact buildFakeBuildprintArtifact(String instanceName, String invariantResourceUuid, @@ -113,10 +117,6 @@ public class CsarInstallerItCase { "example/sdc/blueprint-dcae/tca_3.yaml", "tca_3.yaml", INVARIANT_SERVICE_UUID); blueprintMap.put(blueprintArtifact.getBlueprintArtifactName(), blueprintArtifact); - SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); - ISdcCsarHelper sdcHelper = factory.getSdcCsarHelper(Thread.currentThread().getContextClassLoader() - .getResource("example/sdc/service-Simsfoimap0112.csar").getFile()); - // Build fake csarhandler Mockito.when(csarHandler.getSdcNotification()).thenReturn(notificationData); // Build fake csar Helper @@ -125,28 +125,54 @@ public class CsarInstallerItCase { Mockito.when(data.getValue("name")).thenReturn(generatedName); Mockito.when(notificationData.getServiceName()).thenReturn(generatedName); Mockito.when(csarHelper.getServiceMetadata()).thenReturn(data); + + // Create helper based on real csar to test policy yaml and global properties + // set + SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance(); + ISdcCsarHelper sdcHelper = factory + .getSdcCsarHelper(Thread.currentThread().getContextClassLoader().getResource(CSAR_ARTIFACT_NAME).getFile()); Mockito.when(csarHandler.getSdcCsarHelper()).thenReturn(sdcHelper); + // Mockito.when(csarHandler.getSdcCsarHelper()).thenReturn(csarHelper); - Mockito.when(csarHandler.getPolicyModelYaml()).thenReturn(Optional.ofNullable("")); + Mockito.when(csarHandler.getPolicyModelYaml()) + .thenReturn(Optional.ofNullable(ResourceFileUtil.getResourceAsString("tosca/tca-policy-test.yaml"))); return csarHandler; } + @Test + @Transactional public void testIsCsarAlreadyDeployedTca() throws SdcArtifactInstallerException, SdcToscaParserException, CsarHandlerException, IOException, InterruptedException, PolicyModelException { String generatedName = RandomStringUtils.randomAlphanumeric(5); CsarHandler csarHandler = buildFakeCsarHandler(generatedName); - assertFalse(csarInstaller.isCsarAlreadyDeployed(csarHandler)); + assertThat(csarInstaller.isCsarAlreadyDeployed(csarHandler)).isFalse(); csarInstaller.installTheCsar(csarHandler); - assertTrue(csarInstaller.isCsarAlreadyDeployed(csarHandler)); + assertThat(csarInstaller.isCsarAlreadyDeployed(csarHandler)).isTrue(); } @Test + @Transactional public void testInstallTheCsarTca() throws SdcArtifactInstallerException, SdcToscaParserException, CsarHandlerException, IOException, JSONException, InterruptedException, PolicyModelException { String generatedName = RandomStringUtils.randomAlphanumeric(5); CsarHandler csar = buildFakeCsarHandler(generatedName); csarInstaller.installTheCsar(csar); - + assertThat(loopsRepo + .existsById(Loop.generateLoopName(generatedName, "1.0", RESOURCE_INSTANCE_NAME_RESOURCE1, "tca.yaml"))) + .isTrue(); + assertThat(loopsRepo + .existsById(Loop.generateLoopName(generatedName, "1.0", RESOURCE_INSTANCE_NAME_RESOURCE1, "tca_3.yaml"))) + .isTrue(); + assertThat(loopsRepo + .existsById(Loop.generateLoopName(generatedName, "1.0", RESOURCE_INSTANCE_NAME_RESOURCE2, "tca_2.yaml"))) + .isTrue(); + // Verify now that policy and json representation, global properties are well + // set + Loop loop = loopsRepo + .findById(Loop.generateLoopName(generatedName, "1.0", RESOURCE_INSTANCE_NAME_RESOURCE1, "tca.yaml")).get(); + + assertThat(loop.getModelPropertiesJson().get("serviceDetails")).isNotNull(); + assertThat(loop.getModelPropertiesJson().get("resourceDetails")).isNotNull(); } } diff --git a/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java b/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java index b7781bf2..d247344a 100644 --- a/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java +++ b/src/test/java/org/onap/clamp/loop/LoopServiceTestItCase.java @@ -92,7 +92,7 @@ public class LoopServiceTestItCase { //when Loop actualLoop = loopService - .updateOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(operationalPolicy)); + .updateAndSaveOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(operationalPolicy)); //then assertThat(actualLoop).isNotNull(); @@ -118,7 +118,7 @@ public class LoopServiceTestItCase { //when Loop actualLoop = loopService - .updateMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(microServicePolicy)); + .updateAndSaveMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(microServicePolicy)); //then assertThat(actualLoop).isNotNull(); @@ -143,14 +143,14 @@ public class LoopServiceTestItCase { String secondPolicyTosca = "secondPolicyTosca"; MicroServicePolicy firstMicroServicePolicy = new MicroServicePolicy(firstPolicyName, "policyTosca", false, JsonUtils.GSON.fromJson(EXAMPLE_JSON, JsonObject.class), null); - loopService.updateMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstMicroServicePolicy)); + loopService.updateAndSaveMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstMicroServicePolicy)); MicroServicePolicy secondMicroServicePolicy = new MicroServicePolicy(secondPolicyName, secondPolicyTosca, true, newJsonRepresentation, null); //when firstMicroServicePolicy.setJsonRepresentation(newJsonRepresentation); - Loop actualLoop = loopService.updateMicroservicePolicies(EXAMPLE_LOOP_NAME, + Loop actualLoop = loopService.updateAndSaveMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstMicroServicePolicy, secondMicroServicePolicy)); //then @@ -180,14 +180,14 @@ public class LoopServiceTestItCase { String secondPolicyTosca = "secondPolicyTosca"; MicroServicePolicy firstMicroServicePolicy = new MicroServicePolicy(firstPolicyName, "policyTosca", false, JsonUtils.GSON.fromJson(EXAMPLE_JSON, JsonObject.class), null); - loopService.updateMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstMicroServicePolicy)); + loopService.updateAndSaveMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstMicroServicePolicy)); MicroServicePolicy secondMicroServicePolicy = new MicroServicePolicy(secondPolicyName, secondPolicyTosca, true, jsonRepresentation, null); //when Loop actualLoop = loopService - .updateMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(secondMicroServicePolicy)); + .updateAndSaveMicroservicePolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(secondMicroServicePolicy)); //then assertThat(actualLoop).isNotNull(); @@ -210,13 +210,13 @@ public class LoopServiceTestItCase { String secondPolicyName = "secondPolicyName"; OperationalPolicy firstOperationalPolicy = new OperationalPolicy(firstPolicyName, null, JsonUtils.GSON.fromJson(EXAMPLE_JSON, JsonObject.class)); - loopService.updateOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstOperationalPolicy)); + loopService.updateAndSaveOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstOperationalPolicy)); OperationalPolicy secondOperationalPolicy = new OperationalPolicy(secondPolicyName, null, newJsonConfiguration); //when firstOperationalPolicy.setConfigurationsJson(newJsonConfiguration); - Loop actualLoop = loopService.updateOperationalPolicies(EXAMPLE_LOOP_NAME, + Loop actualLoop = loopService.updateAndSaveOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstOperationalPolicy, secondOperationalPolicy)); //then @@ -244,13 +244,13 @@ public class LoopServiceTestItCase { String secondPolicyName = "policyName"; OperationalPolicy firstOperationalPolicy = new OperationalPolicy(firstPolicyName, null, JsonUtils.GSON.fromJson(EXAMPLE_JSON, JsonObject.class)); - loopService.updateOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstOperationalPolicy)); + loopService.updateAndSaveOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(firstOperationalPolicy)); OperationalPolicy secondOperationalPolicy = new OperationalPolicy(secondPolicyName, null, jsonRepresentation); //when Loop actualLoop = loopService - .updateOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(secondOperationalPolicy)); + .updateAndSaveOperationalPolicies(EXAMPLE_LOOP_NAME, Lists.newArrayList(secondOperationalPolicy)); //then assertThat(actualLoop).isNotNull(); @@ -264,6 +264,26 @@ public class LoopServiceTestItCase { } + @Test + public void shouldCreateModelPropertiesAndUpdateJsonRepresentationOfOldOne() { + //given + saveTestLoopToDb(); + String expectedJson = "{\"test\":\"test\"}"; + JsonObject baseGlobalProperites = JsonUtils.GSON.fromJson("{}", JsonObject.class); + JsonObject updatedGlobalProperites = JsonUtils.GSON.fromJson(expectedJson, JsonObject.class); + loopService.updateAndSaveGlobalPropertiesJson(EXAMPLE_LOOP_NAME, baseGlobalProperites); + + //when + Loop actualLoop = loopService + .updateAndSaveGlobalPropertiesJson(EXAMPLE_LOOP_NAME, updatedGlobalProperites); + + //then + assertThat(actualLoop).isNotNull(); + assertThat(actualLoop.getName()).isEqualTo(EXAMPLE_LOOP_NAME); + JsonObject returnedGlobalProperties = actualLoop.getGlobalPropertiesJson(); + assertThat(returnedGlobalProperties.getAsJsonObject()).isEqualTo(updatedGlobalProperites); + } + private Loop createTestLoop(String loopName, String loopBlueprint, String loopSvg) { return new Loop(loopName, loopBlueprint, loopSvg); } diff --git a/src/test/resources/example/sdc/service-Simsfoimap0112.csar b/src/test/resources/example/sdc/service-Simsfoimap0112.csar Binary files differindex ea0e44a2..8c16d31e 100644 --- a/src/test/resources/example/sdc/service-Simsfoimap0112.csar +++ b/src/test/resources/example/sdc/service-Simsfoimap0112.csar |