Search in sources :

Example 1 with ToscaPolicyConversionException

use of org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException in project policy-xacml-pdp by onap.

the class StdMatchableTranslator method generateTargetType.

/**
 * For generating target type, we scan for matchable properties
 * and use those to build the policy.
 *
 * @param policy the policy
 * @param template template containing the policy
 * @return {@code Pair<TargetType, Integer>} Returns a TargetType and a Total Weight of matchables.
 */
protected Pair<TargetType, Integer> generateTargetType(ToscaPolicy policy, ToscaServiceTemplate template) {
    // 
    // Our return object
    // 
    var target = new TargetType();
    // 
    // See if we have a matchable in the cache already
    // 
    var matchablePolicyType = matchableCache.get(policy.getTypeIdentifier());
    // 
    if (matchablePolicyType == null) {
        // 
        // Our callback
        // 
        var myCallback = new MyMatchableCallback(this, template);
        // 
        // Create the matchable
        // 
        matchablePolicyType = new MatchablePolicyType(template.getPolicyTypes().get(policy.getType()), myCallback);
        // 
        // Cache it
        // 
        matchableCache.put(policy.getTypeIdentifier(), matchablePolicyType);
    }
    // 
    try {
        fillTargetTypeWithMatchables(target, matchablePolicyType, policy.getProperties());
    } catch (ToscaPolicyConversionException e) {
        LOGGER.error("Could not generate target type", e);
    }
    // 
    // There may be a case for default policies there is no weight - need to clean
    // up the target then else PDP will report bad policy missing AnyOf
    // 
    int weight = calculateWeight(target);
    LOGGER.debug("Weight is {} for policy {}", weight, policy.getName());
    // 
    return Pair.of(target, weight);
}
Also used : TargetType(oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType) MatchablePolicyType(org.onap.policy.pdp.xacml.application.common.matchable.MatchablePolicyType) ToscaPolicyConversionException(org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException)

Example 2 with ToscaPolicyConversionException

use of org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException in project policy-xacml-pdp by onap.

the class StdMatchableTranslator method convertPolicy.

@Override
public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException {
    // 
    // Get the TOSCA Policy Type for this policy
    // 
    ToscaServiceTemplate toscaPolicyTypeTemplate = this.findPolicyType(toscaPolicy.getTypeIdentifier());
    // 
    if (toscaPolicyTypeTemplate == null) {
        throw new ToscaPolicyConversionException("Cannot retrieve Policy Type definition for policy " + toscaPolicy.getName());
    }
    // 
    // Policy name should be at the root
    // 
    String policyName = String.valueOf(toscaPolicy.getMetadata().get(POLICY_ID));
    // 
    // Set it as the policy ID
    // 
    var newPolicyType = new PolicyType();
    newPolicyType.setPolicyId(policyName);
    // 
    // Optional description
    // 
    newPolicyType.setDescription(toscaPolicy.getDescription());
    // 
    // There should be a metadata section
    // 
    fillMetadataSection(newPolicyType, toscaPolicy.getMetadata());
    // 
    // Set the combining rule
    // 
    newPolicyType.setRuleCombiningAlgId(XACML3.ID_RULE_FIRST_APPLICABLE.stringValue());
    // 
    // Generate the TargetType - the policy should not be evaluated
    // unless all the matchable properties it cares about are matched.
    // 
    Pair<TargetType, Integer> pairGenerated = generateTargetType(toscaPolicy, toscaPolicyTypeTemplate);
    newPolicyType.setTarget(pairGenerated.getLeft());
    // 
    // Now represent the policy as Json
    // 
    var coder = new StandardCoder();
    String jsonPolicy;
    try {
        jsonPolicy = coder.encode(toscaPolicy);
    } catch (CoderException e) {
        throw new ToscaPolicyConversionException("Failed to encode policy to json", e);
    }
    // 
    // Add it as an obligation
    // 
    addObligation(newPolicyType, policyName, jsonPolicy, pairGenerated.getRight(), toscaPolicy.getType());
    // 
    // Now create the Permit Rule.
    // 
    var rule = new RuleType();
    rule.setDescription("Default is to PERMIT if the policy matches.");
    rule.setRuleId(policyName + ":rule");
    rule.setEffect(EffectType.PERMIT);
    rule.setTarget(new TargetType());
    // 
    // The rule contains the Condition which adds logic for
    // optional policy-type filtering.
    // 
    rule.setCondition(generateConditionForPolicyType(toscaPolicy.getType()));
    // 
    // Add the rule to the policy
    // 
    newPolicyType.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
    // 
    try (var os = new ByteArrayOutputStream()) {
        XACMLPolicyWriter.writePolicyFile(os, newPolicyType);
        LOGGER.info("{}", os);
    } catch (IOException e) {
        LOGGER.error("Failed to create byte array stream", e);
    }
    // 
    return newPolicyType;
}
Also used : ToscaPolicyType(org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType) MatchablePolicyType(org.onap.policy.pdp.xacml.application.common.matchable.MatchablePolicyType) PolicyType(oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType) StandardCoder(org.onap.policy.common.utils.coder.StandardCoder) RuleType(oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) JpaToscaServiceTemplate(org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate) ToscaServiceTemplate(org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate) TargetType(oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType) CoderException(org.onap.policy.common.utils.coder.CoderException) ToscaPolicyConversionException(org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException)

