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.Decision;
27 import com.att.research.xacml.api.Identifier;
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.IdentifierImpl;
34 import com.att.research.xacml.util.XACMLPolicyWriter;
35 import com.google.gson.Gson;
36 import java.io.ByteArrayOutputStream;
37 import java.io.IOException;
38 import java.nio.charset.StandardCharsets;
39 import java.nio.file.Files;
40 import java.nio.file.Path;
41 import java.nio.file.Paths;
42 import java.util.ArrayList;
43 import java.util.Arrays;
44 import java.util.Collection;
45 import java.util.Collections;
46 import java.util.HashMap;
47 import java.util.List;
49 import java.util.Map.Entry;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
62 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
63 import org.onap.policy.common.utils.coder.CoderException;
64 import org.onap.policy.common.utils.coder.StandardCoder;
65 import org.onap.policy.models.decisions.concepts.DecisionRequest;
66 import org.onap.policy.models.decisions.concepts.DecisionResponse;
67 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
68 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
69 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier;
70 import org.onap.policy.models.tosca.authorative.concepts.ToscaProperty;
71 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
72 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
73 import org.onap.policy.pdp.xacml.application.common.PolicyApiCaller;
74 import org.onap.policy.pdp.xacml.application.common.PolicyApiException;
75 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
76 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
77 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
78 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslatorUtils;
79 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 * This standard matchable translator uses Policy Types that contain "matchable" field in order
85 * to translate policies.
87 * @author pameladragosh
90 public class StdMatchableTranslator implements ToscaPolicyTranslator {
92 private static final Logger LOGGER = LoggerFactory.getLogger(StdMatchableTranslator.class);
93 private static final String POLICY_ID = "policy-id";
94 private static final StandardCoder standardCoder = new StandardCoder();
96 private final Map<ToscaPolicyTypeIdentifier, ToscaPolicyType> matchablePolicyTypes = new HashMap<>();
98 private RestServerParameters apiRestParameters;
100 private Path pathForData;
102 public StdMatchableTranslator() {
107 public Request convertRequest(DecisionRequest request) {
108 LOGGER.info("Converting Request {}", request);
110 return StdMatchablePolicyRequest.createInstance(request);
111 } catch (XacmlApplicationException e) {
112 LOGGER.error("Failed to convert DecisionRequest: {}", e);
115 // TODO throw exception
121 public DecisionResponse convertResponse(Response xacmlResponse) {
122 LOGGER.info("Converting Response {}", xacmlResponse);
123 DecisionResponse decisionResponse = new DecisionResponse();
127 decisionResponse.setPolicies(new HashMap<>());
129 // Iterate through all the results
131 for (Result xacmlResult : xacmlResponse.getResults()) {
135 if (xacmlResult.getDecision() == Decision.PERMIT) {
137 // Go through obligations
139 scanObligations(xacmlResult.getObligations(), decisionResponse);
141 if (xacmlResult.getDecision() == Decision.DENY
142 || xacmlResult.getDecision() == Decision.INDETERMINATE) {
144 // TODO we have to return an ErrorResponse object instead
146 decisionResponse.setStatus("A better error message");
150 return decisionResponse;
153 protected void scanObligations(Collection<Obligation> obligations, DecisionResponse decisionResponse) {
154 for (Obligation obligation : obligations) {
155 LOGGER.info("Obligation: {}", obligation);
156 for (AttributeAssignment assignment : obligation.getAttributeAssignments()) {
157 LOGGER.info("Attribute Assignment: {}", assignment);
159 // We care about the content attribute
161 if (! ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
162 .equals(assignment.getAttributeId())) {
164 // If its not there, move on
169 // The contents are in Json form
171 Object stringContents = assignment.getAttributeValue().getValue();
172 if (LOGGER.isInfoEnabled()) {
173 LOGGER.info("Policy contents: {}{}", System.lineSeparator(), stringContents);
176 // Let's parse it into a map using Gson
178 Gson gson = new Gson();
179 @SuppressWarnings("unchecked")
180 Map<String, Object> result = gson.fromJson(stringContents.toString() ,Map.class);
182 // Find the metadata section
184 @SuppressWarnings("unchecked")
185 Map<String, Object> metadata = (Map<String, Object>) result.get("metadata");
186 if (metadata != null) {
187 decisionResponse.getPolicies().put(metadata.get(POLICY_ID).toString(), result);
189 LOGGER.error("Missing metadata section in policy contained in obligation.");
197 public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
199 // Get the TOSCA Policy Type for this policy
201 Collection<ToscaPolicyType> policyTypes = this.getPolicyTypes(toscaPolicy.getTypeIdentifier());
203 // If we don't have any policy types, then we cannot know
204 // which properties are matchable.
206 if (policyTypes.isEmpty()) {
207 throw new ToscaPolicyConversionException(
208 "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
211 // Policy name should be at the root
213 String policyName = toscaPolicy.getMetadata().get(POLICY_ID);
215 // Set it as the policy ID
217 PolicyType newPolicyType = new PolicyType();
218 newPolicyType.setPolicyId(policyName);
220 // Optional description
222 newPolicyType.setDescription(toscaPolicy.getDescription());
224 // There should be a metadata section
226 this.fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
228 // Set the combining rule
230 newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
232 // Generate the TargetType
234 newPolicyType.setTarget(generateTargetType(toscaPolicy.getProperties(), policyTypes));
236 // Now create the Permit Rule
237 // No target since the policy has a target
240 RuleType rule = new RuleType();
241 rule.setDescription("Default is to PERMIT if the policy matches.");
242 rule.setRuleId(policyName + ":rule");
243 rule.setEffect(EffectType.PERMIT);
244 rule.setTarget(new TargetType());
246 // Now represent the policy as Json
248 StandardCoder coder = new StandardCoder();
251 jsonPolicy = coder.encode(toscaPolicy);
252 } catch (CoderException e) {
253 throw new ToscaPolicyConversionException("Failed to encode policy to json", e);
255 addObligation(rule, jsonPolicy);
257 // Add the rule to the policy
259 newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
261 // Return our new policy
263 try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
264 XACMLPolicyWriter.writePolicyFile(os, newPolicyType);
265 LOGGER.info("{}", os);
266 } catch (IOException e) {
267 LOGGER.error("Failed to create byte array stream", e);
269 return newPolicyType;
273 * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
275 * @param policy Policy Object to store the metadata
276 * @param map The Metadata TOSCA Map
277 * @return Same Policy Object
278 * @throws ToscaPolicyConversionException If there is something missing from the metadata
280 protected PolicyType fillMetadataSection(PolicyType policy,
281 Map<String, String> map) throws ToscaPolicyConversionException {
282 if (! map.containsKey(POLICY_ID)) {
283 throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-id");
286 // Do nothing here - the XACML PolicyId is used from TOSCA Policy Name field
289 if (! map.containsKey("policy-version")) {
290 throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
293 // Add in the Policy Version
295 policy.setVersion(map.get("policy-version"));
301 * For generating target type, we are scan for matchable properties
302 * and use those to build the policy.
304 * @param properties Properties section of policy
305 * @param policyTypes Collection of policy Type to find matchable metadata
306 * @return TargetType object
308 @SuppressWarnings("unchecked")
309 protected TargetType generateTargetType(Map<String, Object> properties, Collection<ToscaPolicyType> policyTypes) {
310 TargetType targetType = new TargetType();
312 // Iterate the properties
314 for (Entry<String, Object> entrySet : properties.entrySet()) {
316 // Find matchable properties
318 if (isMatchable(entrySet.getKey(), policyTypes)) {
319 LOGGER.info("Found matchable property {}", entrySet.getValue());
320 if (entrySet.getValue() instanceof Collection) {
321 AnyOfType anyOf = generateMatches((Collection<Object>) entrySet.getValue(),
322 new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + entrySet.getKey()));
323 if (! anyOf.getAllOf().isEmpty()) {
324 targetType.getAnyOf().add(anyOf);
327 AnyOfType anyOf = generateMatches(Arrays.asList(entrySet.getValue()),
328 new IdentifierImpl(ToscaDictionary.ID_RESOURCE_MATCHABLE + entrySet.getKey()));
329 if (! anyOf.getAllOf().isEmpty()) {
330 targetType.getAnyOf().add(anyOf);
339 protected boolean isMatchable(String propertyName, Collection<ToscaPolicyType> policyTypes) {
340 for (ToscaPolicyType policyType : policyTypes) {
341 for (Entry<String, ToscaProperty> propertiesEntry : policyType.getProperties().entrySet()) {
342 if (! propertiesEntry.getKey().equals(propertyName)
343 || propertiesEntry.getValue().getMetadata() == null) {
346 for (Entry<String, String> entrySet : propertiesEntry.getValue().getMetadata().entrySet()) {
347 if ("matchable".equals(entrySet.getKey()) && "true".equals(entrySet.getValue())) {
356 protected AnyOfType generateMatches(Collection<Object> matchables, Identifier attributeId) {
358 // This is our outer AnyOf - which is an OR
360 AnyOfType anyOf = new AnyOfType();
361 for (Object matchable : matchables) {
365 Identifier idFunction = XACML3.ID_FUNCTION_STRING_EQUAL;
366 Identifier idDatatype = XACML3.ID_DATATYPE_STRING;
368 // See if we are another datatype
370 // TODO We should add datetime support. But to do that we need
371 // probably more metadata to describe how that would be translated.
373 if (matchable instanceof Integer) {
374 idFunction = XACML3.ID_FUNCTION_INTEGER_EQUAL;
375 idDatatype = XACML3.ID_DATATYPE_INTEGER;
376 } else if (matchable instanceof Double) {
377 idFunction = XACML3.ID_FUNCTION_DOUBLE_EQUAL;
378 idDatatype = XACML3.ID_DATATYPE_DOUBLE;
379 } else if (matchable instanceof Boolean) {
380 idFunction = XACML3.ID_FUNCTION_BOOLEAN_EQUAL;
381 idDatatype = XACML3.ID_DATATYPE_BOOLEAN;
384 // Create a match for this
386 MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
388 matchable.toString(),
391 XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
393 // Now create an anyOf (OR)
395 anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(match));
400 protected RuleType addObligation(RuleType rule, String jsonPolicy) {
402 // Convert the YAML Policy to JSON Object
404 if (LOGGER.isInfoEnabled()) {
405 LOGGER.info("JSON Optimization Policy {}{}", System.lineSeparator(), jsonPolicy);
408 // Create an AttributeValue for it
410 AttributeValueType value = new AttributeValueType();
411 value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
412 value.getContent().add(jsonPolicy);
414 // Create our AttributeAssignmentExpression where we will
415 // store the contents of the policy in JSON format.
417 AttributeAssignmentExpressionType expressionType = new AttributeAssignmentExpressionType();
418 expressionType.setAttributeId(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS.stringValue());
419 ObjectFactory factory = new ObjectFactory();
420 expressionType.setExpression(factory.createAttributeValue(value));
422 // Create an ObligationExpression for it
424 ObligationExpressionType obligation = new ObligationExpressionType();
425 obligation.setFulfillOn(EffectType.PERMIT);
426 obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
427 obligation.getAttributeAssignmentExpression().add(expressionType);
429 // Now we can add it into the rule
431 ObligationExpressionsType obligations = new ObligationExpressionsType();
432 obligations.getObligationExpression().add(obligation);
433 rule.setObligationExpressions(obligations);
439 * Get Policy Type definitions. This could be previously loaded, or could be
440 * stored in application path, or may need to be pulled from the API.
443 * @param policyTypeId Policy Type Id
444 * @return A list of PolicyTypes
446 private List<ToscaPolicyType> getPolicyTypes(ToscaPolicyTypeIdentifier policyTypeId) {
448 // Create identifier from the policy
450 ToscaPolicyTypeIdentifier typeId = new ToscaPolicyTypeIdentifier(policyTypeId);
452 // Find the Policy Type
454 ToscaPolicyType policyType = findPolicyType(typeId);
455 if (policyType == null) {
456 return Collections.emptyList();
459 // Create our return object
461 List<ToscaPolicyType> listTypes = new ArrayList<>();
462 listTypes.add(policyType);
464 // Look for parent policy types that could also contain matchable properties
466 ToscaPolicyType childPolicyType = policyType;
467 while (! childPolicyType.getDerivedFrom().startsWith("tosca.policies.Root")) {
469 // Create parent policy type id.
471 // We will have to assume the same version between child and the
472 // parent policy type it derives from.
474 // Or do we assume 1.0.0?
476 ToscaPolicyTypeIdentifier parentId = new ToscaPolicyTypeIdentifier(childPolicyType.getDerivedFrom(),
479 // Find the policy type
481 ToscaPolicyType parentPolicyType = findPolicyType(parentId);
482 if (parentPolicyType == null) {
484 // Probably would be best to throw an exception and
485 // return nothing back.
487 // But instead we will log a warning
489 LOGGER.warn("Missing parent policy type - proceeding anyway {}", parentId);
498 listTypes.add(parentPolicyType);
500 // Move to the next parent
502 childPolicyType = parentPolicyType;
509 private ToscaPolicyType findPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
511 // Is it loaded in memory?
513 ToscaPolicyType policyType = this.matchablePolicyTypes.get(policyTypeId);
514 if (policyType == null) {
518 policyType = this.loadPolicyType(policyTypeId);
526 private ToscaPolicyType loadPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
528 // Construct what the file name should be
530 Path policyTypePath = this.constructLocalFilePath(policyTypeId);
537 // If it exists locally, read the bytes in
539 bytes = Files.readAllBytes(policyTypePath);
540 } catch (IOException e) {
542 // Does not exist locally, so let's GET it from the policy api
544 LOGGER.error("PolicyType not found in data area yet {}", policyTypePath, e);
546 // So let's pull it from API REST call and save it locally
548 return this.pullPolicyType(policyTypeId, policyTypePath);
550 LOGGER.info("Read in local policy type {}", policyTypePath.toAbsolutePath());
552 ToscaServiceTemplate serviceTemplate = standardCoder.decode(new String(bytes, StandardCharsets.UTF_8),
553 ToscaServiceTemplate.class);
554 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
555 jtst.fromAuthorative(serviceTemplate);
556 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
558 // Search for our Policy Type, there really only should be one but
559 // this is returned as a map.
561 for ( Entry<String, ToscaPolicyType> entrySet : completedJtst.getPolicyTypes().entrySet()) {
562 ToscaPolicyType entryPolicyType = entrySet.getValue();
563 if (policyTypeId.getName().equals(entryPolicyType.getName())
564 && policyTypeId.getVersion().equals(entryPolicyType.getVersion())) {
565 LOGGER.info("Found existing local policy type {} {}", entryPolicyType.getName(),
566 entryPolicyType.getVersion());
568 // Just simply return the policy type right here
570 return entryPolicyType;
572 LOGGER.warn("local policy type contains different name version {} {}", entryPolicyType.getName(),
573 entryPolicyType.getVersion());
577 // This would be an error, if the file stored does not match what its supposed to be
579 LOGGER.error("Existing policy type file does not contain right name and version");
580 } catch (CoderException e) {
581 LOGGER.error("Failed to decode tosca template for {}", policyTypePath, e);
584 // Hopefully we never get here
586 LOGGER.error("Failed to find/load policy type {}", policyTypeId);
590 private synchronized ToscaPolicyType pullPolicyType(ToscaPolicyTypeIdentifier policyTypeId, Path policyTypePath) {
592 // This is what we return
594 ToscaPolicyType policyType = null;
596 PolicyApiCaller api = new PolicyApiCaller(this.apiRestParameters);
598 policyType = api.getPolicyType(policyTypeId);
599 } catch (PolicyApiException e) {
600 LOGGER.error("Failed to make API call", e);
601 LOGGER.error("parameters: {} ", this.apiRestParameters);
608 standardCoder.encode(policyTypePath.toFile(), policyType);
609 } catch (CoderException e) {
610 LOGGER.error("Failed to store {} locally to {}", policyTypeId, policyTypePath, e);
613 // Done return the policy type
618 private Path constructLocalFilePath(ToscaPolicyTypeIdentifier policyTypeId) {
619 return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
620 + policyTypeId.getVersion() + ".json");