47e92c09490359d38ad91caf38305b734766eb8b
[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  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.xacml.pdp.application.nativ;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27 import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
28
29 import com.att.research.xacml.api.Decision;
30 import com.att.research.xacml.api.Request;
31 import com.att.research.xacml.api.Response;
32 import com.att.research.xacml.std.dom.DOMRequest;
33 import com.att.research.xacml.std.dom.DOMResponse;
34 import java.io.File;
35 import java.nio.file.Path;
36 import java.util.Map;
37 import java.util.Properties;
38 import java.util.ServiceLoader;
39 import org.junit.jupiter.api.BeforeAll;
40 import org.junit.jupiter.api.Test;
41 import org.junit.jupiter.api.io.TempDir;
42 import org.onap.policy.common.utils.coder.StandardYamlCoder;
43 import org.onap.policy.common.utils.resources.ResourceUtils;
44 import org.onap.policy.common.utils.resources.TextFileUtils;
45 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
48 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
49 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
50 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
51 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
52 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 class NativePdpApplicationTest {
57
58     private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTest.class);
59     private static final String PERMIT = "Permit";
60     private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
61     private static final Properties properties = new Properties();
62     private static File propertiesFile;
63     private static NativePdpApplication service;
64     private static Request request;
65
66     @TempDir
67     static Path policyFolder;
68
69     /**
70      * Copies the xacml.properties and policies files into
71      * temporary folder and loads the service provider saving
72      * instance of provider off for other tests to use.
73      */
74     @BeforeAll
75     static void setup() throws Exception {
76         LOGGER.info("Setting up class");
77         //
78         // Setup our temporary folder
79         //
80         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.resolve(filename).toFile();
81         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
82             properties, myCreator);
83         //
84         // Load service
85         //
86         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
87             ServiceLoader.load(XacmlApplicationServiceProvider.class);
88         //
89         // Find the native application and save for use in all the tests
90         //
91         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
92         for (XacmlApplicationServiceProvider application : applicationLoader) {
93             //
94             // Is it our service?
95             //
96             if (application instanceof NativePdpApplication) {
97                 //
98                 // Should be the first and only one
99                 //
100                 assertThat(service).isNull();
101                 service = (NativePdpApplication) application;
102             }
103             strDump.append(application.applicationName());
104             strDump.append(" supports ");
105             strDump.append(application.supportedPolicyTypes());
106             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
107         }
108         LOGGER.info("{}", strDump);
109         //
110         // Tell it to initialize based on the properties file
111         // we just built for it.
112         //
113         service.initialize(propertiesFile.toPath().getParent(), null);
114         //
115         // Load XACML Request
116         //
117         request = DOMRequest.load(
118             TextFileUtils.getTextFileAsString(
119                 "src/test/resources/requests/native.policy.request.xml"));
120     }
121
122     @Test
123     void testUncommon() {
124         NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
125         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
126             translator.convertRequest(null)
127         ).withMessageContaining("Do not call native convertRequest");
128
129         assertThat(translator.convertResponse(null)).isNull();
130
131         NativePdpApplication application = new NativePdpApplication();
132         assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
133             "onap.policies.native.Xacml", "1.0.0"))).isTrue();
134         assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
135             "onap.policies.native.SomethingElse", "1.0.0"))).isFalse();
136         assertThat(application.actionDecisionsSupported()).contains("native");
137     }
138
139     @Test
140     void testBadPolicies() throws Exception {
141         NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
142         String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml");
143         //
144         // Serialize it into a class
145         //
146         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
147         //
148         // Make sure all the fields are setup properly
149         //
150         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
151         jtst.fromAuthorative(serviceTemplate);
152         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
153         //
154         // Get the policies
155         //
156         for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
157             for (ToscaPolicy policy : policies.values()) {
158                 if ("bad.base64".equals(policy.getName())) {
159                     assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
160                         translator.convertPolicy(policy)
161                     ).as(policy.getName()).withMessageContaining("error on Base64 decoding the native policy");
162                 } else if ("bad.noproperties".equals(policy.getName())) {
163                     assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
164                         translator.convertPolicy(policy)
165                     ).as(policy.getName()).withMessageContaining("Cannot decode NativeDefinition from null properties");
166                 } else if ("bad.policy".equals(policy.getName())) {
167                     assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
168                         translator.convertPolicy(policy)
169                     ).as(policy.getName()).withMessageContaining("Invalid XACML Policy");
170                 }
171             }
172         }
173     }
174
175     @Test
176     void testNativePolicy() throws Exception {
177
178         LOGGER.info("*********** Running native policy test *************");
179         //
180         // Now load the TOSCA compliant native policy - make sure
181         // the pdp can support it and have it load into the PDP.
182         //
183         TestUtils.loadPolicies("src/test/resources/policies/native.policy.yaml", service);
184         //
185         // Send the request and verify decision result
186         //
187         requestAndCheckDecision(request);
188     }
189
190     /**
191      * Request a decision and check that it matches expectation.
192      *
193      * @param request to send to XACML PDP
194      * @throws Exception on errors requesting a decision and checking the returned decision
195      **/
196     private void requestAndCheckDecision(Request request) throws Exception {
197         //
198         // Ask for a decision
199         //
200         Response decision = service.makeNativeDecision(request);
201         //
202         // Check decision
203         //
204         checkDecision(decision);
205     }
206
207     /**
208      * Check that decision matches expectation.
209      *
210      * @param response received
211      * @throws Exception on errors checking the decision
212      **/
213     private void checkDecision(Response response) throws Exception {
214         LOGGER.info("Looking for {} Decision", NativePdpApplicationTest.PERMIT);
215         assertThat(response).isNotNull();
216         Decision decision = response.getResults().iterator().next().getDecision();
217         assertThat(decision).isNotNull();
218         assertThat(decision).hasToString(NativePdpApplicationTest.PERMIT);
219         LOGGER.info("Xacml response we received {}", DOMResponse.toString(response));
220     }
221 }