Example 3 with ToscaPolicyConversionException

use of org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException in project policy-xacml-pdp by onap.

the class StdXacmlApplicationServiceProvider method makeDecision.

@Override
public Pair<DecisionResponse, Response> makeDecision(DecisionRequest request, Map<String, String[]> requestQueryParams) {
    // 
    // Convert to a XacmlRequest
    // 
    Request xacmlRequest;
    try {
        xacmlRequest = this.getTranslator().convertRequest(request);
    } catch (ToscaPolicyConversionException e) {
        LOGGER.error("Failed to convert request", e);
        var response = new DecisionResponse();
        response.setStatus("error");
        response.setMessage(e.getLocalizedMessage());
        return Pair.of(response, null);
    }
    // 
    // Now get a decision
    // 
    var xacmlResponse = this.xacmlDecision(xacmlRequest);
    // 
    return Pair.of(this.getTranslator().convertResponse(xacmlResponse), xacmlResponse);
}
Also used : DecisionResponse(org.onap.policy.models.decisions.concepts.DecisionResponse) DecisionRequest(org.onap.policy.models.decisions.concepts.DecisionRequest) Request(com.att.research.xacml.api.Request) ToscaPolicyConversionException(org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException)

Example 4 with ToscaPolicyConversionException

use of org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException in project policy-xacml-pdp by onap.

the class StdXacmlApplicationServiceProvider method loadPolicy.

@Override
public synchronized void loadPolicy(ToscaPolicy toscaPolicy) throws XacmlApplicationException {
    try {
        // 
        // Convert the policies first
        // 
        Object xacmlPolicy = this.getTranslator(toscaPolicy.getType()).convertPolicy(toscaPolicy);
        if (xacmlPolicy == null) {
            throw new ToscaPolicyConversionException("Failed to convert policy");
        }
        // 
        // Create a copy of the properties object
        // 
        var newProperties = this.getProperties();
        // 
        // Construct the filename
        // 
        var refPath = XacmlPolicyUtils.constructUniquePolicyFilename(xacmlPolicy, this.getDataPath());
        // 
        if (XacmlPolicyUtils.writePolicyFile(refPath, xacmlPolicy) == null) {
            throw new ToscaPolicyConversionException("Unable to writePolicyFile");
        }
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Xacml Policy is {}{}", XacmlPolicyUtils.LINE_SEPARATOR, new String(Files.readAllBytes(refPath), StandardCharsets.UTF_8));
        }
        // 
        // Add root policy to properties object
        // 
        XacmlPolicyUtils.addRootPolicy(newProperties, refPath);
        // 
        // Write the properties to disk
        // 
        XacmlPolicyUtils.storeXacmlProperties(newProperties, XacmlPolicyUtils.getPropertiesPath(this.getDataPath()));
        // 
        // Reload the engine
        // 
        this.createEngine(newProperties);
        // 
        // Save the properties
        // 
        this.pdpProperties = newProperties;
        // 
        // Save in our map
        // 
        this.mapLoadedPolicies.put(toscaPolicy, refPath);
    } catch (IOException | ToscaPolicyConversionException e) {
        throw new XacmlApplicationException("loadPolicy failed", e);
    }
}
Also used : IOException(java.io.IOException) XacmlApplicationException(org.onap.policy.pdp.xacml.application.common.XacmlApplicationException) ToscaPolicyConversionException(org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException)

