04fe1fe89071b24c198d95291737b51ea6698db7
[policy/xacml-pdp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
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
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
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.
20  *
21  * SPDX-License-Identifier: Apache-2.0
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.policy.xacml.pdp.application.nativ;
26
27 import static org.assertj.core.api.Assertions.assertThat;
28 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
29
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;
35 import java.io.File;
36 import java.nio.file.Path;
37 import java.util.Map;
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;
59
60 class NativePdpApplicationTest {
61
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;
69
70     @TempDir
71     static Path policyFolder;
72
73     /**
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.
77      */
78     @BeforeAll
79     static void setup() throws Exception {
80         LOGGER.info("Setting up class");
81         //
82         // Setup our temporary folder
83         //
84         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
85         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
86                 properties, myCreator);
87         //
88         // Load service
89         //
90         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
91                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
92         //
93         // Find the native application and save for use in all the tests
94         //
95         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
96         for (XacmlApplicationServiceProvider application : applicationLoader) {
97             //
98             // Is it our service?
99             //
100             if (application instanceof NativePdpApplication) {
101                 //
102                 // Should be the first and only one
103                 //
104                 assertThat(service).isNull();
105                 service = (NativePdpApplication) application;
106             }
107             strDump.append(application.applicationName());
108             strDump.append(" supports ");
109             strDump.append(application.supportedPolicyTypes());
110             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
111         }
112         LOGGER.info("{}", strDump);
113         //
114         // Tell it to initialize based on the properties file
115         // we just built for it.
116         //
117         service.initialize(propertiesFile.toPath().getParent(), null);
118         //
119         // Load XACML Request
120         //
121         request = DOMRequest.load(
122             TextFileUtils.getTextFileAsString(
123                 "src/test/resources/requests/native.policy.request.xml"));
124     }
125
126     @Test
127     void testUncommon() {
128         NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
129         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
130             translator.convertRequest(null)
131         ).withMessageContaining("Do not call native convertRequest");
132
133         assertThat(translator.convertResponse(null)).isNull();
134
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");
143     }
144
145     @Test
146     void testBadPolicies() throws Exception {
147         NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
148         String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml");
149         //
150         // Serialize it into a class
151         //
152         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
153         //
154         // Make sure all the fields are setup properly
155         //
156         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
157         jtst.fromAuthorative(serviceTemplate);
158         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
159         //
160         // Get the policies
161         //
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");
176                 }
177             }
178         }
179     }
180
181     @Test
182     void testNativePolicy() throws Exception {
183
184         LOGGER.info("*********** Running native policy test *************");
185         //
186         // Now load the TOSCA compliant native policy - make sure
187         // the pdp can support it and have it load into the PDP.
188         //
189         TestUtils.loadPolicies("src/test/resources/policies/native.policy.yaml", service);
190         //
191         // Send the request and verify decision result
192         //
193         requestAndCheckDecision(request);
194     }
195
196     @Test
197     void testNativeToscaXacmlPolicy() throws Exception {
198         String policySetTypeYaml = ResourceUtils
199                 .getResourceAsString("src/test/resources/policies/native.toscapolicy.yaml");
200         checkPolicySetType(policySetTypeYaml);
201     }
202
203     @Test
204     void testBadToscaXacmlPolicyRule() throws Exception {
205         NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
206         String policyYaml = ResourceUtils
207                 .getResourceAsString("src/test/resources/policies/bad.native.toscapolicy.yaml");
208
209         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
210         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
211         jtst.fromAuthorative(serviceTemplate);
212         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
213
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");
220             }
221         }
222     }
223
224     @Test
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");
229
230         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
231         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
232         jtst.fromAuthorative(serviceTemplate);
233         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
234
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");
242                 }
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");
248                 }
249             }
250         }
251     }
252
253     /**
254      * Request a decision and check that it matches expectation.
255      *
256      * @param request to send to XACML PDP
257      * @throws Exception on errors requesting a decision and checking the returned decision
258      **/
259     private void requestAndCheckDecision(Request request) throws Exception {
260         //
261         // Ask for a decision
262         //
263         Response decision = service.makeNativeDecision(request);
264         //
265         // Check decision
266         //
267         checkDecision(decision);
268     }
269
270     /**
271      * Check that decision matches expectation.
272      *
273      * @param response received
274      * @throws Exception on errors checking the decision
275      **/
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));
283     }
284
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()) {
293                 try {
294                     service.loadPolicy(policy);
295                 } catch (XacmlApplicationException e) {
296                     LOGGER.error("Application failed to load policy", e);
297                 }
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");
303             }
304         }
305     }
306 }