e3d8757746e59f53ee68e736cc6104592d4e935d
[policy/xacml-pdp.git] /
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.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.google.gson.Gson;
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.AttributeAssignmentExpressionType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
43 import org.onap.policy.models.decisions.concepts.DecisionRequest;
44 import org.onap.policy.models.decisions.concepts.DecisionResponse;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
46 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
47 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
48 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
49 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public class StdBaseTranslator implements ToscaPolicyTranslator {
54     private static final Logger LOGGER = LoggerFactory.getLogger(StdBaseTranslator.class);
55     private static Gson gson = new Gson();
56
57     public static final String POLICY_ID = "policy-id";
58
59     @Override
60     public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
61         throw new ToscaPolicyConversionException("Please override converPolicy");
62     }
63
64     @Override
65     public Request convertRequest(DecisionRequest request) {
66         return null;
67     }
68
69     @Override
70     public DecisionResponse convertResponse(Response xacmlResponse) {
71         LOGGER.info("Converting Response {}", xacmlResponse);
72         DecisionResponse decisionResponse = new DecisionResponse();
73         //
74         // Setup policies
75         //
76         decisionResponse.setPolicies(new HashMap<>());
77         //
78         // Iterate through all the results
79         //
80         for (Result xacmlResult : xacmlResponse.getResults()) {
81             //
82             // Check the result
83             //
84             if (xacmlResult.getDecision() == Decision.PERMIT) {
85                 //
86                 // Go through obligations
87                 //
88                 scanObligations(xacmlResult.getObligations(), decisionResponse);
89             } else if (xacmlResult.getDecision() == Decision.DENY
90                     || xacmlResult.getDecision() == Decision.INDETERMINATE) {
91                 //
92                 // TODO we have to return an ErrorResponse object instead
93                 //
94                 decisionResponse.setStatus("A better error message");
95             }
96         }
97
98         return decisionResponse;
99     }
100
101     @SuppressWarnings("unchecked")
102     protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
103         for (Obligation obligation : obligations) {
104             LOGGER.info("Obligation: {}", obligation);
105             for (AttributeAssignment assignment : obligation.getAttributeAssignments()) {
106                 LOGGER.info("Attribute Assignment: {}", assignment);
107                 //
108                 // We care about the content attribute
109                 //
110                 if (ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
111                         .equals(assignment.getAttributeId())) {
112                     //
113                     // The contents are in Json form
114                     //
115                     Object stringContents = assignment.getAttributeValue().getValue();
116                     LOGGER.info("DCAE contents: {}{}", XacmlPolicyUtils.LINE_SEPARATOR, stringContents);
117                     //
118                     // Let's parse it into a map using Gson
119                     //
120                     Map<String, Object> result;
121                     result = gson.fromJson(stringContents.toString(), Map.class);
122                     //
123                     // Find the metadata section
124                     //
125                     Map<String, Object> metadata = (Map<String, Object>) result.get("metadata");
126                     if (metadata != null) {
127                         decisionResponse.getPolicies().put(metadata.get(POLICY_ID).toString(), result);
128                     } else {
129                         LOGGER.error("Missing metadata section in policy contained in obligation.");
130                     }
131                 }
132             }
133         }
134     }
135
136     /**
137      * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
138      *
139      * @param policy Policy Object to store the metadata
140      * @param map The Metadata TOSCA Map
141      * @return Same Policy Object
142      * @throws ToscaPolicyConversionException If there is something missing from the metadata
143      */
144     protected PolicyType fillMetadataSection(PolicyType policy,
145             Map<String, String> map) throws ToscaPolicyConversionException {
146         //
147         // Ensure the policy-id exists - we don't use it here. It
148         // is saved in the TOSCA Policy Name field.
149         //
150         if (! map.containsKey(POLICY_ID)) {
151             throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-id");
152         }
153         //
154         // Ensure the policy-version exists
155         //
156         if (! map.containsKey("policy-version")) {
157             throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
158         }
159         //
160         // Add in the Policy Version
161         //
162         policy.setVersion(map.get("policy-version"));
163         return policy;
164     }
165
166     protected RuleType addObligation(RuleType rule, String jsonPolicy) {
167         //
168         // Convert the YAML Policy to JSON Object
169         //
170         LOGGER.info("JSON Optimization Policy {}{}", XacmlPolicyUtils.LINE_SEPARATOR, jsonPolicy);
171         //
172         // Create an AttributeValue for it
173         //
174         AttributeValueType value = new AttributeValueType();
175         value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
176         value.getContent().add(jsonPolicy);
177         //
178         // Create our AttributeAssignmentExpression where we will
179         // store the contents of the policy in JSON format.
180         //
181         AttributeAssignmentExpressionType expressionType = new AttributeAssignmentExpressionType();
182         expressionType.setAttributeId(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS.stringValue());
183         ObjectFactory factory = new ObjectFactory();
184         expressionType.setExpression(factory.createAttributeValue(value));
185         //
186         // Create an ObligationExpression for it
187         //
188         ObligationExpressionType obligation = new ObligationExpressionType();
189         obligation.setFulfillOn(EffectType.PERMIT);
190         obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
191         obligation.getAttributeAssignmentExpression().add(expressionType);
192         //
193         // Now we can add it into the rule
194         //
195         ObligationExpressionsType obligations = new ObligationExpressionsType();
196         obligations.getObligationExpression().add(obligation);
197         rule.setObligationExpressions(obligations);
198         return rule;
199     }
200
201 }