Example 5 with ToscaPolicyConversionException

use of org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException in project policy-xacml-pdp by onap.

the class StdBaseTranslatorTest method testBadData.

@Test
public void testBadData() throws ToscaPolicyConversionException, ParseException {
    TestTranslator translator = new TestTranslator();
    assertThatThrownBy(() -> translator.convertPolicy(new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class).hasMessageContaining("missing metadata");
    translator.metadata.put(StdBaseTranslator.POLICY_ID, "random.policy.id");
    assertThatThrownBy(() -> translator.convertPolicy(new ToscaPolicy())).isInstanceOf(ToscaPolicyConversionException.class).hasMessageContaining("missing metadata");
    translator.metadata.put(StdBaseTranslator.POLICY_VERSION, "1.0.0");
    ToscaPolicy policy = new ToscaPolicy();
    assertEquals("1.0.0", translator.convertPolicy(policy).getVersion());
    Map<String, String> ids = new HashMap<>();
    ids.put("onap.policies.Test", "1.0.0");
    Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
    Response xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT, Arrays.asList(obligation), policyIds);
    DecisionResponse decision = translator.convertResponse(xacmlResponse);
    assertNotNull(decision);
    assertThat(decision.getPolicies()).isNotNull();
    assertThat(decision.getPolicies()).isEmpty();
    Obligation badObligation = TestUtilsCommon.createXacmlObligation(ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(), Arrays.asList(assignmentBadPolicy, assignmentUnknown));
    xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_MISSING_ATTRIBUTE, null, Decision.PERMIT, Arrays.asList(badObligation), policyIds);
    decision = translator.convertResponse(xacmlResponse);
    assertNotNull(decision);
    xacmlResponse = TestUtilsCommon.createXacmlResponse(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Bad obligation", Decision.DENY, Arrays.asList(badObligation), policyIds);
    decision = translator.convertResponse(xacmlResponse);
    assertNotNull(decision);
    assertThat(decision.getStatus()).isEqualTo("error");
    assertThat(decision.getMessage()).isEqualTo("Bad obligation");
}
Also used : Response(com.att.research.xacml.api.Response) DecisionResponse(org.onap.policy.models.decisions.concepts.DecisionResponse) DecisionResponse(org.onap.policy.models.decisions.concepts.DecisionResponse) IdReference(com.att.research.xacml.api.IdReference) Obligation(com.att.research.xacml.api.Obligation) HashMap(java.util.HashMap) ToscaPolicy(org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy) ToscaPolicyConversionException(org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException) Test(org.junit.Test)

Aggregations

ToscaPolicyConversionException (org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException)14 IOException (java.io.IOException)5 PolicyType (oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType)4 HashMap (java.util.HashMap)3 RuleType (oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType)3 TargetType (oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType)3 Test (org.junit.Test)3 StandardCoder (org.onap.policy.common.utils.coder.StandardCoder)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 VariableReferenceType (oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType)2 CoderException (org.onap.policy.common.utils.coder.CoderException)2 DecisionRequest (org.onap.policy.models.decisions.concepts.DecisionRequest)2 DecisionResponse (org.onap.policy.models.decisions.concepts.DecisionResponse)2 ToscaPolicy (org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy)2 ToscaServiceTemplate (org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate)2 JpaToscaServiceTemplate (org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate)2 MatchablePolicyType (org.onap.policy.pdp.xacml.application.common.matchable.MatchablePolicyType)2 IdReference (com.att.research.xacml.api.IdReference)1 Identifier (com.att.research.xacml.api.Identifier)1