Fix optimization bug add coverage plus
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / std / StdBaseTranslator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019-2020 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  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.policy.pdp.xacml.application.common.std;
24
25 import com.att.research.xacml.api.Advice;
26 import com.att.research.xacml.api.Decision;
27 import com.att.research.xacml.api.Obligation;
28 import com.att.research.xacml.api.Request;
29 import com.att.research.xacml.api.Response;
30 import com.att.research.xacml.api.Result;
31 import com.att.research.xacml.api.XACML3;
32 import java.util.Collection;
33 import java.util.HashMap;
34 import java.util.Map;
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
47 import org.onap.policy.models.decisions.concepts.DecisionRequest;
48 import org.onap.policy.models.decisions.concepts.DecisionResponse;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
50 import org.onap.policy.pdp.xacml.application.common.OnapObligation;
51 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
52 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
53 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
54 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
55 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public abstract class StdBaseTranslator implements ToscaPolicyTranslator {
60     private static final Logger LOGGER = LoggerFactory.getLogger(StdBaseTranslator.class);
61     private static final ObjectFactory factory = new ObjectFactory();
62
63     public static final String POLICY_ID = "policy-id";
64     public static final String POLICY_VERSION = "policy-version";
65
66     @Override
67     public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
68         throw new ToscaPolicyConversionException("Please override convertPolicy");
69     }
70
71     @Override
72     public Request convertRequest(DecisionRequest request) {
73         return null;
74     }
75
76     @Override
77     public DecisionResponse convertResponse(Response xacmlResponse) {
78         LOGGER.info("Converting Response {}", xacmlResponse);
79         DecisionResponse decisionResponse = new DecisionResponse();
80         //
81         // Setup policies
82         //
83         decisionResponse.setPolicies(new HashMap<>());
84         //
85         // Iterate through all the results
86         //
87         for (Result xacmlResult : xacmlResponse.getResults()) {
88             //
89             // Check the result
90             //
91             if (xacmlResult.getDecision() == Decision.PERMIT) {
92                 //
93                 // Go through obligations
94                 //
95                 scanObligations(xacmlResult.getObligations(), decisionResponse);
96                 //
97                 // Go through advice
98                 //
99                 scanAdvice(xacmlResult.getAssociatedAdvice(), decisionResponse);
100             } else {
101                 //
102                 // TODO we have to return an ErrorResponse object instead
103                 //
104                 decisionResponse.setStatus("A better error message");
105             }
106         }
107
108         return decisionResponse;
109     }
110
111     /**
112      * scanObligations - scans the list of obligations and make appropriate method calls to process
113      * obligations. This method must be overridden and be implemented for the specific application as
114      * obligations may have different expected attributes per application.
115      *
116      * @param obligations Collection of obligation objects
117      * @param decisionResponse DecisionResponse object used to store any results from obligations.
118      */
119     protected abstract void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse);
120
121     /**
122      * scanAdvice - scans the list of advice and make appropriate call to process the advice. This method
123      * can be overridden for each specific application as advice may have different expected attributes per
124      * application.
125      *
126      * @param advice Collection of Advice objects
127      * @param decisionResponse DecisionResponse object used to store any results from advice.
128      */
129     protected abstract void scanAdvice(Collection<Advice> advice, DecisionResponse decisionResponse);
130
131     /**
132      * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
133      *
134      * @param policy Policy Object to store the metadata
135      * @param map The Metadata TOSCA Map
136      * @return Same Policy Object
137      * @throws ToscaPolicyConversionException If there is something missing from the metadata
138      */
139     protected PolicyType fillMetadataSection(PolicyType policy,
140             Map<String, String> map) throws ToscaPolicyConversionException {
141         //
142         // Ensure the policy-id exists - we don't use it here. It
143         // is saved in the TOSCA Policy Name field.
144         //
145         if (! map.containsKey(POLICY_ID)) {
146             throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata " + POLICY_ID);
147         }
148         //
149         // Ensure the policy-version exists
150         //
151         if (! map.containsKey(POLICY_VERSION)) {
152             throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata "
153                     + POLICY_VERSION);
154         }
155         //
156         // Add in the Policy Version
157         //
158         policy.setVersion(map.get(POLICY_VERSION));
159         return policy;
160     }
161
162     /**
163      * addObligation - general code to add a json policy as an obligation. Probably could just
164      * return the obligation only instead of adding it directly to a rule/policy/policyset.
165      * But this is fine for now.
166      *
167      * @param <T> RuleType, PolicyType, PolicySetType object
168      * @Param policyId The policy-id
169      * @param ruleOrPolicy Incoming RuleType, PolicyType, PolicySetType object
170      * @param jsonPolicy JSON String representation of policy.
171      * @param weight Weighting for the policy (optional)
172      * @return Return the Incoming RuleType, PolicyType, PolicySetType object for convenience.
173      */
174     protected <T> T addObligation(T ruleOrPolicy, String policyId, String jsonPolicy, Integer weight,
175             String policyType) {
176         //
177         // Creating obligation for returning policy
178         //
179         LOGGER.info("Obligation Policy id: {} type: {} weight: {} policy:{}{}", policyId, policyType, weight,
180                 XacmlPolicyUtils.LINE_SEPARATOR, jsonPolicy);
181         //
182         // Create our OnapObligation
183         //
184         OnapObligation onapObligation = new OnapObligation(policyId, jsonPolicy, policyType, weight);
185         //
186         // Generate the obligation
187         //
188         ObligationExpressionType obligation = onapObligation.generateObligation();
189         //
190         // Now we can add it into the rule/policy/policyset
191         //
192         ObligationExpressionsType obligations = new ObligationExpressionsType();
193         obligations.getObligationExpression().add(obligation);
194         if (ruleOrPolicy instanceof RuleType) {
195             ((RuleType) ruleOrPolicy).setObligationExpressions(obligations);
196         } else if (ruleOrPolicy instanceof PolicyType) {
197             ((PolicyType) ruleOrPolicy).setObligationExpressions(obligations);
198         } else if (ruleOrPolicy instanceof PolicySetType) {
199             ((PolicySetType) ruleOrPolicy).setObligationExpressions(obligations);
200         } else {
201             LOGGER.error("Unsupported class for adding obligation {}", ruleOrPolicy.getClass());
202         }
203         //
204         // Return as a convenience
205         //
206         return ruleOrPolicy;
207     }
208
209     /**
210      * generateAnyOfForPolicyType - Creates a specific AnyOfType that includes the check
211      * to match on a specific TOSCA Policy Type.
212      *
213      * @param type String represenatation of TOSCA Policy Type (eg. "onap.policies.Foo")
214      * @return AnyOfType object
215      */
216     protected AnyOfType generateAnyOfForPolicyType(String type) {
217         //
218         // Create the match for the policy type
219         //
220         MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
221                 XACML3.ID_FUNCTION_STRING_EQUAL,
222                 type,
223                 XACML3.ID_DATATYPE_STRING,
224                 ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
225                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
226         //
227         // Add it to an AnyOfType object
228         //
229         AnyOfType anyOf = new AnyOfType();
230         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(match));
231         //
232         // Return new AnyOfType
233         //
234         return anyOf;
235     }
236
237     /**
238      * generateConditionForPolicyType - create a ConditionType XACML object
239      * that is able to determine if a request specifies a specific policy type
240      * that the policy is created from, only then is the rule applied. If the
241      * request doesn't even care about the policy type (eg it is missing) then
242      * return the rule should not apply.
243      *
244      * @param type PolicyType (eg. onap.policies.Foo
245      * @return ConditionType object
246      */
247     protected ConditionType generateConditionForPolicyType(String type) {
248         //
249         // Create an ApplyType that checks if the request contains the
250         // policy-type attribute
251         //
252         AttributeDesignatorType designator = new AttributeDesignatorType();
253         designator.setAttributeId(ToscaDictionary.ID_RESOURCE_POLICY_TYPE.stringValue());
254         designator.setCategory(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
255         designator.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
256
257         ApplyType applyBagSize = new ApplyType();
258         applyBagSize.setDescription("Get the size of policy-type attributes");
259         applyBagSize.setFunctionId(XACML3.ID_FUNCTION_STRING_BAG_SIZE.stringValue());
260
261         AttributeValueType valueZero = new AttributeValueType();
262         valueZero.setDataType(XACML3.ID_DATATYPE_INTEGER.stringValue());
263         valueZero.getContent().add("0");    // Yes really - represent as a string
264
265         applyBagSize.getExpression().add(factory.createAttributeDesignator(designator));
266
267         ApplyType applyGreaterThan = new ApplyType();
268         applyGreaterThan.setDescription("Does the policy-type attribute exist?");
269         applyGreaterThan.setFunctionId(XACML3.ID_FUNCTION_INTEGER_EQUAL.stringValue());
270
271         applyGreaterThan.getExpression().add(factory.createApply(applyBagSize));
272         applyGreaterThan.getExpression().add(factory.createAttributeValue(valueZero));
273
274         //
275         // Create an apply type that checks the actual value
276         //
277         AttributeValueType value = new AttributeValueType();
278         value.setDataType(XACML3.ID_DATATYPE_STRING.stringValue());
279         value.getContent().add(type);
280
281         //
282         // Create string-is-in apply - which determines if the policy-type
283         // is in the request bag of resources for policy-type
284         //
285         ApplyType applyIsIn = new ApplyType();
286         applyIsIn.setDescription("Is this policy-type in the list?");
287         applyIsIn.setFunctionId(XACML3.ID_FUNCTION_STRING_IS_IN.stringValue());
288         applyIsIn.getExpression().add(factory.createAttributeValue(value));
289         applyIsIn.getExpression().add(factory.createAttributeDesignator(designator));
290
291         //
292         // Create our outer apply
293         //
294         ApplyType applyOr = new ApplyType();
295         applyOr.setDescription("IF exists and is equal");
296         applyOr.setFunctionId(XACML3.ID_FUNCTION_OR.stringValue());
297
298         applyOr.getExpression().add(factory.createApply(applyGreaterThan));
299         applyOr.getExpression().add(factory.createApply(applyIsIn));
300
301         //
302         // Finally create the condition
303         //
304         ConditionType condition = new ConditionType();
305
306         condition.setExpression(factory.createApply(applyOr));
307
308         return condition;
309     }
310
311 }