2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.pdp.xacml.application.common.std;
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;
36 import java.util.ArrayList;
37 import java.util.Collection;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
52 import org.onap.policy.common.utils.coder.CoderException;
53 import org.onap.policy.common.utils.coder.StandardCoder;
54 import org.onap.policy.models.decisions.concepts.DecisionRequest;
55 import org.onap.policy.models.decisions.concepts.DecisionResponse;
56 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
57 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
58 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
59 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
60 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
61 import org.slf4j.Logger;
62 import org.slf4j.LoggerFactory;
64 public class StdCombinedPolicyResultsTranslator implements ToscaPolicyTranslator {
66 private static final Logger LOGGER = LoggerFactory.getLogger(StdCombinedPolicyResultsTranslator.class);
68 public StdCombinedPolicyResultsTranslator() {
73 public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
75 // Set it as the policy ID
77 PolicyType newPolicyType = new PolicyType();
78 newPolicyType.setPolicyId(toscaPolicy.getMetadata().get("policy-id"));
80 // Optional description
82 newPolicyType.setDescription(toscaPolicy.getDescription());
84 // There should be a metadata section
86 this.fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
88 // Set the combining rule
90 newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
92 // Generate the TargetType
94 TargetType target = this.generateTargetType(toscaPolicy.getMetadata().get("policy-id"),
95 toscaPolicy.getType(), toscaPolicy.getVersion());
96 newPolicyType.setTarget(target);
98 // Now create the Permit Rule
99 // No target since the policy has a target
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());
108 // Now represent the policy as Json
110 StandardCoder coder = new StandardCoder();
113 jsonPolicy = coder.encode(toscaPolicy);
114 } catch (CoderException e) {
115 LOGGER.error("Failed to encode policy to json", e);
116 throw new ToscaPolicyConversionException(e);
118 addObligation(rule, jsonPolicy);
120 // Add the rule to the policy
122 newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
124 // Return our new policy
126 return newPolicyType;
130 public Request convertRequest(DecisionRequest request) {
131 LOGGER.debug("Converting Request {}", request);
133 return RequestParser.parseRequest(StdCombinedPolicyRequest.createInstance(request));
134 } catch (IllegalArgumentException | IllegalAccessException | DataTypeException e) {
135 LOGGER.error("Failed to convert DecisionRequest: {}", e);
138 // TODO throw exception
144 public DecisionResponse convertResponse(Response xacmlResponse) {
145 LOGGER.debug("Converting Response {}", xacmlResponse);
146 DecisionResponse decisionResponse = new DecisionResponse();
148 // Iterate through all the results
150 for (Result xacmlResult : xacmlResponse.getResults()) {
154 if (xacmlResult.getDecision() == Decision.PERMIT) {
158 decisionResponse.setPolicies(new ArrayList<>());
160 // Go through obligations
162 scanObligations(xacmlResult.getObligations(), decisionResponse);
164 if (xacmlResult.getDecision() == Decision.NOTAPPLICABLE) {
166 // There is no policy
168 decisionResponse.setPolicies(new ArrayList<>());
170 if (xacmlResult.getDecision() == Decision.DENY
171 || xacmlResult.getDecision() == Decision.INDETERMINATE) {
173 // TODO we have to return an ErrorResponse object instead
175 decisionResponse.setStatus("A better error message");
179 return decisionResponse;
182 protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
183 for (Obligation obligation : obligations) {
184 LOGGER.debug("Obligation: {}", obligation);
185 for (AttributeAssignment assignment : obligation.getAttributeAssignments()) {
186 LOGGER.debug("Attribute Assignment: {}", assignment);
188 // We care about the content attribute
190 if (ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
191 .equals(assignment.getAttributeId())) {
193 // The contents are in Json form
195 Object stringContents = assignment.getAttributeValue().getValue();
196 if (LOGGER.isDebugEnabled()) {
197 LOGGER.debug("DCAE contents: {}{}", System.lineSeparator(), stringContents);
200 // Let's parse it into a map using Gson
202 Gson gson = new Gson();
203 @SuppressWarnings("unchecked")
204 Map<String, Object> result = gson.fromJson(stringContents.toString() ,Map.class);
205 decisionResponse.getPolicies().add(result);
212 * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
214 * @param policy Policy Object to store the metadata
215 * @param map The Metadata TOSCA Map
216 * @return Same Policy Object
217 * @throws ToscaPolicyConversionException If there is something missing from the metadata
219 protected PolicyType fillMetadataSection(PolicyType policy,
220 Map<String, String> map) throws ToscaPolicyConversionException {
221 if (! map.containsKey("policy-id")) {
222 throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-id");
225 // Do nothing here - the XACML PolicyId is used from TOSCA Policy Name field
228 if (! map.containsKey("policy-version")) {
229 throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
232 // Add in the Policy Version
234 policy.setVersion(map.get("policy-version").toString());
239 protected TargetType generateTargetType(String policyId, String policyType, String policyTypeVersion) {
241 // Create all the match's that are possible
243 // This is for the Policy Id
245 MatchType matchPolicyId = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
246 XACML3.ID_FUNCTION_STRING_EQUAL,
248 XACML3.ID_DATATYPE_STRING,
249 ToscaDictionary.ID_RESOURCE_POLICY_ID,
250 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
252 // This is for the Policy Type
254 MatchType matchPolicyType = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
255 XACML3.ID_FUNCTION_STRING_EQUAL,
257 XACML3.ID_DATATYPE_STRING,
258 ToscaDictionary.ID_RESOURCE_POLICY_TYPE,
259 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
261 // This is for the Policy Type version
263 MatchType matchPolicyTypeVersion = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
264 XACML3.ID_FUNCTION_STRING_EQUAL,
266 XACML3.ID_DATATYPE_STRING,
267 ToscaDictionary.ID_RESOURCE_POLICY_TYPE_VERSION,
268 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
270 // This is our outer AnyOf - which is an OR
272 AnyOfType anyOf = new AnyOfType();
274 // Create AllOf (AND) of just Policy Id
276 anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyId));
278 // Create AllOf (AND) of just Policy Type
280 anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyType));
282 // Create AllOf (AND) of Policy Type and Policy Type Version
284 anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(matchPolicyType, matchPolicyTypeVersion));
286 // Now we can create the TargetType, add the top-level anyOf (OR),
287 // and return the value.
289 TargetType target = new TargetType();
290 target.getAnyOf().add(anyOf);
294 protected RuleType addObligation(RuleType rule, String jsonPolicy) {
296 // Convert the YAML Policy to JSON Object
298 if (LOGGER.isDebugEnabled()) {
299 LOGGER.debug("JSON DCAE Policy {}{}", System.lineSeparator(), jsonPolicy);
302 // Create an AttributeValue for it
304 AttributeValueType value = new AttributeValueType();
305 value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
306 value.getContent().add(jsonPolicy);
308 // Create our AttributeAssignmentExpression where we will
309 // store the contents of the policy in JSON format.
311 AttributeAssignmentExpressionType expressionType = new AttributeAssignmentExpressionType();
312 expressionType.setAttributeId(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS.stringValue());
313 ObjectFactory factory = new ObjectFactory();
314 expressionType.setExpression(factory.createAttributeValue(value));
316 // Create an ObligationExpression for it
318 ObligationExpressionType obligation = new ObligationExpressionType();
319 obligation.setFulfillOn(EffectType.PERMIT);
320 obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
321 obligation.getAttributeAssignmentExpression().add(expressionType);
323 // Now we can add it into the rule
325 ObligationExpressionsType obligations = new ObligationExpressionsType();
326 obligations.getObligationExpression().add(obligation);
327 rule.setObligationExpressions(obligations);