2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6 * Modifications Copyright (C) 2021, 2024 Nordix Foundation.
7 * Modifications Copyright (C) 2024 Deutsche Telekom AG.
8 * ================================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * SPDX-License-Identifier: Apache-2.0
22 * ============LICENSE_END=========================================================
25 package org.onap.policy.xacml.pdp.application.nativ;
27 import static org.assertj.core.api.Assertions.assertThat;
28 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
30 import com.att.research.xacml.api.Decision;
31 import com.att.research.xacml.api.Request;
32 import com.att.research.xacml.api.Response;
33 import com.att.research.xacml.std.dom.DOMRequest;
34 import com.att.research.xacml.std.dom.DOMResponse;
36 import java.nio.file.Path;
38 import java.util.Properties;
39 import java.util.ServiceLoader;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType;
41 import org.junit.jupiter.api.BeforeAll;
42 import org.junit.jupiter.api.Test;
43 import org.junit.jupiter.api.io.TempDir;
44 import org.onap.policy.common.utils.coder.CoderException;
45 import org.onap.policy.common.utils.coder.StandardYamlCoder;
46 import org.onap.policy.common.utils.resources.ResourceUtils;
47 import org.onap.policy.common.utils.resources.TextFileUtils;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
49 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
50 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
51 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
52 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
53 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
54 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
55 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
56 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 class NativePdpApplicationTest {
62 private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTest.class);
63 private static final String PERMIT = "Permit";
64 private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
65 private static final Properties properties = new Properties();
66 private static File propertiesFile;
67 private static NativePdpApplication service;
68 private static Request request;
71 static Path policyFolder;
74 * Copies the xacml.properties and policies files into
75 * temporary folder and loads the service provider saving
76 * instance of provider off for other tests to use.
79 static void setup() throws Exception {
80 LOGGER.info("Setting up class");
82 // Setup our temporary folder
84 XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
85 propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
86 properties, myCreator);
90 ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
91 ServiceLoader.load(XacmlApplicationServiceProvider.class);
93 // Find the native application and save for use in all the tests
95 StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
96 for (XacmlApplicationServiceProvider application : applicationLoader) {
100 if (application instanceof NativePdpApplication) {
102 // Should be the first and only one
104 assertThat(service).isNull();
105 service = (NativePdpApplication) application;
107 strDump.append(application.applicationName());
108 strDump.append(" supports ");
109 strDump.append(application.supportedPolicyTypes());
110 strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
112 LOGGER.info("{}", strDump);
114 // Tell it to initialize based on the properties file
115 // we just built for it.
117 service.initialize(propertiesFile.toPath().getParent(), null);
119 // Load XACML Request
121 request = DOMRequest.load(
122 TextFileUtils.getTextFileAsString(
123 "src/test/resources/requests/native.policy.request.xml"));
127 void testUncommon() {
128 NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
129 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
130 translator.convertRequest(null)
131 ).withMessageContaining("Do not call native convertRequest");
133 assertThat(translator.convertResponse(null)).isNull();
135 NativePdpApplication application = new NativePdpApplication();
136 assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
137 "onap.policies.native.Xacml", "1.0.0"))).isTrue();
138 assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
139 "onap.policies.native.ToscaXacml", "1.0.0"))).isTrue();
140 assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
141 "onap.policies.native.SomethingElse", "1.0.0"))).isFalse();
142 assertThat(application.actionDecisionsSupported()).contains("native");
146 void testBadPolicies() throws Exception {
147 NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
148 String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml");
150 // Serialize it into a class
152 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
154 // Make sure all the fields are setup properly
156 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
157 jtst.fromAuthorative(serviceTemplate);
158 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
162 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
163 for (ToscaPolicy policy : policies.values()) {
164 if ("bad.base64".equals(policy.getName())) {
165 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
166 translator.convertPolicy(policy)
167 ).as(policy.getName()).withMessageContaining("error on Base64 decoding the native policy");
168 } else if ("bad.noproperties".equals(policy.getName())) {
169 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
170 translator.convertPolicy(policy)
171 ).as(policy.getName()).withMessageContaining("Cannot decode NativeDefinition from null properties");
172 } else if ("bad.policy".equals(policy.getName())) {
173 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
174 translator.convertPolicy(policy)
175 ).as(policy.getName()).withMessageContaining("Invalid XACML Policy");
182 void testNativePolicy() throws Exception {
184 LOGGER.info("*********** Running native policy test *************");
186 // Now load the TOSCA compliant native policy - make sure
187 // the pdp can support it and have it load into the PDP.
189 TestUtils.loadPolicies("src/test/resources/policies/native.policy.yaml", service);
191 // Send the request and verify decision result
193 requestAndCheckDecision(request);
197 void testNativeToscaXacmlPolicy() throws Exception {
198 String policySetTypeYaml = ResourceUtils
199 .getResourceAsString("src/test/resources/policies/native.toscapolicy.yaml");
200 checkPolicySetType(policySetTypeYaml);
204 void testBadToscaXacmlPolicyRule() throws Exception {
205 NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
206 String policyYaml = ResourceUtils
207 .getResourceAsString("src/test/resources/policies/bad.native.toscapolicy.yaml");
209 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
210 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
211 jtst.fromAuthorative(serviceTemplate);
212 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
214 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
215 for (ToscaPolicy policy : policies.values()) {
216 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
217 translator.convertPolicy(policy)
218 ).as((String) policy.getMetadata().get("policy-id"))
219 .withMessageContaining("Invalid rule format");
225 void testBadToscaXacmlPolicyTarget() throws Exception {
226 NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
227 String policyYaml = ResourceUtils
228 .getResourceAsString("src/test/resources/policies/bad.native.tosca.policy.target.yaml");
230 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
231 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
232 jtst.fromAuthorative(serviceTemplate);
233 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
235 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
236 for (ToscaPolicy policy : policies.values()) {
237 if ("bad.tosca.policy.test".equals(policy.getName())) {
238 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
239 translator.convertPolicy(policy)
240 ).as((String) policy.getMetadata().get("policy-id"))
241 .withMessageContaining("Invalid operator");
243 if ("bad.tosca.policy.target.test".equals(policy.getName())) {
244 assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
245 translator.convertPolicy(policy)
246 ).as((String) policy.getMetadata().get("policy-id"))
247 .withMessageContaining("Invalid target format");
254 * Request a decision and check that it matches expectation.
256 * @param request to send to XACML PDP
257 * @throws Exception on errors requesting a decision and checking the returned decision
259 private void requestAndCheckDecision(Request request) throws Exception {
261 // Ask for a decision
263 Response decision = service.makeNativeDecision(request);
267 checkDecision(decision);
271 * Check that decision matches expectation.
273 * @param response received
274 * @throws Exception on errors checking the decision
276 private void checkDecision(Response response) throws Exception {
277 LOGGER.info("Looking for {} Decision", NativePdpApplicationTest.PERMIT);
278 assertThat(response).isNotNull();
279 Decision decision = response.getResults().iterator().next().getDecision();
280 assertThat(decision).isNotNull();
281 assertThat(decision).hasToString(NativePdpApplicationTest.PERMIT);
282 LOGGER.info("Xacml response we received {}", DOMResponse.toString(response));
285 private void checkPolicySetType(String policySetTypeYaml) throws ToscaPolicyConversionException, CoderException {
286 NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
287 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policySetTypeYaml, ToscaServiceTemplate.class);
288 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
289 jtst.fromAuthorative(serviceTemplate);
290 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
291 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
292 for (ToscaPolicy policy : policies.values()) {
294 service.loadPolicy(policy);
295 } catch (XacmlApplicationException e) {
296 LOGGER.error("Application failed to load policy", e);
298 PolicySetType policySetType = (PolicySetType) translator.convertPolicy(policy);
299 assertThat(policySetType).isNotNull();
300 assertThat(policySetType.getPolicySetId()).isEqualTo("tosca.policy.test");
301 assertThat(policySetType.getPolicyCombiningAlgId())
302 .isEqualTo("urn:oasis:names:tc:xacml:1.0:policy-combining-algorithm:first-applicable");