7551f7e3dc6b88973063b030aa17ff0a3beb36b9
[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.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;
48 import java.util.Map;
49 import java.util.Map.Entry;
50 import lombok.Setter;
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;
82
83 /**
84  * This standard matchable translator uses Policy Types that contain "matchable" field in order
85  * to translate policies.
86  *
87  * @author pameladragosh
88  *
89  */
90 public class StdMatchableTranslator implements ToscaPolicyTranslator {
91
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();
95
96     private final Map<ToscaPolicyTypeIdentifier, ToscaPolicyType> matchablePolicyTypes = new HashMap<>();
97     @Setter
98     private RestServerParameters apiRestParameters;
99     @Setter
100     private Path pathForData;
101
102     public StdMatchableTranslator() {
103         super();
104     }
105
106     @Override
107     public Request convertRequest(DecisionRequest request) {
108         LOGGER.info("Converting Request {}", request);
109         try {
110             return StdMatchablePolicyRequest.createInstance(request);
111         } catch (XacmlApplicationException e) {
112             LOGGER.error("Failed to convert DecisionRequest: {}", e);
113         }
114         //
115         // TODO throw exception
116         //
117         return null;
118     }
119
120     @Override
121     public DecisionResponse convertResponse(Response xacmlResponse) {
122         LOGGER.info("Converting Response {}", xacmlResponse);
123         DecisionResponse decisionResponse = new DecisionResponse();
124         //
125         // Setup policies
126         //
127         decisionResponse.setPolicies(new HashMap<>());
128         //
129         // Iterate through all the results
130         //
131         for (Result xacmlResult : xacmlResponse.getResults()) {
132             //
133             // Check the result
134             //
135             if (xacmlResult.getDecision() == Decision.PERMIT) {
136                 //
137                 // Go through obligations
138                 //
139                 scanObligations(xacmlResult.getObligations(), decisionResponse);
140             }
141             if (xacmlResult.getDecision() == Decision.DENY
142                     || xacmlResult.getDecision() == Decision.INDETERMINATE) {
143                 //
144                 // TODO we have to return an ErrorResponse object instead
145                 //
146                 decisionResponse.setStatus("A better error message");
147             }
148         }
149
150         return decisionResponse;
151     }
152
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);
158                 //
159                 // We care about the content attribute
160                 //
161                 if (! ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_CONTENTS
162                         .equals(assignment.getAttributeId())) {
163                     //
164                     // If its not there, move on
165                     //
166                     continue;
167                 }
168                 //
169                 // The contents are in Json form
170                 //
171                 Object stringContents = assignment.getAttributeValue().getValue();
172                 if (LOGGER.isInfoEnabled()) {
173                     LOGGER.info("Policy contents: {}{}", System.lineSeparator(), stringContents);
174                 }
175                 //
176                 // Let's parse it into a map using Gson
177                 //
178                 Gson gson = new Gson();
179                 @SuppressWarnings("unchecked")
180                 Map<String, Object> result = gson.fromJson(stringContents.toString() ,Map.class);
181                 //
182                 // Find the metadata section
183                 //
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);
188                 } else {
189                     LOGGER.error("Missing metadata section in policy contained in obligation.");
190                 }
191             }
192         }
193
194     }
195
196     @Override
197     public PolicyType convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
198         //
199         // Get the TOSCA Policy Type for this policy
200         //
201         Collection<ToscaPolicyType> policyTypes = this.getPolicyTypes(toscaPolicy.getTypeIdentifier());
202         //
203         // If we don't have any policy types, then we cannot know
204         // which properties are matchable.
205         //
206         if (policyTypes.isEmpty()) {
207             throw new ToscaPolicyConversionException(
208                     "Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
209         }
210         //
211         // Policy name should be at the root
212         //
213         String policyName = toscaPolicy.getMetadata().get(POLICY_ID);
214         //
215         // Set it as the policy ID
216         //
217         PolicyType newPolicyType = new PolicyType();
218         newPolicyType.setPolicyId(policyName);
219         //
220         // Optional description
221         //
222         newPolicyType.setDescription(toscaPolicy.getDescription());
223         //
224         // There should be a metadata section
225         //
226         this.fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
227         //
228         // Set the combining rule
229         //
230         newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
231         //
232         // Generate the TargetType
233         //
234         newPolicyType.setTarget(generateTargetType(toscaPolicy.getProperties(), policyTypes));
235         //
236         // Now create the Permit Rule
237         // No target since the policy has a target
238         // With obligations.
239         //
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());
245         //
246         // Now represent the policy as Json
247         //
248         StandardCoder coder = new StandardCoder();
249         String jsonPolicy;
250         try {
251             jsonPolicy = coder.encode(toscaPolicy);
252         } catch (CoderException e) {
253             throw new ToscaPolicyConversionException("Failed to encode policy to json", e);
254         }
255         addObligation(rule, jsonPolicy);
256         //
257         // Add the rule to the policy
258         //
259         newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
260         //
261         // Return our new policy
262         //
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);
268         }
269         return newPolicyType;
270     }
271
272     /**
273      * From the TOSCA metadata section, pull in values that are needed into the XACML policy.
274      *
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
279      */
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");
284         } else {
285             //
286             // Do nothing here - the XACML PolicyId is used from TOSCA Policy Name field
287             //
288         }
289         if (! map.containsKey("policy-version")) {
290             throw new ToscaPolicyConversionException(policy.getPolicyId() + " missing metadata policy-version");
291         } else {
292             //
293             // Add in the Policy Version
294             //
295             policy.setVersion(map.get("policy-version"));
296         }
297         return policy;
298     }
299
300     /**
301      * For generating target type, we are scan for matchable properties
302      * and use those to build the policy.
303      *
304      * @param properties Properties section of policy
305      * @param policyTypes Collection of policy Type to find matchable metadata
306      * @return TargetType object
307      */
308     @SuppressWarnings("unchecked")
309     protected TargetType generateTargetType(Map<String, Object> properties, Collection<ToscaPolicyType> policyTypes) {
310         TargetType targetType = new TargetType();
311         //
312         // Iterate the properties
313         //
314         for (Entry<String, Object> entrySet : properties.entrySet()) {
315             //
316             // Find matchable properties
317             //
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);
325                     }
326                 } else {
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);
331                     }
332                 }
333             }
334         }
335
336         return targetType;
337     }
338
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) {
344                     continue;
345                 }
346                 for (Entry<String, String> entrySet : propertiesEntry.getValue().getMetadata().entrySet()) {
347                     if ("matchable".equals(entrySet.getKey()) && "true".equals(entrySet.getValue())) {
348                         return true;
349                     }
350                 }
351             }
352         }
353         return false;
354     }
355
356     protected AnyOfType generateMatches(Collection<Object> matchables, Identifier attributeId) {
357         //
358         // This is our outer AnyOf - which is an OR
359         //
360         AnyOfType anyOf = new AnyOfType();
361         for (Object matchable : matchables) {
362             //
363             // Default to string
364             //
365             Identifier idFunction = XACML3.ID_FUNCTION_STRING_EQUAL;
366             Identifier idDatatype = XACML3.ID_DATATYPE_STRING;
367             //
368             // See if we are another datatype
369             //
370             // TODO We should add datetime support. But to do that we need
371             // probably more metadata to describe how that would be translated.
372             //
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;
382             }
383             //
384             // Create a match for this
385             //
386             MatchType match = ToscaPolicyTranslatorUtils.buildMatchTypeDesignator(
387                     idFunction,
388                     matchable.toString(),
389                     idDatatype,
390                     attributeId,
391                     XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE);
392             //
393             // Now create an anyOf (OR)
394             //
395             anyOf.getAllOf().add(ToscaPolicyTranslatorUtils.buildAllOf(match));
396         }
397         return anyOf;
398     }
399
400     protected RuleType addObligation(RuleType rule, String jsonPolicy) {
401         //
402         // Convert the YAML Policy to JSON Object
403         //
404         if (LOGGER.isInfoEnabled()) {
405             LOGGER.info("JSON Optimization Policy {}{}", System.lineSeparator(), jsonPolicy);
406         }
407         //
408         // Create an AttributeValue for it
409         //
410         AttributeValueType value = new AttributeValueType();
411         value.setDataType(ToscaDictionary.ID_OBLIGATION_POLICY_MONITORING_DATATYPE.stringValue());
412         value.getContent().add(jsonPolicy);
413         //
414         // Create our AttributeAssignmentExpression where we will
415         // store the contents of the policy in JSON format.
416         //
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));
421         //
422         // Create an ObligationExpression for it
423         //
424         ObligationExpressionType obligation = new ObligationExpressionType();
425         obligation.setFulfillOn(EffectType.PERMIT);
426         obligation.setObligationId(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue());
427         obligation.getAttributeAssignmentExpression().add(expressionType);
428         //
429         // Now we can add it into the rule
430         //
431         ObligationExpressionsType obligations = new ObligationExpressionsType();
432         obligations.getObligationExpression().add(obligation);
433         rule.setObligationExpressions(obligations);
434         return rule;
435     }
436
437
438     /**
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.
441      *
442      *
443      * @param policyTypeId Policy Type Id
444      * @return A list of PolicyTypes
445      */
446     private List<ToscaPolicyType> getPolicyTypes(ToscaPolicyTypeIdentifier policyTypeId) {
447         //
448         // Create identifier from the policy
449         //
450         ToscaPolicyTypeIdentifier typeId = new ToscaPolicyTypeIdentifier(policyTypeId);
451         //
452         // Find the Policy Type
453         //
454         ToscaPolicyType policyType = findPolicyType(typeId);
455         if (policyType == null)  {
456             return Collections.emptyList();
457         }
458         //
459         // Create our return object
460         //
461         List<ToscaPolicyType> listTypes = new ArrayList<>();
462         listTypes.add(policyType);
463         //
464         // Look for parent policy types that could also contain matchable properties
465         //
466         ToscaPolicyType childPolicyType = policyType;
467         while (! childPolicyType.getDerivedFrom().startsWith("tosca.policies.Root")) {
468             //
469             // Create parent policy type id.
470             //
471             // We will have to assume the same version between child and the
472             // parent policy type it derives from.
473             //
474             // Or do we assume 1.0.0?
475             //
476             ToscaPolicyTypeIdentifier parentId = new ToscaPolicyTypeIdentifier(childPolicyType.getDerivedFrom(),
477                     "1.0.0");
478             //
479             // Find the policy type
480             //
481             ToscaPolicyType parentPolicyType = findPolicyType(parentId);
482             if (parentPolicyType == null) {
483                 //
484                 // Probably would be best to throw an exception and
485                 // return nothing back.
486                 //
487                 // But instead we will log a warning
488                 //
489                 LOGGER.warn("Missing parent policy type - proceeding anyway {}", parentId);
490                 //
491                 // Break the loop
492                 //
493                 break;
494             }
495             //
496             // Great save it
497             //
498             listTypes.add(parentPolicyType);
499             //
500             // Move to the next parent
501             //
502             childPolicyType = parentPolicyType;
503         }
504
505
506         return listTypes;
507     }
508
509     private ToscaPolicyType findPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
510         //
511         // Is it loaded in memory?
512         //
513         ToscaPolicyType policyType = this.matchablePolicyTypes.get(policyTypeId);
514         if (policyType == null)  {
515             //
516             // Load the policy
517             //
518             policyType = this.loadPolicyType(policyTypeId);
519         }
520         //
521         // Yep return it
522         //
523         return policyType;
524     }
525
526     private ToscaPolicyType loadPolicyType(ToscaPolicyTypeIdentifier policyTypeId) {
527         //
528         // Construct what the file name should be
529         //
530         Path policyTypePath = this.constructLocalFilePath(policyTypeId);
531         //
532         // See if it exists
533         //
534         byte[] bytes;
535         try {
536             //
537             // If it exists locally, read the bytes in
538             //
539             bytes = Files.readAllBytes(policyTypePath);
540         } catch (IOException e) {
541             //
542             // Does not exist locally, so let's GET it from the policy api
543             //
544             LOGGER.error("PolicyType not found in data area yet {}", policyTypePath, e);
545             //
546             // So let's pull it from API REST call and save it locally
547             //
548             return this.pullPolicyType(policyTypeId, policyTypePath);
549         }
550         LOGGER.info("Read in local policy type {}", policyTypePath.toAbsolutePath());
551         try {
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();
557             //
558             // Search for our Policy Type, there really only should be one but
559             // this is returned as a map.
560             //
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());
567                     //
568                     // Just simply return the policy type right here
569                     //
570                     return entryPolicyType;
571                 } else {
572                     LOGGER.warn("local policy type contains different name version {} {}", entryPolicyType.getName(),
573                             entryPolicyType.getVersion());
574                 }
575             }
576             //
577             // This would be an error, if the file stored does not match what its supposed to be
578             //
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);
582         }
583         //
584         // Hopefully we never get here
585         //
586         LOGGER.error("Failed to find/load policy type {}", policyTypeId);
587         return null;
588     }
589
590     private synchronized ToscaPolicyType pullPolicyType(ToscaPolicyTypeIdentifier policyTypeId, Path policyTypePath) {
591         //
592         // This is what we return
593         //
594         ToscaPolicyType policyType = null;
595         try {
596             PolicyApiCaller api = new PolicyApiCaller(this.apiRestParameters);
597
598             policyType = api.getPolicyType(policyTypeId);
599         } catch (PolicyApiException e) {
600             LOGGER.error("Failed to make API call", e);
601             LOGGER.error("parameters: {} ", this.apiRestParameters);
602             return null;
603         }
604         //
605         // Store it locally
606         //
607         try {
608             standardCoder.encode(policyTypePath.toFile(), policyType);
609         } catch (CoderException e) {
610             LOGGER.error("Failed to store {} locally to {}", policyTypeId, policyTypePath, e);
611         }
612         //
613         // Done return the policy type
614         //
615         return policyType;
616     }
617
618     private Path constructLocalFilePath(ToscaPolicyTypeIdentifier policyTypeId) {
619         return Paths.get(this.pathForData.toAbsolutePath().toString(), policyTypeId.getName() + "-"
620                 + policyTypeId.getVersion() + ".json");
621     }
622 }