From b3828de54af94f66e3a6e22bcaeb3372d14eab34 Mon Sep 17 00:00:00 2001 From: Michael Mokry Date: Tue, 14 Nov 2017 15:01:13 -0600 Subject: Refactor to provide Common Policy Validation Provides a common class to perform policy validation during create/udpate of policies by the GUI and API for consistency. Change-Id: Ied459e73d48517bb50064cd10d6a1c871b8311e5 Issue-ID: POLICY-449 Signed-off-by: Michael Mokry --- .../services/CreateUpdatePolicyServiceImpl.java | 125 +++++++++++++-------- .../api/services/MicroServicesPolicyService.java | 1 + .../policy/pdp/rest/api/utils/PolicyApiUtils.java | 12 +- .../onap/policy/pdp/rest/config/PDPRestConfig.java | 103 ++++++++++++++++- .../rest/api/test/PolicyEngineServicesTest.java | 42 +++---- 5 files changed, 215 insertions(+), 68 deletions(-) (limited to 'ONAP-PDP-REST/src') diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java index 528e5cda9..483e13c23 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/CreateUpdatePolicyServiceImpl.java @@ -23,14 +23,20 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; +import org.glassfish.jersey.spi.Contract; import org.onap.policy.api.PolicyException; import org.onap.policy.api.PolicyParameters; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; -import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.util.PolicyValidation; +import org.onap.policy.rest.util.PolicyValidationRequestWrapper; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Controller; + +import com.google.common.base.Strings; public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService { private static final Logger LOGGER = FlexLogger.getLogger(CreateUpdatePolicyServiceImpl.class.getName()); @@ -213,54 +219,83 @@ public class CreateUpdatePolicyServiceImpl implements CreateUpdatePolicyService } protected boolean getValidation() { - if(policyParameters == null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. "; - return false; - } - if(policyParameters.getPolicyName() == null){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } - if (policyParameters.getPolicyName().contains(".")) { - policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf('.') + 1, - policyParameters.getPolicyName().length()); - policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf('.')); - LOGGER.info("Name is " + policyName + " scope is " + policyScope); - } else { - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given."; - return false; - } - if (policyName==null||policyName.trim().isEmpty()){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given."; - return false; - } - message = PolicyUtils.policySpecialCharValidator(policyScope); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - message = PolicyUtils.policySpecialCharValidator(policyName); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - if(policyParameters.getPolicyDescription()!=null){ - message = PolicyUtils.descriptionValidator(policyParameters.getPolicyDescription()); - if(!message.contains("success")){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ message; - return false; - } - } - if(!PolicyApiUtils.validateNONASCIICharactersAndAllowSpaces(policyParameters.toString())){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "This requests contains Non ASCII Characters. Please review your input parameter" - + " values and correct the illegal characters."; - return false; - } + + PolicyValidation validation = new PolicyValidation(); + + StringBuilder responseString; + + if (policyParameters != null) { + + if (!Strings.isNullOrEmpty(policyParameters.getPolicyName())){ + if (policyParameters.getPolicyName().contains(".")) { + policyName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf('.') + 1, + policyParameters.getPolicyName().length()); + policyScope = policyParameters.getPolicyName().substring(0,policyParameters.getPolicyName().lastIndexOf('.')); + policyParameters.setPolicyName(policyName); + LOGGER.info("Name is " + policyName + " scope is " + policyScope); + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Scope: No Policy Scope given"; + LOGGER.error("Common validation did not return success: " + message); + return false; + } + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "PolicyName: PolicyName Should not be empty"; + LOGGER.error("Common validation did not return success: " + message); + return false; + } + + if(policyParameters.getPolicyClass() != null){ + if ("Config".equals(policyParameters.getPolicyClass().toString())){ + String policyConfigType = policyParameters.getPolicyConfigType().toString(); + if(!"BRMS_Param".equalsIgnoreCase(policyConfigType)){ + if(Strings.isNullOrEmpty(policyParameters.getConfigBody())){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "ConfigBody: No Config Body given"; + LOGGER.error("Common validation did not return success: " + message); + return false; + } + } + } + } + + try { + PolicyValidationRequestWrapper wrapper = new PolicyValidationRequestWrapper(); + PolicyRestAdapter policyData = wrapper.populateRequestParameters(policyParameters); + responseString = validation.validatePolicy(policyData); + } catch (Exception e) { + LOGGER.error("Exception Occured during Policy Validation" +e); + if(e.getMessage()!=null){ + if("Action".equals(policyParameters.getPolicyClass().toString()) && e.getMessage().contains("Index:")){ + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Rule Algorithms: One or more Fields in Rule Algorithms is Empty."; + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured During Policy Validation: " + e; + } + } + return false; + } + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy parameters given. "; + return false; + } + // Set some default Values. if (policyParameters.getTtlDate()!=null){ date = convertDate(policyParameters.getTtlDate()); } - return true; + + if (responseString!=null){ + if("success".equals(responseString.toString())||"success@#".equals(responseString.toString())){ + return true; + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + PolicyApiUtils.formatResponse(responseString); + LOGGER.error("Common validation did not return success: " + message); + return false; + } + } else { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unknown Error Occured During Policy Validation"; + LOGGER.error(message); + return false; + } + } protected String convertDate(Date date) { diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java index 22d8873d7..44740391e 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/MicroServicesPolicyService.java @@ -101,6 +101,7 @@ public class MicroServicesPolicyService{ String policyDescription=null; String priority=null; String version=null; + if (microServiceAttributes.get("service")!=null){ microService = microServiceAttributes.get("service").toString().replace("\"", ""); } diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java index cd107d0ba..5477a8b60 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/utils/PolicyApiUtils.java @@ -53,7 +53,17 @@ public class PolicyApiUtils { } return isValidForm; } - + + public static String formatResponse(StringBuilder responseString){ + + LOGGER.info("Formatting response message from Policy Validator"); + String response = null; + response = responseString.toString().replace("
", " | "); + response = response.replaceAll("(|<\\/b>|
||<\\/i>|@#)", ""); + + return response; + } + public static boolean isNumeric(String str) { for (char c : str.toCharArray()) { if (!Character.isDigit(c)) diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java index 078cab2aa..b563c6cce 100644 --- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java +++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java @@ -19,13 +19,27 @@ */ package org.onap.policy.pdp.rest.config; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import javax.annotation.PostConstruct; import javax.servlet.MultipartConfigElement; +import javax.sql.DataSource; +import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; +import org.hibernate.SessionFactory; import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pdp.rest.api.controller.PolicyEngineServices; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; +import org.springframework.orm.hibernate4.HibernateTransactionManager; +import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @@ -41,8 +55,31 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableWebMvc @EnableSwagger2 -@ComponentScan(basePackageClasses = PolicyEngineServices.class) +@ComponentScan(basePackages = { "org.onap.*", "com.*" }) public class PDPRestConfig extends WebMvcConfigurerAdapter{ + + private static final Logger LOGGER = FlexLogger.getLogger(PDPRestConfig.class); + + private static String dbDriver = null; + private static String dbUrl = null; + private static String dbUserName = null; + private static String dbPassword = null; + + @PostConstruct + public void init(){ + Properties prop = new Properties(); + try (InputStream input = new FileInputStream("xacml.pdp.properties")){ + // load a properties file + prop.load(input); + setDbDriver(prop.getProperty("javax.persistence.jdbc.driver")); + setDbUrl(prop.getProperty("javax.persistence.jdbc.url")); + setDbUserName(prop.getProperty("javax.persistence.jdbc.user")); + setDbPassword(prop.getProperty("javax.persistence.jdbc.password")); + }catch(Exception e){ + LOGGER.error("Exception Occured while loading properties file"+e); + } + } + @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); @@ -68,10 +105,74 @@ public class PDPRestConfig extends WebMvcConfigurerAdapter{ .apiInfo(apiInfo()); } + @Bean(name = "dataSource") + public DataSource getDataSource() { + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setDriverClassName(PDPRestConfig.getDbDriver()); + dataSource.setUrl(PDPRestConfig.getDbUrl()); + dataSource.setUsername(PDPRestConfig.getDbUserName()); + dataSource.setPassword(PDPRestConfig.getDbPassword()); + return dataSource; + } + + @Autowired + @Bean(name = "sessionFactory") + public SessionFactory getSessionFactory(DataSource dataSource) { + LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource); + sessionBuilder.scanPackages("org.onap.*", "com.*"); + sessionBuilder.addProperties(getHibernateProperties()); + return sessionBuilder.buildSessionFactory(); + } + + private Properties getHibernateProperties() { + Properties properties = new Properties(); + properties.put("hibernate.show_sql", "true"); + properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect"); + return properties; + } + + @Autowired + @Bean(name = "transactionManager") + public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) { + return new HibernateTransactionManager(sessionFactory); + } + @Bean public MultipartConfigElement multipartConfigElement(){ String location = System.getProperty("java.io.tmpdir"); MultipartConfigElement mp = new MultipartConfigElement(location); return mp; } + + public static String getDbDriver() { + return dbDriver; + } + + public static void setDbDriver(String dbDriver) { + PDPRestConfig.dbDriver = dbDriver; + } + + public static String getDbUrl() { + return dbUrl; + } + + public static void setDbUrl(String dbUrl) { + PDPRestConfig.dbUrl = dbUrl; + } + + public static String getDbUserName() { + return dbUserName; + } + + public static void setDbUserName(String dbUserName) { + PDPRestConfig.dbUserName = dbUserName; + } + + public static String getDbPassword() { + return dbPassword; + } + + public static void setDbPassword(String dbPassword) { + PDPRestConfig.dbPassword = dbPassword; + } } diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java index ac8b269eb..8fea627c9 100644 --- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/test/PolicyEngineServicesTest.java @@ -453,9 +453,9 @@ public class PolicyEngineServicesTest { pep.setAttributes(attributes); pep.setRiskLevel("5"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); // Checks for BRMS Raw Policy pep.setPolicyConfigType(PolicyConfigType.BRMS_RAW); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) @@ -469,9 +469,9 @@ public class PolicyEngineServicesTest { .headers(headers)).andExpect(status().isBadRequest()); pep.setRiskLevel("5"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); } @Test @@ -505,11 +505,11 @@ public class PolicyEngineServicesTest { .headers(headers)).andExpect(status().isBadRequest()); pep.setConfigName("configName"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); pep.setConfigBody("{'test':'test}"); pep.setConfigBodyType(PolicyType.JSON); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); Map> attributes = new HashMap<>(); Map matching = new HashMap<>(); matching.put("key", "value"); @@ -517,7 +517,7 @@ public class PolicyEngineServicesTest { pep.setAttributes(attributes); pep.setConfigBody("testBody"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); } @Test @@ -546,15 +546,15 @@ public class PolicyEngineServicesTest { .headers(headers)).andExpect(status().isBadRequest()); pep.setConfigBody("{\"onapname\":\"test\"}"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); pep.setRiskLevel("test"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) .headers(headers)).andExpect(status().isBadRequest()); pep.setRiskLevel("4"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); } @Test @@ -588,15 +588,15 @@ public class PolicyEngineServicesTest { .headers(headers)).andExpect(status().isBadRequest()); pep.setConfigBody("{\"onapname\":\"test\", \"serviceTypePolicyName\":\"value\"}"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); pep.setRiskLevel("test"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) .headers(headers)).andExpect(status().isBadRequest()); pep.setRiskLevel("4"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); } @Test @@ -626,9 +626,9 @@ public class PolicyEngineServicesTest { .headers(headers)).andExpect(status().isBadRequest()); pep.setConfigBody("{\"configName\":\"test\"}"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); } @Test @@ -659,10 +659,10 @@ public class PolicyEngineServicesTest { .headers(headers)).andExpect(status().isBadRequest()); pep.setRiskLevel("4"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); pep.setConfigBody("{\"service\":\"test\",\"uuid\":\"test\",\"location\":\"test\",\"configName\":\"test\",\"description\":\"test\",\"priority\":\"test\",\"version\":\"test\"}"); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); } @Test @@ -708,18 +708,18 @@ public class PolicyEngineServicesTest { .headers(headers)).andExpect(status().isBadRequest()); pep.setOnapName("xyz"); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); attributes.remove(AttributeType.MATCHING); attributes.put(AttributeType.SETTINGS, matching); pep.setAttributes(attributes); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); attributes.put(AttributeType.MATCHING, matching); pep.setAttributes(attributes); mockMvc.perform(put("/createPolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); mockMvc.perform(put("/updatePolicy").content(PolicyUtils.objectToJsonString(pep)).contentType(MediaType.APPLICATION_JSON) - .headers(headers)).andExpect(status().isInternalServerError()); + .headers(headers)).andExpect(status().isBadRequest()); } @Test -- cgit 1.2.3-korg