Upgrade to Tosca derivedFrom fix
[policy/xacml-pdp.git] / applications / common / src / main / java / org / onap / policy / pdp / xacml / application / common / std / StdCombinedPolicyResultsTranslator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2019 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.AttributeAssignment;
26 import com.att.research.xacml.api.DataTypeException;
27 import com.att.research.xacml.api.Decision;
28 import com.att.research.xacml.api.Obligation;
29 import com.att.research.xacml.api.Request;
30 import com.att.research.xacml.api.Response;
31 import com.att.research.xacml.api.Result;
32 import com.att.research.xacml.api.XACML3;
33 import com.att.research.xacml.std.annotations.RequestParser;
34 import com.google.gson.Gson;
35 import java.util.Collection;
36 import java.util.HashMap;
37 import java.util.Map;
38
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
50
51 import org.onap.policy.common.utils.coder.CoderException;
52 import org.onap.policy.common.utils.coder.StandardCoder;
53 import org.onap.policy.models.decisions.concepts.DecisionRequest;
54 import org.onap.policy.models.decisions.concepts.DecisionResponse;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
56 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
57 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
58 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
59 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62
63 public class StdCombinedPolicyResultsTranslator implements ToscaPolicyTranslator {
64
65     private static final Logger LOGGER = LoggerFactory.getLogger(StdCombinedPolicyResultsTranslator.class);
66     private static final String POLICY_ID = "policy-id";
67
68     public StdCombinedPolicyResultsTranslator() {
69         super();
70     }
71
72     @Override
73     public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
74         //
75         // Set it as the policy ID
76         //
77         PolicyType newPolicyType = new PolicyType();
78         newPolicyType.setPolicyId(toscaPolicy.getMetadata().get(POLICY_ID));
79         //
80         // Optional description
81         //
82         newPolicyType.setDescription(toscaPolicy.getDescription());
83         //
84         // There should be a metadata section
85         //
86         this.fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
87         //
88         // Set the combining rule
89         //
90         newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
91         //
92         // Generate the TargetType
93         //
94         TargetType target = this.generateTargetType(toscaPolicy.getMetadata().get(POLICY_ID),
95                 toscaPolicy.getType(), toscaPolicy.getVersion());
96         newPolicyType.setTarget(target);
97         //
98         // Now create the Permit Rule
99         // No target since the policy has a target
100         // With obligations.
101         //
102         RuleType rule = new RuleType();
103         rule.setDescription("Default is to PERMIT if the policy matches.");
104         rule.setRuleId(toscaPolicy.getMetadata().get(POLICY_ID) + ":rule");
105         rule.setEffect(EffectType.PERMIT);
106         rule.setTarget(new TargetType());
107         //
108         // Now represent the policy as Json
109         //
110         StandardCoder coder = new StandardCoder();
111         String jsonPolicy;
112         try {
113             jsonPolicy = coder.encode(toscaPolicy);
114         } catch (CoderException e) {
115             throw new ToscaPolicyConversionException(e);
116         }
117         addObligation(rule, jsonPolicy);
118         //
119         // Add the rule to the policy
120         //
121         newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
122         //
123         // Return our new policy
124         //
125         return newPolicyType;
126     }
127
128     @Override
129     public Request convertRequest(DecisionRequest request) {
130         LOGGER.info("Converting Request {}", request);
131         try {
132             return RequestParser.parseRequest(StdCombinedPolicyRequest.createInstance(request));
133         } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) {
134             LOGGER.error("Failed to convert DecisionRequest: {}", e);
135         }
136         //
137         // TODO throw exception
138         //
139         return null;
140     }
141
142     @Override
143     public DecisionResponse convertResponse(Response xacmlResponse) {
144         LOGGER.info("Converting Response {}", xacmlResponse);
145         DecisionResponse decisionResponse = new DecisionResponse();
146         //
147         // Setup policies
148         //
149         decisionResponse.setPolicies(new HashMap<>());
150         //
151         // Iterate through all the results
152         //
153         for (Result xacmlResult : xacmlResponse.getResults()) {
154             //
155             // Check the result
156             //
157             if (xacmlResult.getDecision() == Decision.PERMIT) {
158                 //
159                 // Go through obligations
160                 //
161                 scanObligations(xacmlResult.getObligations(), decisionResponse);
162             }
163             if (xacmlResult.getDecision() == Decision.DENY
164                     || xacmlResult.getDecision() == Decision.INDETERMINATE) {
165                 //
166                 // TODO we have to return an ErrorResponse object instead
167                 //
168                 decisionResponse.setStatus("A better error message");
169             }
170         }
171
172         return decisionResponse;
173     }
174
175     protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
176         for (Obligation obligation : obligations) {
177             LOGGER.info("Obligation: {}", obligation);
178             for (AttributeAssignment assignment : obligation.getAttributeAssignments()) {
179                 LOGGER.info("Attribute Assignment: {}", assignment);
180                 //
181                 // We care about the content attribute
182                 //
183                 if (ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
184                         .equals(assignment.getAttributeId())) {
185                     //
186                     // The contents are in Json form
187                     //
188                     Object stringContents = assignment.getAttributeValue().getValue();
189                     if (LOGGER.isInfoEnabled()) {
190                         LOGGER.info("DCAE contents: {}{}", System.lineSeparator(), stringContents);
191                     }
192                     //
193                     // Let's parse it into a map using Gson
194                     //
195                     Gson gson = new Gson();
196                     @SuppressWarnings("unchecked")
197                     Map<String, Object> result = gson.fromJson(stringContents.toString() ,Map.class);
198                     //
199                     // Find the metadata section
200                     //
201                     @SuppressWarnings("unchecked")
202                     Map<String, Object> metadata = (Map<String, Object>) result.get("metadata");
203                     if (metadata != null) {
204                         decisionResponse.getPolicies().put(metadata.get(POLICY_ID).toString(), result);
205                     } else {
206                         LOGGER.error("Missing metadata section in policy contained in obligation.");
207                     }
208                 }
209             }
210         }
211     }
212
213     /**
214      * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
215      *
216      * @param policy Policy Object to store the metadata
217      * @param map The Metadata TOSCA Map
218      * @return Same Policy Object
219      * @throws ToscaPolicyConversionException If there is something missing from the metadata
220      */
221     protected PolicyType fillMetadataSection(PolicyType policy,
222             Map<String, String> map) throws ToscaPolicyConversionException {
223         if (! map.containsKey(POLICY_ID)) {
224             throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-id");
225         } else {
226             //
227             // Do nothing here - the XACML PolicyId is used from TOSCA Policy Name field
228             //
229         }
230         if (! map.containsKey("policy-version")) {
231             throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
232         } else {
233             //
234             // Add in the Policy Version
235             //
236             policy.setVersion(map.get("policy-version"));
237         }
238         return policy;
239     }
240
241     protected TargetType generateTargetType(String policyId, String policyType, String policyTypeVersion) {
242         //
243         // Create all the match's that are possible
244         //
245         // This is for the Policy Id
246         //
247         MatchType matchPolicyId = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
248                 XACML3.ID_FUNCTION_STRING_EQUAL,
249                 policyId,
250                 XACML3.ID_DATATYPE_STRING,
251                 ToscaDictionary.ID_RESOURCE_POLICY_ID,
252                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
253         //
254         // This is for the Policy Type
255         //
256         MatchType matchPolicyType = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
257                 XACML3.ID_FUNCTION_STRING_EQUAL,
258                 policyType,
259                 XACML3.ID_DATATYPE_STRING,
260                 ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
261                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
262         //
263         // This is for the Policy Type version
264         //
265         MatchType matchPolicyTypeVersion = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
266                 XACML3.ID_FUNCTION_STRING_EQUAL,
267                 policyTypeVersion,
268                 XACML3.ID_DATATYPE_STRING,
269                 ToscaDictionary.ID_RESOURCE_POLICY_TYPE_VERSION,
270                 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
271         //
272         // This is our outer AnyOf - which is an OR
273         //
274         AnyOfType anyOf = new AnyOfType();
275         //
276         // Create AllOf (AND) of just Policy Id
277         //
278         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyId));
279         //
280         // Create AllOf (AND) of just Policy Type
281         //
282         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyType));
283         //
284         // Create AllOf (AND) of Policy Type and Policy Type Version
285         //
286         anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyType, matchPolicyTypeVersion));
287         //
288         // Now we can create the TargetType, add the top-level anyOf (OR),
289         // and return the value.
290         //
291         TargetType target = new TargetType();
292         target.getAnyOf().add(anyOf);
293         return target;
294     }
295
296     protected RuleType addObligation(RuleType rule, String jsonPolicy) {
297         //
298         // Convert the YAML Policy to JSON Object
299         //
300         if (LOGGER.isInfoEnabled()) {
301             LOGGER.info("JSON DCAE Policy {}{}", System.lineSeparator(), jsonPolicy);
302         }
303         //
304         // Create an AttributeValue for it
305         //
306         AttributeValueType value = new AttributeValueType();
307         value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
308         value.getContent().add(jsonPolicy);
309         //
310         // Create our AttributeAssignmentExpression where we will
311         // store the contents of the policy in JSON format.
312         //
313         AttributeAssignmentExpressionType expressionType = new AttributeAssignmentExpressionType();
314         expressionType.setAttributeId(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS.stringValue());
315         ObjectFactory factory = new ObjectFactory();
316         expressionType.setExpression(factory.createAttributeValue(value));
317         //
318         // Create an ObligationExpression for it
319         //
320         ObligationExpressionType obligation = new ObligationExpressionType();
321         obligation.setFulfillOn(EffectType.PERMIT);
322         obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
323         obligation.getAttributeAssignmentExpression().add(expressionType);
324         //
325         // Now we can add it into the rule
326         //
327         ObligationExpressionsType obligations = new ObligationExpressionsType();
328         obligations.getObligationExpression().add(obligation);
329         rule.setObligationExpressions(obligations);
330         return rule;
331     }
332
333 }