2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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.
18 * ============LICENSE_END=========================================================
20 package org.onap.policy.xacml.util;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.util.Arrays;
27 import java.util.Iterator;
28 import java.util.List;
30 import javax.xml.bind.JAXBContext;
31 import javax.xml.bind.JAXBElement;
32 import javax.xml.bind.Unmarshaller;
33 import javax.xml.parsers.DocumentBuilder;
34 import javax.xml.parsers.DocumentBuilderFactory;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Element;
40 import org.w3c.dom.Node;
41 import org.w3c.dom.NodeList;
43 import org.onap.policy.common.logging.eelf.MessageCodes;
44 import org.onap.policy.common.logging.eelf.PolicyLogger;
46 import com.att.research.xacml.api.AttributeAssignment;
47 import com.att.research.xacml.std.IdentifierImpl;
48 import com.att.research.xacml.std.StdAttribute;
49 import com.att.research.xacml.std.StdAttributeAssignment;
50 import com.att.research.xacml.std.StdAttributeValue;
51 import com.att.research.xacml.std.StdMutableAdvice;
52 import com.att.research.xacml.std.StdMutableObligation;
53 import com.att.research.xacml.util.XACMLPolicyScanner.Callback;
54 import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeSelectorType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
75 * class XACMLPolicyScanner
77 * This class traverses the hierarchy of a XACML 3.0 policy. You can optionally pass a Callback class
78 * and override any desired methods to retrieve information from a policy.
82 public class XACMLPolicyScanner {
84 private static final Log logger = LogFactory.getLog(XACMLPolicyScanner.class);
85 private Object policyObject = null;
86 private Callback callback = null;
88 public XACMLPolicyScanner(Path filename, Callback callback) {
89 try (InputStream is = Files.newInputStream(filename)) {
90 this.policyObject = XACMLPolicyScanner.readPolicy(is);
91 } catch (IOException e) {
92 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy");
94 this.callback = callback;
97 public XACMLPolicyScanner(InputStream filename, Callback callback) {
98 try (InputStream is = filename) {
99 this.policyObject = XACMLPolicyScanner.readPolicy(is);
100 } catch (IOException e) {
101 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy");
103 this.callback = callback;
106 public XACMLPolicyScanner(PolicySetType policySet, Callback callback) {
107 this.policyObject = policySet;
108 this.callback = callback;
111 public XACMLPolicyScanner(PolicySetType policySet) {
112 this(policySet, null);
115 public XACMLPolicyScanner(PolicyType policy, Callback callback) {
116 this.policyObject = policy;
117 this.callback = callback;
120 public XACMLPolicyScanner(PolicyType policy) {
125 * Sets the callback interface to be used.
129 public void setCallback(Callback cb) {
134 * Saves the given callback object then calls the scan() method.
139 public Object scan(Callback cb) {
146 * This begins the scanning of the contained object.
148 * @return - The PolicySet/Policy that was scanned.
150 public Object scan() {
151 if (this.policyObject == null) {
154 if (this.callback != null && this.callback.onBeginScan(this.policyObject) == CallbackResult.STOP) {
155 return this.policyObject;
157 if (this.policyObject instanceof PolicyType) {
158 this.scanPolicy(null, (PolicyType) this.policyObject);
159 } else if (this.policyObject instanceof PolicySetType) {
160 this.scanPolicySet(null, (PolicySetType) this.policyObject);
162 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + "Unknown class type: " + this.policyObject.getClass().getCanonicalName());
164 if (this.callback != null) {
165 this.callback.onFinishScan(this.policyObject);
167 return this.policyObject;
171 * This performs the scan of a PolicySet
173 * @param parent - Its parent PolicySet. Can be null if this is the root.
174 * @param policySet - The PolicySet object.
175 * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
182 protected CallbackResult scanPolicySet(PolicySetType parent, PolicySetType policySet) {
183 if (logger.isTraceEnabled()) {
184 logger.trace("scanning policy set: " + policySet.getPolicySetId() + " " + policySet.getDescription());
186 if (this.callback != null && this.callback.onPreVisitPolicySet(parent, policySet) == CallbackResult.STOP) {
187 return CallbackResult.STOP;
192 if (this.scanTarget(policySet, policySet.getTarget()) == CallbackResult.STOP) {
193 return CallbackResult.STOP;
195 if (this.scanObligations(policySet, policySet.getObligationExpressions()) == CallbackResult.STOP) {
196 return CallbackResult.STOP;
198 if (this.scanAdvice(policySet, policySet.getAdviceExpressions()) == CallbackResult.STOP) {
199 return CallbackResult.STOP;
202 // Iterate the policy sets and/or policies
204 List<JAXBElement<?>> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference();
205 for (JAXBElement<?> element: list) {
206 if ("PolicySet".equals(element.getName().getLocalPart()) &&
207 this.scanPolicySet(policySet, (PolicySetType)element.getValue()) == CallbackResult.STOP) {
208 return CallbackResult.STOP;
209 } else if ("Policy".equals(element.getName().getLocalPart()) &&
210 this.scanPolicy(policySet, (PolicyType)element.getValue()) == CallbackResult.STOP) {
211 return CallbackResult.STOP;
213 logger.warn("generating policy sets found unsupported element: " + element.getName().getNamespaceURI());
216 if (this.callback != null && this.callback.onPostVisitPolicySet(parent, policySet) == CallbackResult.STOP) {
217 return CallbackResult.STOP;
219 return CallbackResult.CONTINUE;
224 * This performs scanning of the Policy object.
226 * @param parent - The parent PolicySet of the policy. This can be null if this is a root Policy.
227 * @param policy - The policy being scanned.
228 * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
230 protected CallbackResult scanPolicy(PolicySetType parent, PolicyType policy) {
231 if (logger.isTraceEnabled()) {
232 logger.trace("scanning policy: " + policy.getPolicyId() + " " + policy.getDescription());
234 if (this.callback != null && this.callback.onPreVisitPolicy(parent, policy) == CallbackResult.STOP) {
235 return CallbackResult.STOP;
240 if (this.scanTarget(policy, policy.getTarget()) == CallbackResult.STOP) {
241 return CallbackResult.STOP;
243 if (this.scanVariables(policy, policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()) == CallbackResult.STOP) {
244 return CallbackResult.STOP;
246 if (this.scanObligations(policy, policy.getObligationExpressions()) == CallbackResult.STOP) {
247 return CallbackResult.STOP;
249 if (this.scanAdvice(policy, policy.getAdviceExpressions()) == CallbackResult.STOP) {
250 return CallbackResult.STOP;
255 List<Object> list = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition();
256 for (Object o: list) {
257 if (o instanceof RuleType) {
258 RuleType rule = (RuleType) o;
259 if (logger.isTraceEnabled()) {
260 logger.trace("scanning rule: " + rule.getRuleId() + " " + rule.getDescription());
262 if (this.callback != null && this.callback.onPreVisitRule(policy, rule) == CallbackResult.STOP) {
263 return CallbackResult.STOP;
265 if (this.scanTarget(rule, rule.getTarget()) == CallbackResult.STOP) {
266 return CallbackResult.STOP;
268 if (this.scanConditions(rule, rule.getCondition()) == CallbackResult.STOP) {
269 return CallbackResult.STOP;
271 if (this.scanObligations(rule, rule.getObligationExpressions()) == CallbackResult.STOP) {
272 return CallbackResult.STOP;
274 if (this.scanAdvice(rule, rule.getAdviceExpressions()) == CallbackResult.STOP) {
275 return CallbackResult.STOP;
277 if (this.callback != null && this.callback.onPostVisitRule(policy, rule) == CallbackResult.STOP) {
278 return CallbackResult.STOP;
280 } else if (o instanceof VariableDefinitionType) {
281 if (this.callback != null && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) {
282 return CallbackResult.STOP;
285 if (logger.isDebugEnabled()) {
286 logger.debug("scanning policy rules found unsupported object:" + o.toString());
290 if (this.callback != null && this.callback.onPostVisitPolicy(parent, policy) == CallbackResult.STOP) {
291 return CallbackResult.STOP;
293 return CallbackResult.CONTINUE;
297 * Scans the given target for attributes. Its sole purpose is to return attributes found.
299 * @param parent - The parent PolicySet/Policy/Rule for the target.
300 * @param target - The target.
301 * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
303 protected CallbackResult scanTarget(Object parent, TargetType target) {
304 if (target == null) {
305 return CallbackResult.CONTINUE;
307 List<AnyOfType> anyOfList = target.getAnyOf();
308 if (anyOfList != null) {
309 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
310 while (iterAnyOf.hasNext()) {
311 AnyOfType anyOf = iterAnyOf.next();
312 List<AllOfType> allOfList = anyOf.getAllOf();
313 if (allOfList != null) {
314 Iterator<AllOfType> iterAllOf = allOfList.iterator();
315 while (iterAllOf.hasNext()) {
316 AllOfType allOf = iterAllOf.next();
317 List<MatchType> matchList = allOf.getMatch();
318 if (matchList != null) {
319 Iterator<MatchType> iterMatch = matchList.iterator();
320 while (iterMatch.hasNext()) {
321 MatchType match = iterMatch.next();
323 // Finally down to the actual attribute
325 StdAttribute attribute = null;
326 AttributeValueType value = match.getAttributeValue();
327 if (match.getAttributeDesignator() != null && value != null) {
328 AttributeDesignatorType designator = match.getAttributeDesignator();
330 // The content may be tricky
332 attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()),
333 new IdentifierImpl(designator.getAttributeId()),
334 new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()),
335 designator.getIssuer(),
337 } else if (match.getAttributeSelector() != null && value != null) {
338 AttributeSelectorType selector = match.getAttributeSelector();
339 attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()),
340 new IdentifierImpl(selector.getContextSelectorId()),
341 new StdAttributeValue<List<?>>(new IdentifierImpl(value.getDataType()), value.getContent()),
345 logger.warn("NULL designator/selector or value for match.");
347 if (attribute != null && this.callback != null && this.callback.onAttribute(parent, target, attribute) == CallbackResult.STOP) {
348 return CallbackResult.STOP;
356 return CallbackResult.CONTINUE;
360 * Scan the list of obligations.
362 * @param parent - The parent PolicySet/Policy/Rule for the obligation.
363 * @param obligationExpressionsType - All the obligation expressions.
364 * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
366 protected CallbackResult scanObligations(Object parent, ObligationExpressionsType obligationExpressionsType) {
367 if (obligationExpressionsType == null) {
368 return CallbackResult.CONTINUE;
370 List<ObligationExpressionType> expressions = obligationExpressionsType.getObligationExpression();
371 if (expressions == null || expressions.isEmpty()) {
372 return CallbackResult.CONTINUE;
374 for (ObligationExpressionType expression : expressions) {
375 StdMutableObligation ob = new StdMutableObligation(new IdentifierImpl(expression.getObligationId()));
376 List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression();
377 if (assignments != null) {
378 for (AttributeAssignmentExpressionType assignment : assignments) {
379 // category is optional and may be null
380 IdentifierImpl categoryId = null;
381 if (assignment.getCategory() != null) {
382 categoryId = new IdentifierImpl(assignment.getCategory());
384 AttributeAssignment attribute = new StdAttributeAssignment(
386 new IdentifierImpl(assignment.getAttributeId()),
387 assignment.getIssuer(),
388 new StdAttributeValue<Object>(null, null)
390 ob.addAttributeAssignment(attribute);
393 if (this.callback != null && this.callback.onObligation(parent, expression, ob) == CallbackResult.STOP) {
394 return CallbackResult.STOP;
397 return CallbackResult.CONTINUE;
402 * Scans the list of advice expressions returning each individually.
404 * @param parent - The parent PolicySet/Policy/Rule for the advice.
405 * @param adviceExpressionstype - The list of advice expressions.
406 * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
408 protected CallbackResult scanAdvice(Object parent, AdviceExpressionsType adviceExpressionstype) {
409 if (adviceExpressionstype == null) {
410 return CallbackResult.CONTINUE;
412 List<AdviceExpressionType> expressions = adviceExpressionstype.getAdviceExpression();
413 if (expressions == null || expressions.isEmpty()) {
414 return CallbackResult.CONTINUE;
416 for (AdviceExpressionType expression : expressions) {
417 StdMutableAdvice ob = new StdMutableAdvice(new IdentifierImpl(expression.getAdviceId()));
418 List<AttributeAssignmentExpressionType> assignments = expression.getAttributeAssignmentExpression();
419 if (assignments != null) {
420 for (AttributeAssignmentExpressionType assignment : assignments) {
421 IdentifierImpl categoryId = null;
422 if (assignment.getCategory() != null) {
423 categoryId = new IdentifierImpl(assignment.getCategory());
425 AttributeAssignment attribute = new StdAttributeAssignment(
427 new IdentifierImpl(assignment.getAttributeId()),
428 assignment.getIssuer(),
429 new StdAttributeValue<Object>(null, null)
431 ob.addAttributeAssignment(attribute);
434 if (this.callback != null && this.callback.onAdvice(parent, expression, ob) == CallbackResult.STOP) {
435 return CallbackResult.STOP;
438 return CallbackResult.CONTINUE;
442 * Scans the list of variable definitions.
444 * @param policy - Policy object containing the variable definition.
445 * @param list - List of variable definitions.
446 * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning.
448 protected CallbackResult scanVariables(PolicyType policy, List<Object> list) {
450 return CallbackResult.CONTINUE;
452 for (Object o : list) {
453 if (o instanceof VariableDefinitionType && this.callback != null && this.callback.onVariable(policy, (VariableDefinitionType) o) == CallbackResult.STOP) {
454 return CallbackResult.STOP;
458 return CallbackResult.CONTINUE;
462 * Scans the list of conditions.
468 protected CallbackResult scanConditions(RuleType rule, ConditionType condition) {
469 if (condition != null && this.callback != null && this.callback.onCondition(rule, condition) == CallbackResult.STOP) {
470 return CallbackResult.STOP;
472 return CallbackResult.CONTINUE;
476 * Reads the XACML XML policy file in and returns the version contained in the root Policy/PolicySet element.
478 * @param policy - The policy file.
479 * @return - The version string from the file (uninterpreted)
480 * @throws IOException
482 public static String getVersion(Path policy) throws IOException {
484 try (InputStream is = Files.newInputStream(policy)) {
485 data = XACMLPolicyScanner.readPolicy(is);
486 } catch (IOException e) {
487 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Failed to read policy");
491 logger.warn("Version is null.");
494 return getVersion(data);
498 * Reads the Policy/PolicySet element object and returns its current version.
500 * @param data - Either a PolicySet or Policy XACML type object.
501 * @return - The integer version value. -1 if it doesn't exist or was un-parsable.
503 public static String getVersion(Object data) {
504 String version = null;
506 if (data instanceof PolicySetType) {
507 version = ((PolicySetType)data).getVersion();
508 } else if (data instanceof PolicyType) {
509 version = ((PolicyType)data).getVersion();
512 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName());
516 if (version != null && version.length() > 0) {
519 logger.warn("No version set in policy");
521 } catch (NumberFormatException e) {
522 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPolicyScanner", "Invalid version contained in policy: " + version);
529 * Returns the Policy or PolicySet ID.
531 * @param data - A XACML 3.0 Policy or PolicySet element object.
532 * @return The policy/policyset's policy ID
534 public static String getID(Object data) {
535 if (data instanceof PolicySetType) {
536 return ((PolicySetType)data).getPolicySetId();
537 } else if (data instanceof PolicyType) {
538 return ((PolicyType)data).getPolicyId();
540 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Expecting a PolicySet/Policy/Rule object. Got: " + data.getClass().getCanonicalName());
545 public static List<String> getCreatedByModifiedBy(Path policyPath) throws IOException{
546 String createdBy = "";
547 String modifiedBy= "";
548 String cValue = "@CreatedBy:";
549 String mValue = "@ModifiedBy:";
550 for(String line: Files.readAllLines(policyPath)){
551 line = line.replaceAll("\\s+", "");
555 if(line.contains("<Description>") && line.contains(cValue) && line.contains(mValue)){
556 createdBy = line.substring(line.indexOf(cValue) + cValue.length(), line.lastIndexOf(cValue));
557 modifiedBy = line.substring(line.indexOf(mValue) + mValue.length(), line.lastIndexOf(mValue));
561 return Arrays.asList(createdBy, modifiedBy);
564 //get the Created Name of the User on reading the Xml file
565 public static String getCreatedBy(Path policyPath) throws IOException{
567 String value = "@CreatedBy:";
568 for(String line: Files.readAllLines(policyPath)){
569 line = line.replaceAll("\\s+", "");
573 if(line.contains("<Description>") && line.contains(value)){
574 userId = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value));
581 //get the Modified Name of the User on reading the Xml file
582 public static String getModifiedBy(Path policyPath) throws IOException{
583 String modifiedBy = "";
584 String value = "@ModifiedBy:";
585 for(String line: Files.readAllLines(policyPath)){
586 line = line.replaceAll("\\s+", "");
590 if(line.contains("<Description>") && line.contains(value)){
591 modifiedBy = line.substring(line.indexOf(value) + value.length(), line.lastIndexOf(value));
599 * readPolicy - does the work to read in policy data from a file.
601 * @param policy - The path to the policy file.
602 * @return - The policy data object. This *should* be either a PolicySet or a Policy.
604 public static Object readPolicy(InputStream is) {
607 // Create a DOM parser
609 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
610 dbf.setNamespaceAware(true);
611 DocumentBuilder db = dbf.newDocumentBuilder();
613 // Parse the policy file
615 Document doc = db.parse(is);
616 Element e = doc.getDocumentElement();
618 // Is it a 3.0 policy?
620 if ("urn:oasis:names:tc:xacml:3.0:core:schema:wd-17".equals(e.getNamespaceURI())) {
622 // A policyset or policy could be the root
624 if (e.getNodeName().endsWith("Policy")) {
626 // Now we can create the context for the policy set
627 // and unmarshall the policy into a class.
629 JAXBContext context = JAXBContext.newInstance(PolicyType.class);
630 Unmarshaller um = context.createUnmarshaller();
631 JAXBElement<PolicyType> root = um.unmarshal(e, PolicyType.class);
633 // Here is our policy set class
635 return root.getValue();
636 } else if (e.getNodeName().endsWith("PolicySet")) {
638 // Now we can create the context for the policy set
639 // and unmarshall the policy into a class.
641 JAXBContext context = JAXBContext.newInstance(PolicySetType.class);
642 Unmarshaller um = context.createUnmarshaller();
643 JAXBElement<PolicySetType> root = um.unmarshal(e, PolicySetType.class);
645 // Here is our policy set class
647 return root.getValue();
649 if (logger.isDebugEnabled()) {
650 logger.debug("Not supported yet: " + e.getNodeName());
654 logger.warn("unsupported namespace: " + e.getNamespaceURI());
656 } catch (Exception e) {
657 PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPolicyScanner", "Exception in readPolicy");
663 * @return the policyObject
665 public Object getPolicyObject() {