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);
}
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;
}
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);
}
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);
}
}
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");
}
Aggregations