From 30ead499d80c3c6cf6433c6a1e9fb4693d109ab1 Mon Sep 17 00:00:00 2001 From: liamfallon Date: Thu, 17 Dec 2020 16:57:10 +0000 Subject: XACML to accept properties as null xacml-pdp expects the property map to exist in all policies, even if it is sometimes empty. Now, the propperty map can be null. The code is updated to cope with a null property map. Issue-ID: POLICY-2900 Change-Id: Ie31a2770aff1435a1d1064512d0c2fa2088d3183 Signed-off-by: liamfallon --- .../pdp/application/guard/GuardTranslator.java | 9 +- .../pdp/application/guard/GuardTranslatorTest.java | 12 ++ .../src/test/resources/test-bad-policies.yaml | 11 +- .../application/nativ/NativePdpApplication.java | 73 ------- .../nativ/NativePdpApplicationTranslator.java | 110 ---------- .../application/native/NativePdpApplication.java | 73 +++++++ .../native/NativePdpApplicationTranslator.java | 112 ++++++++++ .../nativ/NativePdpApplicationTest.java | 226 --------------------- .../native/NativePdpApplicationTest.java | 226 +++++++++++++++++++++ 9 files changed, 439 insertions(+), 413 deletions(-) delete mode 100644 applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplication.java delete mode 100644 applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTranslator.java create mode 100644 applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplication.java create mode 100644 applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTranslator.java delete mode 100644 applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java create mode 100644 applications/native/src/test/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTest.java (limited to 'applications') diff --git a/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java b/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java index b3ee36bc..2b713740 100644 --- a/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java +++ b/applications/guard/src/main/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslator.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -129,6 +130,12 @@ public class GuardTranslator implements ToscaPolicyTranslator { // this.fillMetadataSection(newPolicyType, toscaPolicy.getMetadata()); // + // There should be properties metadata section + // + if (toscaPolicy.getProperties() == null) { + throw new ToscaPolicyConversionException("no properties specified on guard policy: " + policyName); + } + // // Generate the TargetType - add true if not blacklist // newPolicyType.setTarget(this.generateTargetType(toscaPolicy.getProperties(), @@ -694,4 +701,4 @@ public class GuardTranslator implements ToscaPolicyTranslator { return rule; } -} \ No newline at end of file +} diff --git a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java index 7e5e3ed5..e4c958b9 100644 --- a/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java +++ b/applications/guard/src/test/java/org/onap/policy/xacml/pdp/application/guard/GuardTranslatorTest.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,6 +36,7 @@ import com.att.research.xacml.std.StdStatusCode; import com.att.research.xacml.util.XACMLPolicyWriter; import java.io.ByteArrayOutputStream; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; @@ -204,6 +206,16 @@ public class GuardTranslatorTest { } } } + + ToscaPolicy testPol = completedJtst.getToscaTopologyTemplate().getPolicies().get(0).values().iterator().next(); + + testPol.setProperties(new LinkedHashMap<>()); + assertThatExceptionOfType(ToscaPolicyConversionException.class) + .isThrownBy(() -> translator.convertPolicy(testPol)); + + testPol.setProperties(null); + assertThatExceptionOfType(ToscaPolicyConversionException.class) + .isThrownBy(() -> translator.convertPolicy(testPol)); } private void validateCommon(ToscaPolicy policy, PolicyType xacmlPolicy) { diff --git a/applications/guard/src/test/resources/test-bad-policies.yaml b/applications/guard/src/test/resources/test-bad-policies.yaml index 07040c54..eb39aded 100644 --- a/applications/guard/src/test/resources/test-bad-policies.yaml +++ b/applications/guard/src/test/resources/test-bad-policies.yaml @@ -5,6 +5,8 @@ topology_template: type: onap.policies.controlloop.guard.common.FrequencyLimiter type_version: 1.0.0 version: 1.0.0 + properties: + badProperty: badValue - frequency-timewindow: type: onap.policies.controlloop.guard.common.FrequencyLimiter type_version: 1.0.0 @@ -16,7 +18,8 @@ topology_template: type: onap.policies.controlloop.guard.common.MinMax type_version: 1.0.0 version: 1.0.0 - properties: null + properties: + badProperty: badValue - minmax-nominmax: type: onap.policies.controlloop.guard.common.MinMax type_version: 1.0.0 @@ -27,12 +30,14 @@ topology_template: type: onap.policies.controlloop.guard.common.Blacklist type_version: 1.0.0 version: 1.0.0 - properties: null + properties: + badProperty: badValue - filter-noalgorithm: type: onap.policies.controlloop.guard.common.Filter type_version: 1.0.0 version: 1.0.0 - properties: null + properties: + badProperty: badValue - filter-badalgorithm: type: onap.policies.controlloop.guard.common.Filter type_version: 1.0.0 diff --git a/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplication.java b/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplication.java deleted file mode 100644 index f8248f1c..00000000 --- a/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplication.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.xacml.pdp.application.nativ; - -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import java.util.Arrays; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; -import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator; -import org.onap.policy.pdp.xacml.application.common.std.StdXacmlApplicationServiceProvider; - -/** - * This class implements an application that handles onap.policies.native.Xacml policies. - * - * @author Chenfei Gao (cgao@research.att.com) - * - */ -public class NativePdpApplication extends StdXacmlApplicationServiceProvider { - - private static final ToscaPolicyTypeIdentifier nativePolicyType = new ToscaPolicyTypeIdentifier( - "onap.policies.native.Xacml", "1.0.0"); - private NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator(); - - /** - * Constructor. - */ - public NativePdpApplication() { - super(); - - applicationName = "native"; - actions = Arrays.asList("native"); - supportedPolicyTypes.add(nativePolicyType); - } - - @Override - public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) { - return nativePolicyType.equals(policyTypeId); - } - - @Override - protected ToscaPolicyTranslator getTranslator(String type) { - return translator; - } - - /** - * Makes decision for the incoming native xacml request. - * @param request the native xacml request - * @return the native xacml response - */ - public Response makeNativeDecision(Request request) { - return this.xacmlDecision(request); - } -} diff --git a/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTranslator.java b/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTranslator.java deleted file mode 100644 index 5ce25fac..00000000 --- a/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTranslator.java +++ /dev/null @@ -1,110 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.xacml.pdp.application.nativ; - -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.util.XACMLPolicyScanner; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Map; -import org.onap.policy.models.decisions.concepts.DecisionRequest; -import org.onap.policy.models.decisions.concepts.DecisionResponse; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; -import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException; -import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class implements one translator that interprets TOSCA policy and decision API request/response payload. - * - * @author Chenfei Gao (cgao@research.att.com) - * - */ -public class NativePdpApplicationTranslator implements ToscaPolicyTranslator { - - private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTranslator.class); - private static final String POLICY = "policy"; - - public NativePdpApplicationTranslator() { - super(); - } - - @Override - public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException { - // - // Extract the Base64 encoded policy xml string and decode it - // - String encodedXacmlPolicy = getNativeXacmlPolicy(toscaPolicy); - String decodedXacmlPolicy; - try { - decodedXacmlPolicy = new String(Base64.getDecoder().decode(encodedXacmlPolicy), StandardCharsets.UTF_8); - } catch (IllegalArgumentException exc) { - throw new ToscaPolicyConversionException("error on Base64 decoding the native policy", exc); - } - LOGGER.debug("Decoded xacml policy {}", decodedXacmlPolicy); - // - // Scan the string and convert to xacml PolicyType - // - try (ByteArrayInputStream is = new ByteArrayInputStream(decodedXacmlPolicy.getBytes(StandardCharsets.UTF_8))) { - // - // Read the Policy In - // - Object policy = XACMLPolicyScanner.readPolicy(is); - if (policy == null) { - throw new ToscaPolicyConversionException("Invalid XACML Policy"); - } - return policy; - } catch (IOException exc) { - throw new ToscaPolicyConversionException("Failed to read policy", exc); - } - } - - private String getNativeXacmlPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException { - - Map propertyMap = toscaPolicy.getProperties(); - if (propertyMap.isEmpty() || !propertyMap.containsKey(POLICY)) { - throw new ToscaPolicyConversionException("no xacml native policy found in the tosca policy"); - } - - String nativePolicyString = propertyMap.get(POLICY).toString(); - LOGGER.debug("Base64 encoded native xacml policy {}", nativePolicyString); - return nativePolicyString; - } - - @Override - public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException { - throw new ToscaPolicyConversionException("Do not call native convertRequest"); - } - - @Override - public DecisionResponse convertResponse(Response xacmlResponse) { - // - // We do nothing to DecisionResponse for native xacml application - // - return null; - } -} \ No newline at end of file diff --git a/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplication.java b/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplication.java new file mode 100644 index 00000000..f8248f1c --- /dev/null +++ b/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplication.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.xacml.pdp.application.nativ; + +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import java.util.Arrays; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; +import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator; +import org.onap.policy.pdp.xacml.application.common.std.StdXacmlApplicationServiceProvider; + +/** + * This class implements an application that handles onap.policies.native.Xacml policies. + * + * @author Chenfei Gao (cgao@research.att.com) + * + */ +public class NativePdpApplication extends StdXacmlApplicationServiceProvider { + + private static final ToscaPolicyTypeIdentifier nativePolicyType = new ToscaPolicyTypeIdentifier( + "onap.policies.native.Xacml", "1.0.0"); + private NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator(); + + /** + * Constructor. + */ + public NativePdpApplication() { + super(); + + applicationName = "native"; + actions = Arrays.asList("native"); + supportedPolicyTypes.add(nativePolicyType); + } + + @Override + public boolean canSupportPolicyType(ToscaPolicyTypeIdentifier policyTypeId) { + return nativePolicyType.equals(policyTypeId); + } + + @Override + protected ToscaPolicyTranslator getTranslator(String type) { + return translator; + } + + /** + * Makes decision for the incoming native xacml request. + * @param request the native xacml request + * @return the native xacml response + */ + public Response makeNativeDecision(Request request) { + return this.xacmlDecision(request); + } +} diff --git a/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTranslator.java b/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTranslator.java new file mode 100644 index 00000000..34ef1462 --- /dev/null +++ b/applications/native/src/main/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTranslator.java @@ -0,0 +1,112 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.xacml.pdp.application.nativ; + +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.util.XACMLPolicyScanner; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; +import org.apache.commons.collections4.MapUtils; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException; +import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class implements one translator that interprets TOSCA policy and decision API request/response payload. + * + * @author Chenfei Gao (cgao@research.att.com) + * + */ +public class NativePdpApplicationTranslator implements ToscaPolicyTranslator { + + private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTranslator.class); + private static final String POLICY = "policy"; + + public NativePdpApplicationTranslator() { + super(); + } + + @Override + public Object convertPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException { + // + // Extract the Base64 encoded policy xml string and decode it + // + String encodedXacmlPolicy = getNativeXacmlPolicy(toscaPolicy); + String decodedXacmlPolicy; + try { + decodedXacmlPolicy = new String(Base64.getDecoder().decode(encodedXacmlPolicy), StandardCharsets.UTF_8); + } catch (IllegalArgumentException exc) { + throw new ToscaPolicyConversionException("error on Base64 decoding the native policy", exc); + } + LOGGER.debug("Decoded xacml policy {}", decodedXacmlPolicy); + // + // Scan the string and convert to xacml PolicyType + // + try (ByteArrayInputStream is = new ByteArrayInputStream(decodedXacmlPolicy.getBytes(StandardCharsets.UTF_8))) { + // + // Read the Policy In + // + Object policy = XACMLPolicyScanner.readPolicy(is); + if (policy == null) { + throw new ToscaPolicyConversionException("Invalid XACML Policy"); + } + return policy; + } catch (IOException exc) { + throw new ToscaPolicyConversionException("Failed to read policy", exc); + } + } + + private String getNativeXacmlPolicy(ToscaPolicy toscaPolicy) throws ToscaPolicyConversionException { + + Map propertyMap = toscaPolicy.getProperties(); + if (MapUtils.isEmpty(propertyMap) || !propertyMap.containsKey(POLICY)) { + throw new ToscaPolicyConversionException("no xacml native policy found in the tosca policy"); + } + + String nativePolicyString = propertyMap.get(POLICY).toString(); + LOGGER.debug("Base64 encoded native xacml policy {}", nativePolicyString); + return nativePolicyString; + } + + @Override + public Request convertRequest(DecisionRequest request) throws ToscaPolicyConversionException { + throw new ToscaPolicyConversionException("Do not call native convertRequest"); + } + + @Override + public DecisionResponse convertResponse(Response xacmlResponse) { + // + // We do nothing to DecisionResponse for native xacml application + // + return null; + } +} diff --git a/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java b/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java deleted file mode 100644 index f434e80f..00000000 --- a/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/nativ/NativePdpApplicationTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - * ============LICENSE_END========================================================= - */ - -package org.onap.policy.xacml.pdp.application.nativ; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; - -import com.att.research.xacml.api.Decision; -import com.att.research.xacml.api.Request; -import com.att.research.xacml.api.Response; -import com.att.research.xacml.std.dom.DOMRequest; -import com.att.research.xacml.std.dom.DOMResponse; -import java.io.File; -import java.util.Map; -import java.util.Properties; -import java.util.ServiceLoader; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.onap.policy.common.endpoints.parameters.RestServerParameters; -import org.onap.policy.common.utils.coder.StandardYamlCoder; -import org.onap.policy.common.utils.resources.ResourceUtils; -import org.onap.policy.common.utils.resources.TextFileUtils; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; -import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; -import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; -import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; -import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException; -import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider; -import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils; -import org.onap.policy.pdp.xacml.xacmltest.TestUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class NativePdpApplicationTest { - - private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTest.class); - private static final String PERMIT = "Permit"; - private static final StandardYamlCoder yamlCoder = new StandardYamlCoder(); - private static Properties properties = new Properties(); - private static File propertiesFile; - private static RestServerParameters clientParams = new RestServerParameters(); - private static NativePdpApplication service; - private static Request request; - - @ClassRule - public static final TemporaryFolder policyFolder = new TemporaryFolder(); - - /** - * Copies the xacml.properties and policies files into - * temporary folder and loads the service provider saving - * instance of provider off for other tests to use. - */ - @BeforeClass - public static void setup() throws Exception { - LOGGER.info("Setting up class"); - // - // Setup our temporary folder - // - XacmlPolicyUtils.FileCreator myCreator = (filename) -> policyFolder.newFile(filename); - propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties", - properties, myCreator); - // - // Load service - // - ServiceLoader applicationLoader = - ServiceLoader.load(XacmlApplicationServiceProvider.class); - // - // Find the native application and save for use in all the tests - // - StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR); - for (XacmlApplicationServiceProvider application : applicationLoader) { - // - // Is it our service? - // - if (application instanceof NativePdpApplication) { - // - // Should be the first and only one - // - assertThat(service).isNull(); - service = (NativePdpApplication) application; - } - strDump.append(application.applicationName()); - strDump.append(" supports "); - strDump.append(application.supportedPolicyTypes()); - strDump.append(XacmlPolicyUtils.LINE_SEPARATOR); - } - LOGGER.info("{}", strDump); - // - // Tell it to initialize based on the properties file - // we just built for it. - // - service.initialize(propertiesFile.toPath().getParent(), clientParams); - // - // Load XACML Request - // - request = DOMRequest.load( - TextFileUtils.getTextFileAsString( - "src/test/resources/requests/native.policy.request.xml")); - } - - @Test - public void testUncommon() { - NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator(); - assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> - translator.convertRequest(null) - ).withMessageContaining("Do not call native convertRequest"); - - assertThat(translator.convertResponse(null)).isNull(); - - NativePdpApplication application = new NativePdpApplication(); - assertThat(application.canSupportPolicyType(new ToscaPolicyTypeIdentifier( - "onap.policies.native.Xacml", "1.0.0"))).isTrue(); - assertThat(application.canSupportPolicyType(new ToscaPolicyTypeIdentifier( - "onap.policies.native.SomethingElse", "1.0.0"))).isFalse(); - assertThat(application.actionDecisionsSupported()).contains("native"); - } - - @Test - public void testBadPolicies() throws Exception { - NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator(); - String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml"); - // - // Serialize it into a class - // - ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class); - // - // Make sure all the fields are setup properly - // - JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate(); - jtst.fromAuthorative(serviceTemplate); - ToscaServiceTemplate completedJtst = jtst.toAuthorative(); - // - // Get the policies - // - for (Map policies : completedJtst.getToscaTopologyTemplate().getPolicies()) { - for (ToscaPolicy policy : policies.values()) { - if ("bad.base64".equals(policy.getName())) { - assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> - translator.convertPolicy(policy) - ).withMessageContaining("error on Base64 decoding the native policy"); - } else if ("bad.noproperties".equals(policy.getName())) { - assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> - translator.convertPolicy(policy) - ).withMessageContaining("no xacml native policy found in the tosca policy"); - } else if ("bad.policy".equals(policy.getName())) { - assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> - translator.convertPolicy(policy) - ).withMessageContaining("Invalid XACML Policy"); - } - } - } - } - - @Test - public void testNativePolicy() throws Exception { - - LOGGER.info("*********** Running native policy test *************"); - // - // Now load the TOSCA compliant native policy - make sure - // the pdp can support it and have it load into the PDP. - // - TestUtils.loadPolicies("src/test/resources/policies/native.policy.yaml", service); - // - // Send the request and verify decision result - // - requestAndCheckDecision(request, PERMIT); - } - - /** - * Request a decision and check that it matches expectation. - * - * @param request to send to XACML PDP - * @param expected from the response - * @throws Exception on errors requesting a decision and checking the returned decision - * - **/ - private void requestAndCheckDecision(Request request, String expected) throws Exception { - // - // Ask for a decision - // - Response decision = service.makeNativeDecision(request); - // - // Check decision - // - checkDecision(expected, decision); - } - - /** - * Check that decision matches expectation. - * - * @param expected from the response - * @param response received - * @throws Exception on errors checking the decision - * - **/ - private void checkDecision(String expected, Response response) throws Exception { - LOGGER.info("Looking for {} Decision", expected); - assertThat(response).isNotNull(); - Decision decision = response.getResults().iterator().next().getDecision(); - assertThat(decision).isNotNull(); - assertThat(decision).hasToString(expected); - LOGGER.info("Xacml response we received {}", DOMResponse.toString(response)); - } -} \ No newline at end of file diff --git a/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTest.java b/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTest.java new file mode 100644 index 00000000..f434e80f --- /dev/null +++ b/applications/native/src/test/java/org/onap/policy/xacml/pdp/application/native/NativePdpApplicationTest.java @@ -0,0 +1,226 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.xacml.pdp.application.nativ; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +import com.att.research.xacml.api.Decision; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.Response; +import com.att.research.xacml.std.dom.DOMRequest; +import com.att.research.xacml.std.dom.DOMResponse; +import java.io.File; +import java.util.Map; +import java.util.Properties; +import java.util.ServiceLoader; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.onap.policy.common.endpoints.parameters.RestServerParameters; +import org.onap.policy.common.utils.coder.StandardYamlCoder; +import org.onap.policy.common.utils.resources.ResourceUtils; +import org.onap.policy.common.utils.resources.TextFileUtils; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy; +import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyTypeIdentifier; +import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate; +import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate; +import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException; +import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider; +import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils; +import org.onap.policy.pdp.xacml.xacmltest.TestUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class NativePdpApplicationTest { + + private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTest.class); + private static final String PERMIT = "Permit"; + private static final StandardYamlCoder yamlCoder = new StandardYamlCoder(); + private static Properties properties = new Properties(); + private static File propertiesFile; + private static RestServerParameters clientParams = new RestServerParameters(); + private static NativePdpApplication service; + private static Request request; + + @ClassRule + public static final TemporaryFolder policyFolder = new TemporaryFolder(); + + /** + * Copies the xacml.properties and policies files into + * temporary folder and loads the service provider saving + * instance of provider off for other tests to use. + */ + @BeforeClass + public static void setup() throws Exception { + LOGGER.info("Setting up class"); + // + // Setup our temporary folder + // + XacmlPolicyUtils.FileCreator myCreator = (filename) -> policyFolder.newFile(filename); + propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties", + properties, myCreator); + // + // Load service + // + ServiceLoader applicationLoader = + ServiceLoader.load(XacmlApplicationServiceProvider.class); + // + // Find the native application and save for use in all the tests + // + StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR); + for (XacmlApplicationServiceProvider application : applicationLoader) { + // + // Is it our service? + // + if (application instanceof NativePdpApplication) { + // + // Should be the first and only one + // + assertThat(service).isNull(); + service = (NativePdpApplication) application; + } + strDump.append(application.applicationName()); + strDump.append(" supports "); + strDump.append(application.supportedPolicyTypes()); + strDump.append(XacmlPolicyUtils.LINE_SEPARATOR); + } + LOGGER.info("{}", strDump); + // + // Tell it to initialize based on the properties file + // we just built for it. + // + service.initialize(propertiesFile.toPath().getParent(), clientParams); + // + // Load XACML Request + // + request = DOMRequest.load( + TextFileUtils.getTextFileAsString( + "src/test/resources/requests/native.policy.request.xml")); + } + + @Test + public void testUncommon() { + NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator(); + assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> + translator.convertRequest(null) + ).withMessageContaining("Do not call native convertRequest"); + + assertThat(translator.convertResponse(null)).isNull(); + + NativePdpApplication application = new NativePdpApplication(); + assertThat(application.canSupportPolicyType(new ToscaPolicyTypeIdentifier( + "onap.policies.native.Xacml", "1.0.0"))).isTrue(); + assertThat(application.canSupportPolicyType(new ToscaPolicyTypeIdentifier( + "onap.policies.native.SomethingElse", "1.0.0"))).isFalse(); + assertThat(application.actionDecisionsSupported()).contains("native"); + } + + @Test + public void testBadPolicies() throws Exception { + NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator(); + String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml"); + // + // Serialize it into a class + // + ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class); + // + // Make sure all the fields are setup properly + // + JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate(); + jtst.fromAuthorative(serviceTemplate); + ToscaServiceTemplate completedJtst = jtst.toAuthorative(); + // + // Get the policies + // + for (Map policies : completedJtst.getToscaTopologyTemplate().getPolicies()) { + for (ToscaPolicy policy : policies.values()) { + if ("bad.base64".equals(policy.getName())) { + assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> + translator.convertPolicy(policy) + ).withMessageContaining("error on Base64 decoding the native policy"); + } else if ("bad.noproperties".equals(policy.getName())) { + assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> + translator.convertPolicy(policy) + ).withMessageContaining("no xacml native policy found in the tosca policy"); + } else if ("bad.policy".equals(policy.getName())) { + assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() -> + translator.convertPolicy(policy) + ).withMessageContaining("Invalid XACML Policy"); + } + } + } + } + + @Test + public void testNativePolicy() throws Exception { + + LOGGER.info("*********** Running native policy test *************"); + // + // Now load the TOSCA compliant native policy - make sure + // the pdp can support it and have it load into the PDP. + // + TestUtils.loadPolicies("src/test/resources/policies/native.policy.yaml", service); + // + // Send the request and verify decision result + // + requestAndCheckDecision(request, PERMIT); + } + + /** + * Request a decision and check that it matches expectation. + * + * @param request to send to XACML PDP + * @param expected from the response + * @throws Exception on errors requesting a decision and checking the returned decision + * + **/ + private void requestAndCheckDecision(Request request, String expected) throws Exception { + // + // Ask for a decision + // + Response decision = service.makeNativeDecision(request); + // + // Check decision + // + checkDecision(expected, decision); + } + + /** + * Check that decision matches expectation. + * + * @param expected from the response + * @param response received + * @throws Exception on errors checking the decision + * + **/ + private void checkDecision(String expected, Response response) throws Exception { + LOGGER.info("Looking for {} Decision", expected); + assertThat(response).isNotNull(); + Decision decision = response.getResults().iterator().next().getDecision(); + assertThat(decision).isNotNull(); + assertThat(decision).hasToString(expected); + LOGGER.info("Xacml response we received {}", DOMResponse.toString(response)); + } +} \ No newline at end of file -- cgit 1.2.3-korg