From 91d04c64771832a0b8815ffbe1f0f9920320d94d Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Tue, 14 Feb 2017 19:41:00 -0500 Subject: Initial OpenECOMP policy/engine commit Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e Signed-off-by: Pamela Dragosh --- .../policy/pypdp/ConfigFirewallPolicyRequest.java | 128 +++++ .../org/openecomp/policy/pypdp/ConfigRequest.java | 182 +++++++ .../policy/pypdp/DeletePolicyRequest.java | 80 +++ .../org/openecomp/policy/pypdp/EventRequest.java | 83 +++ .../openecomp/policy/pypdp/ListConfigRequest.java | 69 +++ .../policy/pypdp/PolicyCreateUpdateRequest.java | 124 +++++ .../openecomp/policy/pypdp/PushPolicyRequest.java | 90 ++++ .../pypdp/authorization/AuthenticationFilter.java | 80 +++ .../pypdp/authorization/AuthenticationService.java | 232 +++++++++ .../policy/pypdp/authorization/Config.java | 300 +++++++++++ .../policy/pypdp/controller/Application.java | 80 +++ .../pypdp/controller/PolicyEngineServices.java | 556 +++++++++++++++++++++ .../policy/pypdp/jmx/PyPdpMBeanListener.java | 75 +++ .../openecomp/policy/pypdp/jmx/PyPdpMonitor.java | 90 ++++ .../policy/pypdp/jmx/PyPdpMonitorMBean.java | 28 ++ .../model_pojo/PepConfigFirewallPolicyRequest.java | 82 +++ .../model_pojo/PepConfigPolicyNameRequest.java | 39 ++ .../pypdp/model_pojo/PepConfigPolicyRequest.java | 187 +++++++ .../pypdp/model_pojo/PepPushPolicyRequest.java | 66 +++ .../policy/pypdp/model_pojo/PyPolicyConfig.java | 95 ++++ .../policy/pypdp/notifications/Notification.java | 50 ++ .../notifications/NotificationController.java | 149 ++++++ .../pypdp/notifications/NotificationServer.java | 90 ++++ 23 files changed, 2955 insertions(+) create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java create mode 100644 PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java (limited to 'PyPDPServer/src/main/java/org/openecomp') diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java new file mode 100644 index 000000000..4a11b8c9e --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigFirewallPolicyRequest.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp; + +import java.io.StringReader; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonObject; +import javax.json.JsonReader; + +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.pypdp.model_pojo.PepConfigFirewallPolicyRequest; +import org.openecomp.policy.std.StdPolicyEngine; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +public class ConfigFirewallPolicyRequest { + + private StdPolicyEngine pe; + public ConfigFirewallPolicyRequest(StdPolicyEngine pe){ + this.pe= pe; + } + + public String run(PepConfigFirewallPolicyRequest pep, String requestID, String operation, String userID, String passcode) { + + String result = null; + + // construct a UUID from the request string + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } + catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + PolicyLogger.info("Generated Random UUID: " + requestUUID.toString()); + } + } + + if (pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) { + if (pep.getFirewallJson() != null && !pep.getFirewallJson().isEmpty()) { + if (pep.getPolicyScope() != null && !pep.getPolicyScope().isEmpty()) { + try { + + JsonObject json = stringToJson(pep.getFirewallJson()); + + if(!json.toString().contains("errorMessage")){ + if (operation.equalsIgnoreCase("create")) { + result = pe.createConfigFirewallPolicy(pep.getPolicyName(), json, pep.getPolicyScope(), requestUUID, userID, passcode, + pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate()); + } else { + result = pe.updateConfigFirewallPolicy(pep.getPolicyName(), json, pep.getPolicyScope(), requestUUID, userID, passcode, + pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate()); + } + } else { + result = XACMLErrorConstants.ERROR_SCHEMA_INVALID + "BAD REQUEST: Invalid Json for firewallJson: " + pep.getFirewallJson(); + } + } catch (PolicyConfigException e) { + result = e.getMessage(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyScope was null or empty."; + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: firewallJson was null or empty."; + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty."; + } + + return result; + + } + + private JsonObject stringToJson(String jsonString) { + + JsonObject json = null; + if (jsonString != null) { + + try { + + //Read jsonBody to JsonObject + StringReader in = null; + + in = new StringReader(jsonString); + + JsonReader jsonReader = Json.createReader(in); + json = jsonReader.readObject(); + + } catch (Exception e) { + String jsonError = "{\"errorMessage\": \"" + e.getMessage() + "\"}"; + StringReader error = null; + error = new StringReader(jsonError); + JsonReader jsonReader = Json.createReader(error); + JsonObject badJson = jsonReader.readObject(); + return badJson; + } + + } + + return json; + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java new file mode 100644 index 000000000..694d010f3 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ConfigRequest.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp; + +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.UUID; + +import javax.json.JsonObject; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.PolicyConfig; +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.api.PolicyType; +import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyNameRequest; +import org.openecomp.policy.pypdp.model_pojo.PyPolicyConfig; +import org.openecomp.policy.std.StdPolicyConfig; +import org.openecomp.policy.std.StdPolicyEngine; +import org.w3c.dom.Document; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +public class ConfigRequest { + + private StdPolicyEngine pe; + public ConfigRequest(StdPolicyEngine pe){ + this.pe= pe; + } + + public Collection run(ConfigRequestParameters pep, String requestID, String userID, String passcode) { + PolicyLogger.debug("... Request Params : \n" + + "configName " + pep.getConfigName() + "\n" + + "ecompName" + pep.getEcompName() + "\n" + + "policyName" + pep.getPolicyName() + "\n"); + StdPolicyConfig policyConfig = new StdPolicyConfig(); + Collection result = new ArrayList(); + // construct a UUID from the request string + if(pep.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } + catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + PolicyLogger.info("Generated Random UUID: " + requestUUID.toString()); + } + } + pep.setRequestID(requestUUID); + } + try { + PolicyLogger.debug("\n\n calling PEP.. "); + Collection pConfigs = pe.configRequest(pep, userID, passcode); + for(PolicyConfig pConfig: pConfigs){ + PyPolicyConfig pyPolicyConfig = checkResponse(pConfig); + result.add(pyPolicyConfig); + } + return result; + } catch(Exception e){ + policyConfig.setConfigStatus(e.getMessage(), PolicyConfigStatus.CONFIG_NOT_FOUND); + PyPolicyConfig pyPolicyConfig = checkResponse(policyConfig); + result.add(pyPolicyConfig); + return result; + } + } + + public Collection run(PepConfigPolicyNameRequest pep, String requestID, String userID, String passcode) { + PolicyLogger.debug("... Request Params : \n" + + "policyName" + pep.getPolicyName() + "\n"); + StdPolicyConfig policyConfig = new StdPolicyConfig(); + Collection result = new ArrayList(); + // construct a UUID from the request string + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } + catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + PolicyLogger.info("Generated Random UUID: " + requestUUID.toString()); + } + } + if(pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) { + try { + Collection pConfigs = pe.configPolicyName(pep.getPolicyName(), requestUUID, userID, passcode); + for(PolicyConfig pConfig: pConfigs){ + PyPolicyConfig pyPolicyConfig = checkResponse(pConfig); + result.add(pyPolicyConfig); + } + return result; + } catch (PolicyConfigException e) { + policyConfig.setConfigStatus(e.getMessage(), PolicyConfigStatus.CONFIG_NOT_FOUND); + PyPolicyConfig pyPolicyConfig = checkResponse(policyConfig); + result.add(pyPolicyConfig); + return result; + } + } + else { + policyConfig.setConfigStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "PolicyFile Name is empty", PolicyConfigStatus.CONFIG_NOT_FOUND); + PyPolicyConfig pyPolicyConfig = checkResponse(policyConfig); + result.add(pyPolicyConfig); + return result; + } + } + + public PyPolicyConfig checkResponse(PolicyConfig pConfig) { + PyPolicyConfig policyConfig = new PyPolicyConfig(); + policyConfig.setPolicyConfigMessage(pConfig.getPolicyConfigMessage()); + policyConfig.setPolicyConfigStatus(pConfig.getPolicyConfigStatus()); + policyConfig.setType(pConfig.getType()); + policyConfig.setPolicyName(pConfig.getPolicyName()); + policyConfig.setMatchingConditions(pConfig.getMatchingConditions()); + policyConfig.setResponseAttributes(pConfig.getResponseAttributes()); + policyConfig.setPolicyVersion(pConfig.getPolicyVersion()); + if (pConfig.getPolicyConfigStatus().equals(PolicyConfigStatus.CONFIG_RETRIEVED)) { + PolicyType policyType = policyConfig.getType(); + if(policyType.equals(PolicyType.PROPERTIES)) { + Properties properties = pConfig.toProperties(); + Map propVal = new HashMap(); + for(String name: properties.stringPropertyNames()) { + propVal.put(name, properties.getProperty(name)); + } + policyConfig.setProperty(propVal); + } else if(policyType.equals(PolicyType.OTHER)) { + String other = pConfig.toOther(); + policyConfig.setConfig(other); + } else if (policyType.equals(PolicyType.JSON)) { + JsonObject json = pConfig.toJSON(); + policyConfig.setConfig(json.toString()); + } else if (policyType.equals(PolicyType.XML)) { + Document document = pConfig.toXML(); + DOMSource domSource = new DOMSource(document); + StringWriter writer = new StringWriter(); + StreamResult result = new StreamResult(writer); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer; + try { + transformer = tf.newTransformer(); + transformer.transform(domSource, result); + policyConfig.setConfig(writer.toString()); + } catch (TransformerException e) { + policyConfig.setConfig(null); + policyConfig.setPolicyConfigMessage(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "XML error in the Configuration. " + e.getMessage()); + policyConfig.setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND); + } + } + } else { + policyConfig.setConfig(null); + } + return policyConfig; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java new file mode 100644 index 000000000..0ca5bb0d2 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/DeletePolicyRequest.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp; + +import java.util.UUID; + +import org.openecomp.policy.api.DeletePolicyParameters; +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.std.StdPolicyEngine; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +public class DeletePolicyRequest { + private StdPolicyEngine pe; + public DeletePolicyRequest(StdPolicyEngine pe){ + this.pe= pe; + } + + public String run(DeletePolicyParameters pep, String requestID, String userID, String passcode) { + + String result = null; + + // construct a UUID from the request string + if(pep.getRequestID()==null){ + if (requestID != null && !requestID.isEmpty()) { + try { + pep.setRequestID(UUID.fromString(requestID)); + } + catch (IllegalArgumentException e) { + pep.setRequestID(UUID.randomUUID()); + PolicyLogger.info("Generated Random UUID: " + pep.getRequestID().toString()); + } + } + } + + if (pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) { + if (pep.getPolicyComponent() != null && !pep.getPolicyComponent().isEmpty()) { + + try { + + result = pe.deletePolicy(pep, userID, passcode).getResponseMessage(); + + } catch (PolicyConfigException e) { + result = e.getMessage(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyComponent was null or empty."; + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty."; + } + + return result; + + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java new file mode 100644 index 000000000..021b3d7f0 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/EventRequest.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; + +import org.openecomp.policy.api.EventRequestParameters; +import org.openecomp.policy.api.PolicyResponse; +import org.openecomp.policy.api.PolicyResponseStatus; +import org.openecomp.policy.std.StdPolicyEngine; +import org.openecomp.policy.std.StdPolicyResponse; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +public class EventRequest { + + private StdPolicyEngine pe; + public EventRequest(StdPolicyEngine pe){ + this.pe= pe; + } + + public Collection run(EventRequestParameters pep, String requestID, String userID, String passcode){ + StdPolicyResponse policyResponse = new StdPolicyResponse(); + Collection result = new ArrayList(); + // construct a UUID from the request string + if(pep.getRequestID()==null){ + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } + catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + PolicyLogger.info("Generated Random UUID: " + requestUUID.toString()); + } + } + pep.setRequestID(requestUUID); + } + try { + Collection pResponses = pe.event(pep.getEventAttributes(), pep.getRequestID(), userID, passcode); + for(PolicyResponse pResponse: pResponses){ + pResponse = checkResponse(pResponse); + result.add(pResponse); + } + return result; + } catch(Exception e){ + policyResponse.setPolicyResponseStatus(e.getMessage(), PolicyResponseStatus.NO_ACTION_REQUIRED); + policyResponse = checkResponse(policyResponse); + result.add(policyResponse); + return result; + } + } + + private StdPolicyResponse checkResponse(PolicyResponse pResponse) { + StdPolicyResponse policyResponse= new StdPolicyResponse(); + policyResponse.setActionAdvised(pResponse.getActionAdvised()); + policyResponse.setActionTaken(pResponse.getActionTaken()); + policyResponse.setPolicyResponseMessage(pResponse.getPolicyResponseMessage()); + policyResponse.setPolicyResponseStatus(pResponse.getPolicyResponseStatus()); + policyResponse.setRequestAttributes(pResponse.getRequestAttributes()); + return policyResponse; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java new file mode 100644 index 000000000..8aac105bf --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/ListConfigRequest.java @@ -0,0 +1,69 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.UUID; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.std.StdPolicyConfig; +import org.openecomp.policy.std.StdPolicyEngine; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +public class ListConfigRequest { + + private StdPolicyEngine pe; + public ListConfigRequest(StdPolicyEngine pe){ + this.pe= pe; + } + + public Collection run(ConfigRequestParameters pep, String requestID, String userID, String passcode) { + + StdPolicyConfig policyConfig = new StdPolicyConfig(); + Collection configList = new ArrayList(); + + // construct a UUID from the request string + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } + catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + PolicyLogger.info("Generated Random UUID: " + requestUUID.toString()); + } + } + pep.setRequestID(requestUUID); + try { + PolicyLogger.debug("\n\n calling PEP.. "); + configList = pe.listConfigRequest(pep, userID, passcode); + return configList; + } catch(Exception e){ + policyConfig.setConfigStatus(e.getMessage(), PolicyConfigStatus.CONFIG_NOT_FOUND); + configList.add(policyConfig.getPolicyConfigStatus().toString()); + return configList; + } + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java new file mode 100644 index 000000000..56151f483 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PolicyCreateUpdateRequest.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp; + +import java.util.UUID; + +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyRequest; +import org.openecomp.policy.std.StdPolicyEngine; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +public class PolicyCreateUpdateRequest { + private StdPolicyEngine pe; + public PolicyCreateUpdateRequest(StdPolicyEngine pe){ + this.pe= pe; + } + + public String run(PolicyParameters pep, String requestID, String operation, String userID, String passcode) { + String result = null; + if(pep.getRequestID()==null){ + if (requestID != null && !requestID.isEmpty()) { + try { + pep.setRequestID(UUID.fromString(requestID)); + } + catch (IllegalArgumentException e) { + pep.setRequestID(UUID.randomUUID()); + PolicyLogger.info("Generated Random UUID: " + pep.getRequestID().toString()); + } + } + } + // check if this is create + try{ + if (operation.equalsIgnoreCase("create")) { + result = pe.createPolicy(pep, userID, passcode ).getResponseMessage(); + }else{ + // this is Update policy. + result = pe.updatePolicy(pep, userID, passcode ).getResponseMessage(); + } + }catch(Exception e){ + result = e.getMessage(); + } + return result; + } + + public String run(PepConfigPolicyRequest pep, String requestID, String operation, String userID, String passcode) { + + String result = null; + + // construct a UUID from the request string + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } + catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + PolicyLogger.info("Generated Random UUID: " + requestUUID.toString()); + } + } + + if (pep.getPolicyName()!= null && !pep.getPolicyName().isEmpty()) { + if (pep.getEcompName() != null && !pep.getEcompName().isEmpty()) { + if (pep.getConfigName() != null && !pep.getConfigName().isEmpty()){ + if (pep.getPolicyScope() != null && !pep.getPolicyScope().isEmpty()) { + try { + + if (operation.equalsIgnoreCase("create")) { + + result = pe.createConfigPolicy(pep.getPolicyName(), pep.getPolicyDescription(), pep.getEcompName(), + pep.getConfigName(), pep.getConfigAttributes(), pep.getConfigType(), pep.getBody(), + pep.getPolicyScope(), requestUUID, userID, passcode, pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate()); + } else { + result = pe.updateConfigPolicy(pep.getPolicyName(), pep.getPolicyDescription(), pep.getEcompName(), + pep.getConfigName(), pep.getConfigAttributes(), pep.getConfigType(), pep.getBody(), + pep.getPolicyScope(), requestUUID, userID, passcode, pep.getRiskLevel(), pep.getRiskType(), pep.getGuard(), pep.getTtlDate()); + } + + + } catch (PolicyConfigException e) { + result = e.getMessage(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyScope was null or empty."; + } + + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: configName was null or empty."; + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: ecompName was null or empty."; + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty."; + } + + return result; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java new file mode 100644 index 000000000..47326b326 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/PushPolicyRequest.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp; + +import java.util.UUID; + +import org.openecomp.policy.api.PolicyConfigException; +import org.openecomp.policy.pypdp.model_pojo.PepPushPolicyRequest; +import org.openecomp.policy.std.StdPolicyEngine; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +public class PushPolicyRequest { + private StdPolicyEngine pe; + public PushPolicyRequest(StdPolicyEngine pe){ + this.pe= pe; + } + + public String run(PepPushPolicyRequest pep, String requestID, String userID, String passcode) { + + String result = null; + + // construct a UUID from the request string + UUID requestUUID = null; + if (requestID != null && !requestID.isEmpty()) { + try { + requestUUID = UUID.fromString(requestID); + } + catch (IllegalArgumentException e) { + requestUUID = UUID.randomUUID(); + PolicyLogger.info("Generated Random UUID: " + requestUUID.toString()); + } + }else{ + requestUUID = UUID.randomUUID(); + PolicyLogger.error("No Request UUID Given, hence generating one random ID: " + requestUUID.toString()); + } + String policyName = pep.getPolicyName(); + String policyScope = pep.getPolicyScope(); + if(policyName==null || policyName.isEmpty()){ + return XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyName was null or empty."; + } + if(policyScope== null || policyScope.isEmpty()){ + try{ + policyName = pep.getPolicyName().substring(pep.getPolicyName().lastIndexOf(".")+1, pep.getPolicyName().length()); + policyScope = pep.getPolicyName().substring(0, pep.getPolicyName().lastIndexOf(".")); + } catch (Exception e){ + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "BAD REQUEST: policyScope was null or empty."); + return XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyScope was null or empty."; + } + } + PolicyLogger.info("policyName: " + policyName + " policyScope is : " + policyScope); + if (pep.getPolicyType() != null && !pep.getPolicyType().isEmpty()) { + if (pep.getPdpGroup() != null && !pep.getPdpGroup().isEmpty()) { + try { + result = pe.pushPolicy(policyScope ,policyName , pep.getPolicyType(), pep.getPdpGroup(), requestUUID, userID, passcode); + } catch (PolicyConfigException e) { + result = e.getMessage(); + } catch (Exception e) { + result = e.getMessage(); + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyGroup was null or empty."; + } + } else { + result = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: policyType was null or empty."; + } + return result; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java new file mode 100644 index 000000000..c5526d753 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationFilter.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.authorization; + +import java.io.IOException; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.annotation.WebFilter; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@WebFilter("/*") +public class AuthenticationFilter implements Filter { + + public static final String AUTHENTICATION_HEADER = "Authorization"; + public static final String ENVIRONMENT_HEADER = "Environment"; + + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain filter) throws IOException, ServletException { + if (request instanceof HttpServletRequest) { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + String authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); + String environment = httpServletRequest.getHeader(ENVIRONMENT_HEADER); + String path = ((HttpServletRequest) request).getRequestURI(); + + // better injected + AuthenticationService authenticationService = new AuthenticationService(); + + boolean authenticationStatus = authenticationService.authenticate(authCredentials); + + if (authenticationStatus && environment!=null && (environment.equalsIgnoreCase(Config.getEnvironment()))) { + filter.doFilter(request, response); + } else if(environment==null| path.contains("org.openecomp.policy.pypdp.notifications") || path.contains("swagger") || path.contains("api-docs") || path.contains("configuration") || path.contains("pdps") || path.contains("count") || path.contains("paps")){ + filter.doFilter(request, response); + } else { + if (response instanceof HttpServletResponse) { + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + } + } + if (path.contains("error")){ + HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); + } + } + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig arg0) throws ServletException { + Config.setProperty(); + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java new file mode 100644 index 000000000..c7deac910 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/AuthenticationService.java @@ -0,0 +1,232 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.authorization; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.Properties; +import java.util.StringTokenizer; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +public class AuthenticationService { + private String pyPDPID = Config.getPYPDPID(); + private String pyPDPPass = Config.getPYPDPPass(); + private static Path clientPath = null; + private static HashMap> clientMap = null; + private static Long oldModified = null; + private static Long newModified = null; + private static final Log logger = LogFactory.getLog(AuthenticationService.class); + + public boolean authenticate(String authCredentials) { + + if (null == authCredentials) + return false; + // header value format will be "Basic encodedstring" for Basic authentication. + final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", ""); + String usernameAndPassword = null; + try { + byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); + return false; + } + try { + final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + final String username = tokenizer.nextToken(); + final String password = tokenizer.nextToken(); + + boolean authenticationStatus = pyPDPID.equals(username) && pyPDPPass.equals(password); + return authenticationStatus; + } catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + return false; + } + } + + public static boolean clientAuth(String clientCredentials) { + if(clientCredentials == null){ + return false; + } + // Decode the encoded Client Credentials. + String usernameAndPassword = null; + try { + byte[] decodedBytes = Base64.getDecoder().decode(clientCredentials); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); + return false; + } + try { + final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + final String username = tokenizer.nextToken(); + final String password = tokenizer.nextToken(); + return checkClient(username,password); + } catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); + return false; + } + } + + public static boolean checkClientScope(String clientCredentials, String scope) { + if(clientCredentials == null){ + return false; + } + // Decode the encoded Client Credentials. + String usernameAndPassword = null; + try { + byte[] decodedBytes = Base64.getDecoder().decode(clientCredentials); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, ""); + return false; + } + final StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + final String username = tokenizer.nextToken(); + // Read the properties and compare. + try{ + readFile(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + return false; + } + // Check ID, Scope + if (clientMap.containsKey(username) && (clientMap.get(username).get(1).equals(scope) || clientMap.get(username).get(1).equals("MASTER"))) { + return true; + } + return false; + } + + private static boolean checkClient(String username, String password) { + // Read the properties and compare. + try{ + readFile(); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + return false; + } + // Check ID, Key + if (clientMap.containsKey(username) && clientMap.get(username).get(0).equals(password)) { + return true; + } + return false; + } + + private static void readFile() throws Exception { + String clientFile = Config.getClientFile(); + if (clientFile == null) { + Config.setProperty(); + if(clientFile == null){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Missing CLIENT_FILE property value: " + clientFile); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Missing CLIENT_FILE property value: " + clientFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Missing CLIENT_FILE property value: " + clientFile); + } + } + if (clientPath == null) { + clientPath = Paths.get(clientFile); + if (Files.notExists(clientPath)) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + clientPath.toString()); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "File doesn't exist in the specified Path : " + clientPath.toString()); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ clientPath.toString()); + } + if (clientPath.toString().endsWith(".properties")) { + readProps(); + } else { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + clientFile); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, "Not a .properties file " + clientFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file " + clientFile); + } + } + // Check if File is updated recently + else { + newModified = clientPath.toFile().lastModified(); + if (newModified != oldModified) { + // File has been updated. + readProps(); + } + } + } + + private static void readProps() throws Exception{ + InputStream in; + Properties clientProp = new Properties(); + try { + in = new FileInputStream(clientPath.toFile()); + oldModified = clientPath.toFile().lastModified(); + clientProp.load(in); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, ""); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e); + + } + // Read the Properties and Load the PDPs and encoding. + clientMap = new HashMap>(); + // + for (Object propKey : clientProp.keySet()) { + String clientID = (String)propKey; + String clientValue = clientProp.getProperty(clientID); + if (clientValue != null) { + if (clientValue.contains(",")) { + ArrayList clientValues = new ArrayList(Arrays.asList(clientValue.split("\\s*,\\s*"))); + if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){ + clientMap.put(clientID, clientValues); + } + } + } + } + if (clientMap == null || clientMap.isEmpty()) { + logger.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!"); + } + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java new file mode 100644 index 000000000..388909ecf --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/authorization/Config.java @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.authorization; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.im.IntegrityMonitor; + + +public class Config { + private static final String propertyFilePath = "config.properties"; + private static Properties prop = new Properties(); + private static List pdps = null; + private static List paps = null; + private static List encoding = null; + private static List encodingPAP = null; + private static String pyPDPPass = null; + private static String pyPDPID = null; + private static String environment = null; + private static final Log logger = LogFactory.getLog(Config.class); + private static String clientFile = null; + private static boolean test = false; + + private static IntegrityMonitor im; + private static String resourceName = null; + + public static String getProperty(String propertyKey) { + return prop.getProperty(propertyKey); + } + + /* + * Set Property by reading the properties File. + */ + public static void setProperty() { + Path file = Paths.get(propertyFilePath); + if (Files.notExists(file)) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "File doesn't exist in the specified Path "+ file.toString()); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "File doesn't exist in the specified Path "+ file.toString()); + } else { + InputStream in; + prop = new Properties(); + try { + in = new FileInputStream(file.toFile()); + prop.load(in); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Cannot Load the Properties file" + e); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "Cannot Load the Properties file"); + } + } + // Initializing the values. + pdps = new ArrayList(); + paps = new ArrayList(); + encoding = new ArrayList(); + encodingPAP = new ArrayList(); + + // Check the Keys for PDP_URLs + Collection unsorted = prop.keySet(); + List sorted = new ArrayList(unsorted); + Collections.sort(sorted); + for (String propKey : sorted) { + if (propKey.startsWith("PDP_URL")) { + String check_val = prop.getProperty(propKey); + logger.debug("Property file value for Key : \"" + propKey + "\" Value is : \"" + check_val + "\""); + if (check_val == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have the PDP_URL parameter"); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have the PDP_URL parameter"); + } + if (check_val.contains(";")) { + List pdp_default = new ArrayList(Arrays.asList(check_val.split("\\s*;\\s*"))); + int pdpCount = 0; + while (pdpCount < pdp_default.size()) { + String pdpVal = pdp_default.get(pdpCount); + readPDPParam(pdpVal); + pdpCount++; + } + } else { + readPDPParam(check_val); + } + } else if (propKey.startsWith("PAP_URL")) { + String check_val = prop.getProperty(propKey); + logger.debug("Property file value for Key : \"" + propKey + "\" Value is : \"" + check_val + "\""); + if (check_val == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have the PAP_URL parameter"); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have the PAP_URL parameter"); + } + if (check_val.contains(";")) { + List pap_default = new ArrayList(Arrays.asList(check_val.split("\\s*;\\s*"))); + int papCount=0; + while (papCount < pap_default.size()) { + String papVal = pap_default.get(papCount); + readPAPParam(papVal); + papCount++; + } + } else { + readPAPParam(check_val); + } + } + } + if (pdps == null || pdps.isEmpty()) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Cannot Proceed without PDP_URLs"); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Cannot Proceed without PDP_URLs"); + } + + if (prop.containsKey("PYPDP_ID")) { + String id = prop.getProperty("PYPDP_ID"); + logger.debug("Property file value key: \"PYPDP_ID\" Value is : \"" + id + "\""); + if (id == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_ID parameter"); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_ID parameter"); + } + Config.pyPDPID = id; + } else { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_ID parameter"); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_ID parameter"); + } + if (prop.containsKey("PYPDP_PASSWORD")) { + String pass = prop.getProperty("PYPDP_PASSWORD"); + logger.debug("Property file value key: \"PYPDP_PASSWORD\" Value is : \"" + pass + "\""); + if (pass == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_PASSWORD parameter"); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_PASSWORD parameter"); + } + Config.pyPDPPass = pass; + } else { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Properties file doesn't have PYPDP_PASSWORD parameter"); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "Properties file doesn't have PYPDP_PASSWORD parameter"); + } + environment = prop.getProperty("ENVIRONMENT", "DEVL"); + logger.info("Property value for Environment " + environment); + String value = prop.getProperty("Test"); + if(value!= null && value.equalsIgnoreCase("true")){ + test = true; + } + if(prop.containsKey("CLIENT_FILE")){ + clientFile = prop.getProperty("CLIENT_FILE"); + logger.debug("Property file value key: \"CLIENT_FILE\" Value is : \"" + clientFile + "\""); + if(clientFile == null){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"CLIENT_FILE value is missing."); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "CLIENT_FILE value is missing."); + } + }else{ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"CLIENT_FILE paramter is missing from the property file."); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "CLIENT_FILE paramter is missing from the property file."); + } + logger.info("Trying to set up IntegrityMonitor"); + try { + logger.info("Trying to set up IntegrityMonitor"); + resourceName = prop.getProperty("RESOURCE_NAME").replaceAll(" ", "");; + if(resourceName==null){ + logger.warn("RESOURCE_NAME is missing setting default value. "); + resourceName = "pypdp_pdp01"; + } + im = IntegrityMonitor.getInstance(resourceName, prop); + } catch (Exception e) { + logger.error("Error starting Integerity Monitor: " + e); + } + } + + private static void readPDPParam(String pdpVal) { + if (pdpVal.contains(",")) { + List pdpValues = new ArrayList(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + if (pdpValues.size() == 3) { + // 0 - PDPURL + pdps.add(pdpValues.get(0)); + // 1:2 will be UserID:Password + String userID = pdpValues.get(1); + String pass = pdpValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + encoding.add(encoder.encodeToString((userID + ":" + pass) + .getBytes(StandardCharsets.UTF_8))); + } else { + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"No enough Credentials to send Request. "+ pdpValues); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No enough Credentials to send Request. "+ pdpValues); + } + } else { + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"No enough Credentials to send Request."); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "No enough Credentials to send Request."); + } + } + + private static void readPAPParam(String papVal) { + if (papVal.contains(",")) { + List papValues = new ArrayList(Arrays.asList(papVal.split("\\s*,\\s*"))); + if (papValues.size() == 3) { + // 0 - PAPURL + paps.add(papValues.get(0)); + // 1:2 will be UserID:Password + String userID = papValues.get(1); + String pass = papValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + encodingPAP.add(encoder.encodeToString((userID + ":" + pass) + .getBytes(StandardCharsets.UTF_8))); + } else { + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"Not enough Credentials to send Request. "+ papValues); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, "Not enough Credentials to send Request. "+ papValues); + } + } else { + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS+"Not enough Credentials to send Request."); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS, "Not enough Credentials to send Request."); + } + } + + public static List getPDPs() { + setProperty(); + return Config.pdps; + } + + public static List getPAPs() { + setProperty(); + return Config.paps; + } + + public static List getEncoding() { + return Config.encoding; + } + + public static List getEncodingPAP() { + return Config.encodingPAP; + } + + public static String getPYPDPID() { + return Config.pyPDPID; + } + + public static String getPYPDPPass() { + return Config.pyPDPPass; + } + + public static String getEnvironment(){ + return Config.environment; + } + + public static IntegrityMonitor getIntegrityMonitor(){ + if(im==null){ + setProperty(); + } + return im; + } + + public static String getClientFile() { + return Config.clientFile; + } + + public static Boolean isTest() { + return Config.test; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java new file mode 100644 index 000000000..a98e1109d --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/Application.java @@ -0,0 +1,80 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.controller; + +import javax.servlet.Filter; + +import org.openecomp.policy.pypdp.authorization.AuthenticationFilter; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.context.web.SpringBootServletInitializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackageClasses = {PolicyEngineServices.class}) +public class Application extends SpringBootServletInitializer { + + public static void main(String[] args) { + SpringApplication.run(Application.class, args); + } + + @Override + protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { + return application.sources(applicationClass); + } + + private static Class applicationClass = Application.class; + + @Bean + public Filter authenticationFilter(){ + return new AuthenticationFilter(); + } + + private ApiInfo apiInfo(){ + return new ApiInfoBuilder() + .title("Policy Engine REST API") + .description("This API helps applications across Domain 2.0 Platform to make queries against Policy Engine") + .version("2.0") + .build(); + } + + @Bean + public Docket policyAPI(){ + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(RequestHandlerSelectors.basePackage("org.openecomp.policy.pypdp.controller")) + .build() + .pathMapping("/") + ; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java new file mode 100644 index 000000000..12a5f25f5 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/controller/PolicyEngineServices.java @@ -0,0 +1,556 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.controller; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiImplicitParam; +import io.swagger.annotations.ApiImplicitParams; +import io.swagger.annotations.ApiOperation; + +import java.util.Base64; +import java.util.Collection; +import java.util.List; +import java.util.StringTokenizer; +import java.util.concurrent.atomic.AtomicLong; + +import org.openecomp.policy.api.ConfigRequestParameters; +import org.openecomp.policy.api.DeletePolicyParameters; +import org.openecomp.policy.api.EventRequestParameters; +import org.openecomp.policy.api.NotificationScheme; +import org.openecomp.policy.api.PolicyParameters; +import org.openecomp.policy.api.PolicyResponse; +import org.openecomp.policy.pypdp.ConfigFirewallPolicyRequest; +import org.openecomp.policy.pypdp.ConfigRequest; +import org.openecomp.policy.pypdp.DeletePolicyRequest; +import org.openecomp.policy.pypdp.EventRequest; +import org.openecomp.policy.pypdp.ListConfigRequest; +import org.openecomp.policy.pypdp.PolicyCreateUpdateRequest; +import org.openecomp.policy.pypdp.PushPolicyRequest; +import org.openecomp.policy.pypdp.authorization.AuthenticationService; +import org.openecomp.policy.pypdp.authorization.Config; +import org.openecomp.policy.pypdp.jmx.PyPdpMonitor; +import org.openecomp.policy.pypdp.model_pojo.PepConfigFirewallPolicyRequest; +import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyNameRequest; +import org.openecomp.policy.pypdp.model_pojo.PepConfigPolicyRequest; +import org.openecomp.policy.pypdp.model_pojo.PepPushPolicyRequest; +import org.openecomp.policy.pypdp.model_pojo.PyPolicyConfig; +import org.openecomp.policy.pypdp.notifications.NotificationController; +import org.openecomp.policy.std.StdPolicyEngine; +import org.openecomp.policy.utils.PolicyUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import springfox.documentation.annotations.ApiIgnore; + +import org.openecomp.policy.common.logging.eelf.PolicyLogger; +import org.openecomp.policy.common.im.AdministrativeStateException; +import org.openecomp.policy.common.im.StandbyStatusException; + +@RestController +@Api(value="Policy Engine Services") +public class PolicyEngineServices { + private final NotificationScheme scheme = NotificationScheme.AUTO_ALL_NOTIFICATIONS; + private final NotificationController handler = new NotificationController(); + private final AtomicLong configCounter = PyPdpMonitor.singleton.getAtomicConfigCounter(); + private final AtomicLong eventCounter = PyPdpMonitor.singleton.getAtomicEventCounter(); + private final AtomicLong configPolicyNameCounter = PyPdpMonitor.singleton.getAtomicConfigPolicyNameCounter(); + private final StdPolicyEngine policyEngine = new StdPolicyEngine(Config.getPDPs(), Config.getPAPs(), Config.getEncodingPAP(), Config.getEncoding(), scheme, handler, Config.getEnvironment(), Config.getClientFile(), Config.isTest()); + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Gets the configuration from the PolicyDecisionPoint(PDP)") + @RequestMapping(value = "/getConfig", method = RequestMethod.POST) + public @ResponseBody ResponseEntity> createConfigRequest(@RequestBody ConfigRequestParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) { + Collection policyConfig = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CONFIG"); + } catch (Exception e1) { + return new ResponseEntity>(policyConfig, HttpStatus.UNAUTHORIZED); + } + ConfigRequest configRequest = new ConfigRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + policyConfig = configRequest.run(pep, requestID, userNamePass[0], userNamePass[1]); + configCounter.incrementAndGet(); + Config.getIntegrityMonitor().endTransaction(); + for(PyPolicyConfig pythonConfig: policyConfig){ + if(pythonConfig.getPolicyConfigMessage()!=null && pythonConfig.getPolicyConfigMessage().contains("PE300")){ + return new ResponseEntity>(policyConfig, HttpStatus.BAD_REQUEST); + } + } + return new ResponseEntity>(policyConfig, HttpStatus.OK); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Gets the configuration from the PDP") + @RequestMapping(value = "/listConfig", method = RequestMethod.POST) + public @ResponseBody ResponseEntity> createListConfigRequest(@RequestBody ConfigRequestParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) { + Collection policyList = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CONFIG"); + } catch (Exception e1) { + return new ResponseEntity>(policyList, HttpStatus.UNAUTHORIZED); + } + ListConfigRequest listConfigRequest = new ListConfigRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (StandbyStatusException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + policyList = listConfigRequest.run(pep, requestID, userNamePass[0], userNamePass[1]); + + configCounter.incrementAndGet(); + Config.getIntegrityMonitor().endTransaction(); + + for(String response : policyList){ + if(response!=null && response.contains("PE300")){ + return new ResponseEntity>(policyList, HttpStatus.BAD_REQUEST); + } + } + return new ResponseEntity>(policyList, HttpStatus.OK); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Sends the Events specified to the Policy Engine") + @RequestMapping(value = "/sendEvent", method = RequestMethod.POST) + public @ResponseBody ResponseEntity> createEventParameterRequest(@RequestBody EventRequestParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + Collection policyResponse = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "ACTION"); + } catch (Exception e1) { + return new ResponseEntity>(policyResponse, HttpStatus.UNAUTHORIZED); + } + EventRequest eventRequest = new EventRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + policyResponse = eventRequest.run(pep, requestID, userNamePass[0], userNamePass[1]); + eventCounter.incrementAndGet(); + Config.getIntegrityMonitor().endTransaction(); + for(PolicyResponse response: policyResponse ){ + if(response.getPolicyResponseMessage()!=null && response.getPolicyResponseMessage().contains("PE300")){ + return new ResponseEntity>(policyResponse,HttpStatus.BAD_REQUEST); + } + } + return new ResponseEntity>(policyResponse,HttpStatus.OK); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Gets the configuration from the PolicyDecisionPoint(PDP)") + @RequestMapping(value = "/getConfigByPolicyName", method = RequestMethod.POST) + @Deprecated + public @ResponseBody ResponseEntity> createConfigRequest(@RequestBody PepConfigPolicyNameRequest pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + Collection policyConfig = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CONFIG"); + } catch (Exception e1) { + return new ResponseEntity>(policyConfig, HttpStatus.UNAUTHORIZED); + } + ConfigRequest configRequest = new ConfigRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + policyConfig = configRequest.run(pep, requestID, userNamePass[0], userNamePass[1]); + configPolicyNameCounter.incrementAndGet(); + Config.getIntegrityMonitor().endTransaction(); + return new ResponseEntity>(policyConfig, HttpStatus.OK); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value="Pushes the specified policy to the PDP Group.") + @RequestMapping(value = "/pushPolicy", method = RequestMethod.PUT) + public @ResponseBody ResponseEntity pushPolicyRequest(@RequestBody PepPushPolicyRequest pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + PushPolicyRequest pushPolicy = new PushPolicyRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = pushPolicy.run(pep, requestID, userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if (response.contains("BAD REQUEST")||response.contains("PE300")) { + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } else { + return new ResponseEntity(response, HttpStatus.OK); + } + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value="Deletes the specified policy from the PDP Group or PAP.") + @RequestMapping(value = "/deletePolicy", method = RequestMethod.DELETE) + public @ResponseBody ResponseEntity deletePolicyRequest(@RequestBody DeletePolicyParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "DELETEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + DeletePolicyRequest deletePolicy = new DeletePolicyRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = deletePolicy.run(pep, requestID, userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if (response.contains("BAD REQUEST")||response.contains("PE300")||response.contains("not exist")||response.contains("Invalid policyName")) { + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } else if (response.contains("locked down")){ + return new ResponseEntity(response, HttpStatus.ACCEPTED); + } else if (response.contains("not Authorized")) { + return new ResponseEntity(response, HttpStatus.FORBIDDEN); + } else if (response.contains("groupId")) { + return new ResponseEntity(response, HttpStatus.NOT_FOUND); + } else if (response.contains("JPAUtils")||response.contains("database")||response.contains("policy file")|| + response.contains("unknown")||response.contains("configuration")) { + return new ResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); + } else { + return new ResponseEntity(response, HttpStatus.OK); + } + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Creates a Policy based on given Policy Parameters.") + @RequestMapping(value = "/createPolicy", method = RequestMethod.PUT) + public @ResponseBody ResponseEntity createRequest(@RequestBody PolicyParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false)String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = policyCreateUpdateRequest.run(pep, requestID, "create", userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if(response== null || response.contains("BAD REQUEST")||response.contains("PE300")){ + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } + else if (response.contains("Policy Exist Error")) { + return new ResponseEntity(response, HttpStatus.CONFLICT); + } else if (response.contains("PE200")){ + return new ResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); + } else { + return new ResponseEntity(response, HttpStatus.OK); + } + + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Updates a Policy based on given Policy Parameters.") + @RequestMapping(value = "/updatePolicy", method = RequestMethod.PUT) + public @ResponseBody ResponseEntity updateRequest(@RequestBody PolicyParameters pep,@RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = policyCreateUpdateRequest.run(pep, requestID, "update", userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if (response==null|| response.contains("BAD REQUEST")||response.contains("PE300")){ + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } else if (response.contains("PE200")){ + return new ResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); + } else { + return new ResponseEntity(response, HttpStatus.OK); + } + + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Creates a Config Policy based on given Policy Parameters.") + @RequestMapping(value = "/createConfig", method = RequestMethod.PUT) + @Deprecated + public @ResponseBody ResponseEntity createConfigRequest(@RequestBody PepConfigPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = policyCreateUpdateRequest.run(pep, requestID, "create", userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if (response!=null && !response.contains("BAD REQUEST")) { + return new ResponseEntity(response, HttpStatus.OK); + } else { + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } + + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value= "Updates a Config Policy based on given Policy Parameters.") + @RequestMapping(value = "/updateConfig", method = RequestMethod.PUT) + @Deprecated + public @ResponseBody ResponseEntity updateConfigRequest(@RequestBody PepConfigPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + PolicyCreateUpdateRequest policyCreateUpdateRequest = new PolicyCreateUpdateRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = policyCreateUpdateRequest.run(pep, requestID, "update", userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if (response!=null && !response.contains("BAD REQUEST")) { + return new ResponseEntity(response, HttpStatus.OK); + } else { + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } + + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value = "Creates a Config Firewall Policy") + @RequestMapping(value = "/createFirewallConfig", method = RequestMethod.PUT) + @Deprecated + public @ResponseBody ResponseEntity createFirewallConfigRequest(@RequestBody PepConfigFirewallPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + ConfigFirewallPolicyRequest firewallPolicyRequest = new ConfigFirewallPolicyRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = firewallPolicyRequest.run(pep, requestID, "create", userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if (response!=null && !response.contains("BAD REQUEST")) { + return new ResponseEntity(response, HttpStatus.OK); + } else { + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } + + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header"), + @ApiImplicitParam(name ="Environment", required = true, paramType = "Header") + }) + @ApiOperation(value = "Updates a Config Firewall Policy") + @RequestMapping(value = "/updateFirewallConfig", method = RequestMethod.PUT) + @Deprecated + public @ResponseBody ResponseEntity updateFirewallConfigRequest(@RequestBody PepConfigFirewallPolicyRequest pep, @RequestHeader(value="ClientAuth", required=true)String clientEncoding, + @RequestHeader(value="X-ECOMP-RequestID", required=false) String requestID) { + String response = null; + String[] userNamePass = null; + try { + userNamePass = decodeEncoding(clientEncoding, "CREATEPOLICY"); + } catch (Exception e1) { + return new ResponseEntity(response, HttpStatus.UNAUTHORIZED); + } + ConfigFirewallPolicyRequest firewallPolicyRequest = new ConfigFirewallPolicyRequest(policyEngine); + try{ + Config.getIntegrityMonitor().startTransaction(); + } catch (AdministrativeStateException e) { + PolicyLogger.error("Error while starting Transaction " + e); + } catch (Exception e) { + PolicyLogger.error("Error while starting Transaction " + e); + } + response = firewallPolicyRequest.run(pep, requestID, "update", userNamePass[0], userNamePass[1]); + + Config.getIntegrityMonitor().endTransaction(); + if (response!=null && !response.contains("BAD REQUEST")) { + return new ResponseEntity(response, HttpStatus.OK); + } else { + return new ResponseEntity(response, HttpStatus.BAD_REQUEST); + } + + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header") + }) + @ApiOperation(value= "Gets the API Services usage Information") + @ApiIgnore + @RequestMapping(value = "/count", method = RequestMethod.GET) + public String getCount() { + return "Total Config Calls : " + configCounter + "\n" + +"Total Config calls made using Policy File Name: " + configPolicyNameCounter + "\n" + + "Total Event Calls : " + eventCounter; + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header") + }) + @ApiOperation(value = "Gets the PDPs that are listed to provide service.") + @RequestMapping(value = "/pdps", method = RequestMethod.GET) + public List listPDPs() { + return Config.getPDPs(); + } + + @ApiImplicitParams({ + @ApiImplicitParam(name ="Authorization", required = true, paramType = "Header") + }) + @ApiOperation(value = "Gets the PAPs that are listed to provide service.") + @RequestMapping(value = "/paps", method = RequestMethod.GET) + public List listPAPs() { + return Config.getPAPs(); + } + + /* + * Internal Decoding System. to support old and new Calls. + */ + private String[] decodeEncoding(String clientEncoding, String scope) throws Exception{ + String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding); + if(userNamePass==null){ + if(AuthenticationService.clientAuth(clientEncoding)){ + if(AuthenticationService.checkClientScope(clientEncoding, scope)){ + String usernameAndPassword = null; + byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding); + usernameAndPassword = new String(decodedBytes, "UTF-8"); + StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":"); + String username = tokenizer.nextToken(); + String password = tokenizer.nextToken(); + userNamePass= new String[]{username, password}; + } + } + } + if(userNamePass==null){ + throw new Exception("Client is Not authrorized to make this call. Please contact PyPDP Admin."); + } + return userNamePass; + } +} \ No newline at end of file diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java new file mode 100644 index 000000000..cd1c95d53 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMBeanListener.java @@ -0,0 +1,75 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.jmx; + +import java.lang.management.ManagementFactory; + +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.servlet.ServletContextEvent; +import javax.servlet.ServletContextListener; +import javax.servlet.annotation.WebListener; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@WebListener +public class PyPdpMBeanListener implements ServletContextListener { + private static final String JMX_OBJECT_NAME = "PyPdp:type=PyPdpMonitor"; +// private static final Log logger = LogFactory.getLog(PyPdpMBeanListener.class); + private static final Logger logger = FlexLogger.getLogger(PyPdpMBeanListener.class); + + private ObjectName objectName; + + @Override + public void contextInitialized(ServletContextEvent contextEvent) { + if (logger.isInfoEnabled()) + logger.info("Registering."); + + final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + try { + objectName = new ObjectName(JMX_OBJECT_NAME); + server.registerMBean(PyPdpMonitor.singleton, objectName); + logger.info("MBean registered: " + objectName); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + } + + @Override + public void contextDestroyed(ServletContextEvent arg0) { + if (logger.isInfoEnabled()) + logger.info("Unregistering"); + final MBeanServer server = ManagementFactory.getPlatformMBeanServer(); + try { + objectName = new ObjectName(JMX_OBJECT_NAME); + server.unregisterMBean(objectName); + if (logger.isInfoEnabled()) + logger.info("MBean unregistered: " + objectName); + } catch (Exception e) { + logger.warn(e.getMessage(), e); + } + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java new file mode 100644 index 000000000..849d8ae3f --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitor.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.jmx; + +import java.util.concurrent.atomic.AtomicLong; + +public class PyPdpMonitor implements PyPdpMonitorMBean { + + public static PyPdpMonitor singleton = new PyPdpMonitor(); + + private final AtomicLong configCounter; + private final AtomicLong eventCounter; + private final AtomicLong configPolicyNameCounter; + + private PyPdpMonitor() { + this.configCounter = new AtomicLong(); + this.eventCounter = new AtomicLong(); + this.configPolicyNameCounter = new AtomicLong(); + } + + /** + * @return the configCounter + */ + public AtomicLong getAtomicConfigCounter() { + return configCounter; + } + + /** + * @return the eventCounter + */ + public AtomicLong getAtomicEventCounter() { + return eventCounter; + } + + /** + * @return the configPolicyNameCounter + */ + public AtomicLong getAtomicConfigPolicyNameCounter() { + return configPolicyNameCounter; + } + /** + * @return the configCounter + */ + @Override + public long getConfigCounter() { + return configCounter.longValue(); + } + + /** + * @return the eventCounter + */ + @Override + public long getEventCounter() { + return eventCounter.longValue(); + } + + /** + * @return the configPolicyNameCounter + */ + @Override + public long getConfigPolicyNameCounter() { + return configPolicyNameCounter.longValue(); + } + + @Override + public synchronized void resetCounters() { + this.configCounter.set(0); + this.eventCounter.set(0); + this.configPolicyNameCounter.set(0); + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java new file mode 100644 index 000000000..b111bb6f1 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/jmx/PyPdpMonitorMBean.java @@ -0,0 +1,28 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.jmx; + +public interface PyPdpMonitorMBean { + public long getConfigCounter(); + public long getEventCounter(); + public long getConfigPolicyNameCounter(); + public void resetCounters(); +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java new file mode 100644 index 000000000..1e76854c5 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigFirewallPolicyRequest.java @@ -0,0 +1,82 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.model_pojo; + +import java.io.Serializable; +import java.util.Map; + +import javax.json.JsonObject; + +public class PepConfigFirewallPolicyRequest implements Serializable { + + private static final long serialVersionUID = 1L; + + private String policyName = null; + private String policyScope = null; + private String firewallJson = null; + private String riskType = "defualt"; + private String riskLevel = "5"; + private String guard = "false"; + private String ttlDate = null; + + public String getPolicyName() { + return policyName; + } + public String getPolicyScope() { + return policyScope; + } + public String getFirewallJson() { + return firewallJson; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + public void setFirewallJson(String firewallJson) { + this.firewallJson = firewallJson; + } + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public String getRiskLevel() { + return riskLevel; + } + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + public String getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getTtlDate() { + return ttlDate; + } + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java new file mode 100644 index 000000000..14979b8a1 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyNameRequest.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.model_pojo; + +import java.io.Serializable; + +public class PepConfigPolicyNameRequest implements Serializable{ + + private static final long serialVersionUID = -5045734290192376081L; + + private String policyName = null; + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + + public String getPolicyName() { + return policyName; + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java new file mode 100644 index 000000000..9776e5091 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepConfigPolicyRequest.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.model_pojo; + +import java.io.Serializable; +import java.util.Map; + +public class PepConfigPolicyRequest implements Serializable { + + private static final long serialVersionUID = 7946941587312347282L; + + private String policyScope = null; + private String policyName = null; + private String policyDescription = null; + private String ecompName = null; + private String configName = null; + private Map configAttributes = null; + private String configType = null; + private String body = null; + private String riskType = "defualt"; + private String riskLevel = "5"; + private String guard = "false"; + private String ttlDate = null; + + /** + * @return the policyScope + */ + public String getPolicyScope() { + return policyScope; + } + /** + * @return the policyName + */ + public String getPolicyName() { + return policyName; + } + /** + * @return the policyDescription + */ + public String getPolicyDescription() { + return policyDescription; + } + /** + * @return the ecompName + */ + public String getEcompName() { + return ecompName; + } + /** + * @return the configName + */ + public String getConfigName() { + return configName; + } + /** + * @return the configAttributes + */ + public Map getConfigAttributes() { + return configAttributes; + } + /** + * @return the configType + */ + public String getConfigType() { + return configType; + } + /** + * @return the body + */ + public String getBody() { + return body; + } + /** + * @param policyScope the policyScope to set + */ + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + /** + * @param policyName the policyName to set + */ + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + /** + * @param policyDescription the policyDescription to set + */ + public void setPolicyDescription(String policyDescription) { + this.policyDescription = policyDescription; + } + /** + * @param ecompName the ecompName to set + */ + public void setEcompName(String ecompName) { + this.ecompName = ecompName; + } + /** + * @param configName the configName to set + */ + public void setConfigName(String configName) { + this.configName = configName; + } + /** + * @param configAttributes the configAttributes to set + */ + public void setConfigAttributes(Map configAttributes) { + this.configAttributes = configAttributes; + } + /** + * @param configType the configType to set + */ + public void setConfigType(String configType) { + this.configType = configType; + } + /** + * @param body the body to set + */ + public void setBody(String body) { + this.body = body; + } + /** + * @return the guard + */ + public String getGuard() { + return guard; + } + /** + * @param guard the guard to set + */ + public void setGuard(String guard) { + this.guard = guard; + } + /** + * @return the riskLevel + */ + public String getRiskLevel() { + return riskLevel; + } + /** + * @param riskLevel the riskLevel to set + */ + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + /** + * @return the ttlDate + */ + public String getTtlDate() { + return ttlDate; + } + /** + * @param ttlDate the ttlDate to set + */ + public void setTtlDate(String ttlDate) { + this.ttlDate = ttlDate; + } + /** + * @return the riskType + */ + public String getRiskType() { + return riskType; + } + /** + * @param riskType the riskType to set + */ + public void setRiskType(String riskType) { + this.riskType = riskType; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java new file mode 100644 index 000000000..0c3c8efd9 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PepPushPolicyRequest.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.model_pojo; + +import java.io.Serializable; + +public class PepPushPolicyRequest implements Serializable { + + private static final long serialVersionUID = 2638006651985508836L; + + private String policyScope = null; + private String policyName = null; + private String policyType = null; + private String pdpGroup = null; + + public String getPolicyScope() { + return policyScope; + } + + public String getPolicyName() { + return policyName; + } + + public String getPolicyType() { + return policyType; + } + + public String getPdpGroup() { + return pdpGroup; + } + + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + + public void setPolicyType(String policyType) { + this.policyType = policyType; + } + + public void setPdpGroup(String pdpGroup) { + this.pdpGroup = pdpGroup; + } + + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java new file mode 100644 index 000000000..22882764c --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/model_pojo/PyPolicyConfig.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.model_pojo; + +import io.swagger.annotations.ApiModel; + +import java.util.Map; + +import org.openecomp.policy.api.PolicyConfigStatus; +import org.openecomp.policy.api.PolicyType; + +@ApiModel +public class PyPolicyConfig{ + private String policyConfigMessage; + private PolicyConfigStatus policyConfigStatus; + private PolicyType type; + private String config; + private String policyName; + private String policyVersion; + private Map matchingConditions; + private Map responseAttributes; + private Map property; + public String getConfig() { + return config; + } + public void setConfig(String config) { + this.config = config; + } + public PolicyType getType() { + return type; + } + public void setType(PolicyType type) { + this.type = type; + } + public PolicyConfigStatus getPolicyConfigStatus() { + return policyConfigStatus; + } + public void setPolicyConfigStatus(PolicyConfigStatus policyConfigStatus) { + this.policyConfigStatus = policyConfigStatus; + } + public String getPolicyConfigMessage() { + return policyConfigMessage; + } + public void setPolicyConfigMessage(String policyConfigMessage) { + this.policyConfigMessage = policyConfigMessage; + } + public Map getProperty() { + return property; + } + public void setProperty(Map property) { + this.property = property; + } + public String getPolicyName(){ + return policyName; + } + public void setPolicyName(String policyName){ + this.policyName = policyName; + } + public String getPolicyVersion(){ + return policyVersion; + } + public void setPolicyVersion(String policyVersion){ + this.policyVersion = policyVersion; + } + public Map getMatchingConditions(){ + return matchingConditions; + } + public void setMatchingConditions(Map matchingConditions){ + this.matchingConditions = matchingConditions; + } + public void setResponseAttributes(Map responseAttributes){ + this.responseAttributes = responseAttributes; + } + public Map getResponseAttributes(){ + return responseAttributes; + } +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java new file mode 100644 index 000000000..a1717c275 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/Notification.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.notifications; + +import java.util.Collection; + +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.RemovedPolicy; + +public class Notification{ + + private Collection removedPolicies = null; + private Collection loadedPolicies = null; + + public Collection getRemovedPolicies() { + return removedPolicies; + } + + public Collection getLoadedPolicies() { + return loadedPolicies; + } + + + public void setRemovedPolicies(Collection removedPolicies){ + this.removedPolicies = removedPolicies; + } + + public void setLoadedPolicies(Collection loadedPolicies){ + this.loadedPolicies = loadedPolicies; + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java new file mode 100644 index 000000000..0f2ed9b45 --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationController.java @@ -0,0 +1,149 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.notifications; + +import java.util.HashSet; +import java.util.Iterator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.policy.api.LoadedPolicy; +import org.openecomp.policy.api.NotificationHandler; +import org.openecomp.policy.api.PDPNotification; +import org.openecomp.policy.api.RemovedPolicy; +import org.openecomp.policy.common.logging.eelf.MessageCodes; +import org.openecomp.policy.common.logging.eelf.PolicyLogger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; + +public class NotificationController implements NotificationHandler{ + private static final Log logger = LogFactory.getLog(NotificationController.class); + private static Notification record = new Notification(); + //private static CountDownLatch latch; + + @Override + public void notificationReceived(PDPNotification notification) { + //latch = new CountDownLatch(1); + if(notification!=null){ + // Take this into our Record holder for polling requests. + NotificationServer.setUpdate(record(notification)); + // Send the Update as is for AUTO clients. + ObjectWriter ow = new ObjectMapper().writer(); + try{ + String json = ow.writeValueAsString(notification); + System.out.println("\n Notification: "+json); + logger.info(json); + NotificationServer.sendNotification(json); + //latch.await(); + } catch (JsonProcessingException e) { + logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e.getMessage()); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, ""); + } + + } + } + + public static String record(PDPNotification notification) { + // Initialization with updates. + if(record.getRemovedPolicies()== null){ + record.setRemovedPolicies(notification.getRemovedPolicies()); + } + if(record.getLoadedPolicies()== null){ + record.setLoadedPolicies(notification.getLoadedPolicies()); + } + // Check if there is anything new and update the record.. + if(record.getLoadedPolicies()!= null || record.getRemovedPolicies()!=null) { + HashSet removedPolicies = (HashSet) record.getRemovedPolicies(); + HashSet updatedPolicies = (HashSet) record.getLoadedPolicies(); + // Checking with New updated policies. + if(notification.getLoadedPolicies()!= null && !notification.getLoadedPolicies().isEmpty()) { + for( LoadedPolicy newUpdatedPolicy : notification.getLoadedPolicies()) { + // If it was removed earlier then we need to remove from our record + Iterator oldRemovedPolicy = removedPolicies.iterator(); + while(oldRemovedPolicy.hasNext()){ + RemovedPolicy policy = oldRemovedPolicy.next(); + if(newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was previously updated need to Overwrite it to the record. + Iterator oldUpdatedPolicy = updatedPolicies.iterator(); + while(oldUpdatedPolicy.hasNext()){ + LoadedPolicy policy = oldUpdatedPolicy.next(); + if(newUpdatedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newUpdatedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + updatedPolicies.add(newUpdatedPolicy); + } + } + // Checking with New Removed policies. + if(notification.getRemovedPolicies()!= null && !notification.getRemovedPolicies().isEmpty()) { + for( RemovedPolicy newRemovedPolicy : notification.getRemovedPolicies()) { + // If it was removed earlier then we need to remove from our record + Iterator oldRemovedPolicy = removedPolicies.iterator(); + while(oldRemovedPolicy.hasNext()){ + RemovedPolicy policy = oldRemovedPolicy.next(); + if(newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldRemovedPolicy.remove(); + } + } + } + // If it was previously updated need to Overwrite it to the record. + Iterator oldUpdatedPolicy = updatedPolicies.iterator(); + while(oldUpdatedPolicy.hasNext()){ + LoadedPolicy policy = oldUpdatedPolicy.next(); + if(newRemovedPolicy.getPolicyName().equals(policy.getPolicyName())) { + if(newRemovedPolicy.getVersionNo().equals(policy.getVersionNo())) { + oldUpdatedPolicy.remove(); + } + } + } + removedPolicies.add(newRemovedPolicy); + } + } + record.setRemovedPolicies(removedPolicies); + record.setLoadedPolicies(updatedPolicies); + } + // Send the Result to the caller. + ObjectWriter om = new ObjectMapper().writer(); + String json = null; + try { + json = om.writeValueAsString(record); + } catch (JsonProcessingException e) { + logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e.getMessage()); + // TODO:EELF Cleanup - Remove logger + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, ""); + } + logger.info(json); + return json; + } + +} diff --git a/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java new file mode 100644 index 000000000..44324b55c --- /dev/null +++ b/PyPDPServer/src/main/java/org/openecomp/policy/pypdp/notifications/NotificationServer.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pypdp.notifications; + +import java.io.IOException; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.ServerEndpoint; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + + +@ServerEndpoint(value = "/org.openecomp.policy.pypdp.notifications") +public class NotificationServer { + private static final Logger logger = FlexLogger.getLogger(NotificationServer.class); + private static Queue queue = new ConcurrentLinkedQueue(); + private static String update = null; + + @OnOpen + public void openConnection(Session session) { + logger.info("Session Connected: " + session.getId()); + queue.add(session); + } + + @OnClose + public void closeConnection(Session session) { + queue.remove(session); + } + + @OnError + public void error(Session session, Throwable t) { + queue.remove(session); + logger.info(XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Session Error for : " + session.getId() + " Error: " + t.getMessage()); + + } + + @OnMessage + public void Message(String message, Session session) { + if(message.equalsIgnoreCase("Manual")) { + try { + session.getBasicRemote().sendText(update); + } catch (IOException e) { + logger.info(XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Error in sending the Event Notification: "+ e.getMessage()); + } + } + } + + public static void sendNotification(String notification){ + for(Session session: queue) { + try { + session.getBasicRemote().sendText(notification); + } catch (IOException e) { + logger.info(XACMLErrorConstants.ERROR_SYSTEM_ERROR+ "Error in sending the Event Notification: "+ e.getMessage()); + } + } + } + + public static void setUpdate(String update) { + NotificationServer.update = update; + } +} \ No newline at end of file -- cgit 1.2.3-korg