2196209d8f15d85bd64acb31a2ccb80547019588
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / Policy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.HashMap;
31 import java.util.Map;
32
33 import org.apache.commons.io.FilenameUtils;
34 import org.onap.policy.common.logging.eelf.MessageCodes;
35 import org.onap.policy.common.logging.eelf.PolicyLogger;
36 import org.onap.policy.common.logging.flexlogger.FlexLogger;
37 import org.onap.policy.common.logging.flexlogger.Logger;
38 import org.onap.policy.rest.XACMLRestProperties;
39 import org.onap.policy.rest.adapter.PolicyRestAdapter;
40 import org.onap.policy.xacml.util.XACMLPolicyWriter;
41
42 import com.att.research.xacml.api.pap.PAPException;
43 import com.att.research.xacml.std.IdentifierImpl;
44 import com.att.research.xacml.util.XACMLProperties;
45 import com.att.research.xacmlatt.pdp.policy.PolicyDef;
46 import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef;
47
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
52
53 public abstract class Policy {
54         
55         private static final Logger LOGGER      = FlexLogger.getLogger(Policy.class);
56         
57
58         /**
59          * Common Fields
60          */
61         public static final String GET_INT_TYPE = "Integer";
62         public static final String GET_STRING_TYPE = "String";
63
64         public static final String ONAPID = "ONAPName";
65         public static final String CONFIGID = "ConfigName";
66         public static final String CLOSEDLOOPID = "ServiceType";
67
68         public static final String CONFIG_POLICY = "Config";
69         public static final String ACTION_POLICY = "Action";
70         public static final String DECISION_POLICY = "Decision";
71
72         protected String policyName = null;
73
74         protected boolean isValidForm = true;
75
76         private Path finalPolicyPath = null;
77
78         private boolean preparedToSave = false;
79
80         private boolean policyExists = false;
81
82         public Path getFinalPolicyPath() {
83                 return finalPolicyPath;
84         }
85
86         public void setFinalPolicyPath(Path finalPolicyPath) {
87                 this.finalPolicyPath = finalPolicyPath;
88         }
89
90         // Constants Used in XML Creation
91         public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject";
92         public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource";
93         public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action";
94         public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject";
95         public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id";
96         public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id";
97         public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id";
98         public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only";
99         public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only";
100         public static final String FUNCTION_BOOLEAN_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:boolean-one-and-only";
101         public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal";
102         public static final String FUNCTION_STRING_REGEX_MATCH = "org.onap.function.regex-match";
103         public static final String FUNCTION_STRING_REGEXP_MATCH = "urn:oasis:names:tc:xacml:1.0:function:string-regexp-match";
104         public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case";
105         public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer";
106         public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean";
107         public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string";
108         public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI";
109         public static final String RULE_VARIABLE = "var:";
110         public static final String EMPTY_STRING = "";
111
112         protected static String CONFIG_HOME = null;
113         protected static String ACTION_HOME = null;
114         protected static String CONFIG_URL = null;
115
116         protected Map<String, String> performer = new HashMap<>();
117
118         private static String actionHome = null;
119         private static String configHome = null;
120
121         public PolicyRestAdapter policyAdapter = null;
122         String ruleID = "";
123
124         public Policy() {
125                 CONFIG_HOME = getConfigHome();
126                 ACTION_HOME = getActionHome();
127                 CONFIG_URL = "$URL";
128                 performer.put("PDP", "PDPAction");
129                 performer.put("PEP", "PEPAction");
130         }
131
132         //Each policy type seems to either use policyData or data field policy adapter when
133         //getting the xml to save the policy. Instead of keep this hardcoded in the save method,
134         //this method makes it usable outside.
135         /**
136          * Return the data field of the PolicyAdapter that will be used when saving this policy
137          * with the savePolicies method.
138          * @return Either the PolicyAdapter.getData() or PolicyAdapter.getPolicyData()
139          */
140         public abstract Object getCorrectPolicyDataObject();
141         public abstract Map<String, String>  savePolicies() throws PAPException;
142
143         //This is the method for preparing the policy for saving.  We have broken it out
144         //separately because the fully configured policy is used for multiple things
145         public abstract boolean prepareToSave() throws PAPException;
146
147
148         // create match for onap and config name
149         protected MatchType createMatch(String key, String value) {
150                 MatchType match = new MatchType();
151
152                 AttributeValueType attributeValue = new AttributeValueType();
153                 attributeValue.setDataType(STRING_DATATYPE);
154                 attributeValue.getContent().add(value);
155                 match.setAttributeValue(attributeValue);
156                 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
157                 URI uri = null;
158                 try {
159                         uri = new URI(key);
160                 } catch (URISyntaxException e) {
161                         LOGGER.error("Exception Occured"+e);
162                 }
163                 attributeDesignator.setCategory(CATEGORY_ACCESS_SUBJECT);
164                 attributeDesignator.setDataType(STRING_DATATYPE);
165                 attributeDesignator.setAttributeId(new IdentifierImpl(uri).stringValue());
166                 match.setAttributeDesignator(attributeDesignator);
167                 match.setMatchId(FUNCTION_STRING_REGEX_MATCH);
168                 return match;
169         }
170
171         // Creating the match for dynamically added components.
172         protected MatchType createDynamicMatch(String key, String value) {
173                 MatchType dynamicMatch = new MatchType();
174                 AttributeValueType dynamicAttributeValue = new AttributeValueType();
175                 String dataType = null;
176                 dataType = STRING_DATATYPE;
177                 dynamicAttributeValue.setDataType(dataType);
178                 dynamicAttributeValue.getContent().add(value);
179                 dynamicMatch.setAttributeValue(dynamicAttributeValue);
180
181                 AttributeDesignatorType dynamicAttributeDesignator = new AttributeDesignatorType();
182
183                 URI dynamicURI = null;
184                 try {
185                         dynamicURI = new URI(key);
186                 } catch (URISyntaxException e) {
187                         LOGGER.error("Exception Occured"+e);// log msg
188                 }
189                 dynamicAttributeDesignator.setCategory(CATEGORY_RESOURCE);
190                 dynamicAttributeDesignator.setDataType(dataType);
191                 dynamicAttributeDesignator.setAttributeId(new IdentifierImpl(dynamicURI).stringValue());
192                 dynamicMatch.setAttributeDesignator(dynamicAttributeDesignator);
193                 dynamicMatch.setMatchId(FUNCTION_STRING_REGEX_MATCH);
194
195                 return dynamicMatch;
196         }
197
198         //  the Policy Name as Unique One throws error
199         @SuppressWarnings("static-access")
200         protected Path getNextFilename(Path parent, String policyType, String polcyFileName, Integer version) {
201                 policyType = FilenameUtils.removeExtension(policyType);
202                 polcyFileName = FilenameUtils.removeExtension(polcyFileName);
203                 Path newFile = null;
204                 String policyDir = EMPTY_STRING;
205                 String absolutePath = parent.toString();
206                 if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) {
207                         policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length());
208                         if (policyDir == null || policyDir.equals(EMPTY_STRING)) {
209                                 policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length());
210                         }
211                 }
212
213                 String fileName = "default";
214                 if (policyDir != null && !policyDir.equals(EMPTY_STRING)) {
215                         fileName = policyType + "_" + String.format(polcyFileName) + "." + version + ".xml";
216                 } 
217                 if (fileName != null) {
218                         newFile = Paths.get(parent.toString(), fileName);
219                 }
220                 if (Files.notExists(newFile)) {
221                         return newFile;
222                 }
223                 return null;
224         }
225
226         protected Path getNextLoopFilename(Path parentPath, String policyType, String policyConfigType, String policyFileName, Integer version) {
227                 policyType = FilenameUtils.removeExtension(policyType);
228                 policyConfigType = FilenameUtils.removeExtension(policyConfigType);
229                 policyFileName = FilenameUtils.removeExtension(policyFileName);
230                 Path newFile = null;
231                 String policyDir = EMPTY_STRING;
232                 String absolutePath = parentPath.toString();
233                 if (absolutePath != null && !absolutePath.equals(EMPTY_STRING)) {
234                         policyDir = absolutePath.substring(absolutePath.lastIndexOf("\\") + 1, absolutePath.length());
235                         if (policyDir == null || policyDir.equals(EMPTY_STRING)) {
236                                 policyDir = absolutePath.substring(absolutePath.lastIndexOf("/") + 1, absolutePath.length());
237                         }
238                 }
239
240                 String fileName = "default";
241                 if (policyDir != null && !policyDir.equals(EMPTY_STRING)) {
242                         if(policyConfigType.equals("ClosedLoop_PM")){
243                                 fileName = policyType + "_" + "PM" + "_" +java.lang.String.format(policyFileName) + "." +version +".xml";
244                         }else if(policyConfigType.equals("ClosedLoop_Fault")){
245                                 fileName = policyType + "_" + "Fault" + "_" +java.lang.String.format(policyFileName) +  "." + version + ".xml";
246                         }else if(policyConfigType.equals("Micro Service")){
247                                 fileName = policyType + "_" + "MS" + "_" + java.lang.String.format(policyFileName) + "." + version + ".xml";
248                         }
249                 } 
250                 if (fileName != null) {
251                         newFile = Paths.get(parentPath.toString(), fileName);
252                 }
253                 if (Files.notExists(newFile)) {
254                         return newFile;
255                 }
256                 return null;
257         }
258
259
260         //create policy once all the validations are completed
261         protected Map<String, String> createPolicy(final Path policyPath, final Object policyData) {
262                 Map<String, String> success = new HashMap<>(); 
263                 //
264                 // Is the root a PolicySet or Policy?
265                 //
266
267                 if (policyData instanceof PolicyType) {
268                         //
269                         // Write it out
270                         //
271                         //Does not need to be XACMLPolicyWriterWithPapNotify since it is already in the PAP
272                         //and this transaction is intercepted up stream.
273                         InputStream inputStream = null;
274                         try {
275                                 inputStream = XACMLPolicyWriter.getXmlAsInputStream((PolicyType) policyData);
276                                 PolicyDef policyDef = DOMPolicyDef.load(inputStream);
277                                 if (policyDef == null) {
278                                         success.put("validation", "PolicyDef Validation Failed");
279                                 }else{
280                                         success.put("success", "success");
281                                 }
282                         } catch (Exception e) {
283                                 LOGGER.error("PolicyDef Validation failed"+e);
284                                 success.put("error", "Validation Failed");
285                         }finally{
286                                 try {
287                                         if(inputStream != null)
288                                                 inputStream.close();
289                                 } catch (IOException e) {
290                                         LOGGER.error("Exception Occured while closing the input stream"+e);
291                                 }
292                         }
293                 } else {
294                         PolicyLogger.error("Unknown data type sent back.");
295                         return success;
296                 }
297                 return success;
298         }
299
300         public static String getConfigHome(){
301                 try {
302                         loadWebapps();
303                 } catch (Exception e) {
304                         LOGGER.debug(e);
305                         return null;
306                 }
307                 return configHome;
308         }
309
310         public static String getActionHome(){
311                 try {
312                         loadWebapps();
313                 } catch (Exception e) {
314                         LOGGER.debug(e);
315                         return null;
316                 }
317                 return actionHome;
318         }
319
320         private static void loadWebapps() throws PAPException{
321                 if(actionHome == null || configHome == null){
322                         Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS));
323                         //Sanity Check
324                         if (webappsPath == null) {
325                                 PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
326                                 throw new PAPException("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS);
327                         }
328                         Path webappsPathConfig;
329                         Path webappsPathAction;
330                         if(webappsPath.toString().contains("\\")){
331                                 webappsPathConfig = Paths.get(webappsPath.toString()+"\\Config");
332                                 webappsPathAction = Paths.get(webappsPath.toString()+"\\Action");
333                         }else{
334                                 webappsPathConfig = Paths.get(webappsPath.toString()+"/Config");
335                                 webappsPathAction = Paths.get(webappsPath.toString()+"/Action");
336                         }
337                         if(!webappsPathConfig.toFile().exists()){
338                                 try {
339                                         Files.createDirectories(webappsPathConfig);
340                                 } catch (IOException e) {
341                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory");
342                                 }
343                         }
344                         if(!webappsPathAction.toFile().exists()){
345                                 try {
346                                         Files.createDirectories(webappsPathAction);
347                                 } catch (IOException e) {
348                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "Policy", "Failed to create config directory");
349                                 }
350                         }
351                         actionHome = webappsPathAction.toString();
352                         configHome = webappsPathConfig.toString();
353                 }
354         }
355         
356         public boolean validateConfigForm() {
357                 return true;
358         }
359
360         /**
361          * @return the preparedToSave
362          */
363         public boolean isPreparedToSave() {
364                 return preparedToSave;
365         }
366
367         /**
368          * @param preparedToSave the preparedToSave to set
369          */
370         protected void setPreparedToSave(boolean preparedToSave) {
371                 this.preparedToSave = preparedToSave;
372         }
373
374         public boolean isPolicyExists() {
375                 return policyExists;
376         }
377
378         public void setPolicyExists(boolean policyExists) {
379                 this.policyExists = policyExists;
380         }
381
382
383 }