0cd263800b0694e7a98a7ee4521c6bb2c959ae4b
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / ConfigPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pap.xacml.rest.components;
23
24 import java.io.BufferedWriter;
25 import java.io.File;
26 import java.io.FileWriter;
27 import java.io.IOException;
28 import java.net.URI;
29 import java.net.URISyntaxException;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
33 import java.util.Map;
34
35 import org.apache.commons.io.FilenameUtils;
36 import org.onap.policy.common.logging.eelf.MessageCodes;
37 import org.onap.policy.common.logging.eelf.PolicyLogger;
38 import org.onap.policy.common.logging.flexlogger.FlexLogger;
39 import org.onap.policy.common.logging.flexlogger.Logger;
40 import org.onap.policy.rest.adapter.PolicyRestAdapter;
41 import org.onap.policy.utils.PolicyUtils;
42
43 import com.att.research.xacml.api.pap.PAPException;
44 import com.att.research.xacml.std.IdentifierImpl;
45
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
59
60 public class ConfigPolicy extends Policy {
61
62     /**
63      * Config Fields
64      */
65     private static final Logger LOGGER = FlexLogger.getLogger(ConfigPolicy.class);
66
67     public static final String JSON_CONFIG = "JSON";
68     public static final String XML_CONFIG = "XML";
69     public static final String PROPERTIES_CONFIG = "PROPERTIES";
70     public static final String OTHER_CONFIG = "OTHER";
71
72     private String configBodyData;
73
74     public ConfigPolicy() {
75         super();
76     }
77
78     public ConfigPolicy(PolicyRestAdapter policyAdapter) {
79         this.policyAdapter = policyAdapter;
80     }
81
82     // Saving the Configurations file at server location for config policy.
83     protected void saveConfigurations(String policyName) {
84         String fileName = getConfigFile(policyName);
85         try (BufferedWriter bw = new BufferedWriter(new FileWriter(CONFIG_HOME + File.separator + fileName))) {
86             bw.write(configBodyData);
87             if (LOGGER.isDebugEnabled()) {
88                 LOGGER.debug("Configuration is succesfully saved");
89             }
90         } catch (IOException e) {
91             LOGGER.error("Exception Occured while writing Configuration Data" + e);
92         }
93     }
94
95
96     // Here we are adding the extension for the configurations file based on the
97     // config type selection for saving.
98     private String getConfigFile(String filename) {
99         filename = FilenameUtils.removeExtension(filename);
100         if (filename.endsWith(".xml")) {
101             filename = filename.substring(0, filename.length() - 4);
102         }
103         String id = policyAdapter.getConfigType();
104
105         if (id != null) {
106             if (id.equalsIgnoreCase(JSON_CONFIG)) {
107                 filename = filename + ".json";
108             }
109             if (id.equalsIgnoreCase(XML_CONFIG)) {
110                 filename = filename + ".xml";
111             }
112             if (id.equalsIgnoreCase(PROPERTIES_CONFIG)) {
113                 filename = filename + ".properties";
114             }
115             if (id.equalsIgnoreCase(OTHER_CONFIG)) {
116                 filename = filename + ".txt";
117             }
118         }
119         return filename;
120     }
121
122
123     // Validations for Config form
124     /*
125      * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
126      * BODY VALIDATION WILL BE DONE BY THE PAP-REST after receiving and deserializing the JSON object
127      */
128     public boolean validateConfigForm() {
129
130         isValidForm = true;
131
132         /*
133          * Validate Text Area Body
134          */
135         configBodyData = policyAdapter.getConfigBodyData();
136         String id = policyAdapter.getConfigType();
137         if (id != null) {
138             if (id.equals(JSON_CONFIG)) {
139                 if (!PolicyUtils.isJSONValid(configBodyData)) {
140                     isValidForm = false;
141                 }
142             } else if (id.equals(XML_CONFIG)) {
143                 if (!PolicyUtils.isXMLValid(configBodyData)) {
144                     isValidForm = false;
145                 }
146             } else if (id.equals(PROPERTIES_CONFIG)) {
147                 if (!PolicyUtils.isPropValid(configBodyData) || configBodyData.equals("")) {
148                     isValidForm = false;
149                 }
150             } else if (id.equals(OTHER_CONFIG)) {
151                 if (configBodyData.equals("")) {
152                     isValidForm = false;
153                 }
154             }
155         }
156         return isValidForm;
157
158     }
159
160     @Override
161     public Map<String, String> savePolicies() throws PAPException {
162
163         Map<String, String> successMap = new HashMap<>();
164         if (isPolicyExists()) {
165             successMap.put("EXISTS", "This Policy already exist on the PAP");
166             return successMap;
167         }
168
169         if (!isPreparedToSave()) {
170             //Prep and configure the policy for saving
171             prepareToSave();
172         }
173
174         // Until here we prepared the data and here calling the method to create xml.
175         Path newPolicyPath = null;
176         newPolicyPath = Paths.get(policyAdapter.getNewFileName());
177         successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
178         return successMap;
179     }
180
181     //This is the method for preparing the policy for saving.  We have broken it out
182     //separately because the fully configured policy is used for multiple things
183     @Override
184     public boolean prepareToSave() throws PAPException {
185
186         if (isPreparedToSave()) {
187             return true;
188         }
189
190         int version = 0;
191         String policyID = policyAdapter.getPolicyID();
192         version = policyAdapter.getHighestVersion();
193
194         // Create the Instance for pojo, PolicyType object is used in marshalling.
195         if (policyAdapter.getPolicyType().equals("Config")) {
196             PolicyType policyConfig = new PolicyType();
197
198             policyConfig.setVersion(Integer.toString(version));
199             policyConfig.setPolicyId(policyID);
200             policyConfig.setTarget(new TargetType());
201             policyAdapter.setData(policyConfig);
202         }
203
204         policyName = policyAdapter.getNewFileName();
205         configBodyData = policyAdapter.getConfigBodyData();
206         saveConfigurations(policyName);
207
208         if (policyAdapter.getData() != null) {
209             PolicyType configPolicy = (PolicyType) policyAdapter.getData();
210
211             configPolicy.setDescription(policyAdapter.getPolicyDescription());
212
213             configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
214             AllOfType allOfOne = new AllOfType();
215
216             String fileName = policyAdapter.getNewFileName();
217             String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
218             if ((name == null) || (name.equals(""))) {
219                 name = fileName.substring(fileName.lastIndexOf("/") + 1);
220             }
221             allOfOne.getMatch().add(createMatch("PolicyName", name));
222             AllOfType allOf = new AllOfType();
223
224             // Adding the matches to AllOfType element Match for Onap
225             allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
226             // Match for riskType
227             allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
228             // Match for riskLevel
229             allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
230             // Match for riskguard
231             allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
232             // Match for ttlDate
233             allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
234             // Match for ConfigName
235             allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
236
237             Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
238
239             // If there is any dynamic field create the matches here
240             for (String keyField : dynamicFieldConfigAttributes.keySet()) {
241                 String key = keyField;
242                 String value = dynamicFieldConfigAttributes.get(key);
243                 MatchType dynamicMatch = createDynamicMatch(key, value);
244                 allOf.getMatch().add(dynamicMatch);
245             }
246
247             AnyOfType anyOf = new AnyOfType();
248             anyOf.getAllOf().add(allOfOne);
249             anyOf.getAllOf().add(allOf);
250
251             TargetType target = new TargetType();
252             ((TargetType) target).getAnyOf().add(anyOf);
253
254             // Adding the target to the policy element
255             configPolicy.setTarget((TargetType) target);
256
257             RuleType rule = new RuleType();
258             rule.setRuleId(policyAdapter.getRuleID());
259             rule.setEffect(EffectType.PERMIT);
260
261             // Create Target in Rule
262             AllOfType allOfInRule = new AllOfType();
263
264             // Creating match for ACCESS in rule target
265             MatchType accessMatch = new MatchType();
266             AttributeValueType accessAttributeValue = new AttributeValueType();
267             accessAttributeValue.setDataType(STRING_DATATYPE);
268             accessAttributeValue.getContent().add("ACCESS");
269             accessMatch.setAttributeValue(accessAttributeValue);
270             AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
271             URI accessURI = null;
272             try {
273                 accessURI = new URI(ACTION_ID);
274             } catch (URISyntaxException e) {
275                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating ACCESS URI");
276             }
277             accessAttributeDesignator.setCategory(CATEGORY_ACTION);
278             accessAttributeDesignator.setDataType(STRING_DATATYPE);
279             accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
280             accessMatch.setAttributeDesignator(accessAttributeDesignator);
281             accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
282
283             // Creating Config Match in rule Target
284             MatchType configMatch = new MatchType();
285             AttributeValueType configAttributeValue = new AttributeValueType();
286             configAttributeValue.setDataType(STRING_DATATYPE);
287             configAttributeValue.getContent().add("Config");
288             configMatch.setAttributeValue(configAttributeValue);
289             AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
290             URI configURI = null;
291             try {
292                 configURI = new URI(RESOURCE_ID);
293             } catch (URISyntaxException e) {
294                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "ConfigPolicy", "Exception creating Config URI");
295             }
296             configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
297             configAttributeDesignator.setDataType(STRING_DATATYPE);
298             configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
299             configMatch.setAttributeDesignator(configAttributeDesignator);
300             configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
301
302             allOfInRule.getMatch().add(accessMatch);
303             allOfInRule.getMatch().add(configMatch);
304
305             AnyOfType anyOfInRule = new AnyOfType();
306             anyOfInRule.getAllOf().add(allOfInRule);
307
308             TargetType targetInRule = new TargetType();
309             targetInRule.getAnyOf().add(anyOfInRule);
310
311             rule.setTarget(targetInRule);
312             rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
313
314             configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
315             policyAdapter.setPolicyData(configPolicy);
316
317         } else {
318             PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
319         }
320         setPreparedToSave(true);
321         return true;
322     }
323
324     // Data required for Advice part is setting here.
325     private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
326         AdviceExpressionsType advices = new AdviceExpressionsType();
327         AdviceExpressionType advice = new AdviceExpressionType();
328         advice.setAdviceId("configID");
329         advice.setAppliesTo(EffectType.PERMIT);
330
331         // For Configuration
332         AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
333         assignment1.setAttributeId("type");
334         assignment1.setCategory(CATEGORY_RESOURCE);
335         assignment1.setIssuer("");
336
337         AttributeValueType configNameAttributeValue = new AttributeValueType();
338         configNameAttributeValue.setDataType(STRING_DATATYPE);
339         configNameAttributeValue.getContent().add("Configuration");
340         assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
341
342         advice.getAttributeAssignmentExpression().add(assignment1);
343
344         // For Config file Url if configurations are provided.
345         if (policyAdapter.getConfigType() != null) {
346             AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
347             assignment2.setAttributeId("URLID");
348             assignment2.setCategory(CATEGORY_RESOURCE);
349             assignment2.setIssuer("");
350
351             AttributeValueType AttributeValue = new AttributeValueType();
352             AttributeValue.setDataType(URI_DATATYPE);
353             String content = "$URL" + "/Config/" + getConfigFile(policyName);
354             AttributeValue.getContent().add(content);
355             assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
356
357             advice.getAttributeAssignmentExpression().add(assignment2);
358             AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
359             assignment3.setAttributeId("PolicyName");
360             assignment3.setCategory(CATEGORY_RESOURCE);
361             assignment3.setIssuer("");
362
363             AttributeValueType attributeValue3 = new AttributeValueType();
364             attributeValue3.setDataType(STRING_DATATYPE);
365
366             fileName = FilenameUtils.removeExtension(fileName);
367             fileName = fileName + ".xml";
368             String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
369             if ((name == null) || (name.equals(""))) {
370                 name = fileName.substring(fileName.lastIndexOf("/") + 1);
371             }
372             attributeValue3.getContent().add(name);
373             assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
374             advice.getAttributeAssignmentExpression().add(assignment3);
375
376             AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
377             assignment4.setAttributeId("VersionNumber");
378             assignment4.setCategory(CATEGORY_RESOURCE);
379             assignment4.setIssuer("");
380
381             AttributeValueType configNameAttributeValue4 = new AttributeValueType();
382             configNameAttributeValue4.setDataType(STRING_DATATYPE);
383             configNameAttributeValue4.getContent().add(Integer.toString(version));
384             assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
385
386             advice.getAttributeAssignmentExpression().add(assignment4);
387
388             AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
389             assignment5.setAttributeId("matching:" + ONAPID);
390             assignment5.setCategory(CATEGORY_RESOURCE);
391             assignment5.setIssuer("");
392
393             AttributeValueType configNameAttributeValue5 = new AttributeValueType();
394             configNameAttributeValue5.setDataType(STRING_DATATYPE);
395             configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
396             assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
397
398             advice.getAttributeAssignmentExpression().add(assignment5);
399
400             AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
401             assignment6.setAttributeId("matching:" + CONFIGID);
402             assignment6.setCategory(CATEGORY_RESOURCE);
403             assignment6.setIssuer("");
404
405             AttributeValueType configNameAttributeValue6 = new AttributeValueType();
406             configNameAttributeValue6.setDataType(STRING_DATATYPE);
407             configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
408             assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
409
410             advice.getAttributeAssignmentExpression().add(assignment6);
411
412             Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
413             for (String keyField : dynamicFieldConfigAttributes.keySet()) {
414                 String key = keyField;
415                 String value = dynamicFieldConfigAttributes.get(key);
416                 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
417                 assignment7.setAttributeId("matching:" + key);
418                 assignment7.setCategory(CATEGORY_RESOURCE);
419                 assignment7.setIssuer("");
420
421                 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
422                 configNameAttributeValue7.setDataType(STRING_DATATYPE);
423                 configNameAttributeValue7.getContent().add(value);
424                 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
425
426                 advice.getAttributeAssignmentExpression().add(assignment7);
427             }
428         }
429
430         //Risk Attributes
431         AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
432         assignment8.setAttributeId("RiskType");
433         assignment8.setCategory(CATEGORY_RESOURCE);
434         assignment8.setIssuer("");
435
436         AttributeValueType configNameAttributeValue8 = new AttributeValueType();
437         configNameAttributeValue8.setDataType(STRING_DATATYPE);
438         configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
439         assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
440
441         advice.getAttributeAssignmentExpression().add(assignment8);
442
443         AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
444         assignment9.setAttributeId("RiskLevel");
445         assignment9.setCategory(CATEGORY_RESOURCE);
446         assignment9.setIssuer("");
447
448         AttributeValueType configNameAttributeValue9 = new AttributeValueType();
449         configNameAttributeValue9.setDataType(STRING_DATATYPE);
450         configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
451         assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
452
453         advice.getAttributeAssignmentExpression().add(assignment9);
454
455         AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
456         assignment10.setAttributeId("guard");
457         assignment10.setCategory(CATEGORY_RESOURCE);
458         assignment10.setIssuer("");
459
460         AttributeValueType configNameAttributeValue10 = new AttributeValueType();
461         configNameAttributeValue10.setDataType(STRING_DATATYPE);
462         configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
463         assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
464
465         advice.getAttributeAssignmentExpression().add(assignment10);
466
467         AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
468         assignment11.setAttributeId("TTLDate");
469         assignment11.setCategory(CATEGORY_RESOURCE);
470         assignment11.setIssuer("");
471
472         AttributeValueType configNameAttributeValue11 = new AttributeValueType();
473         configNameAttributeValue11.setDataType(STRING_DATATYPE);
474         configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
475         assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
476
477         advice.getAttributeAssignmentExpression().add(assignment11);
478
479         advices.getAdviceExpression().add(advice);
480         return advices;
481     }
482
483     @Override
484     public Object getCorrectPolicyDataObject() {
485         return policyAdapter.getPolicyData();
486     }
487
488 }