Change RestServerParameters to BusTopicParams
[policy/xacml-pdp.git] / applications / native / src / test / java / org / onap / policy / xacml / pdp / application / nativ / NativePdpApplicationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021 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.util.Map;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
38 import org.junit.BeforeClass;
39 import org.junit.ClassRule;
40 import org.junit.Test;
41 import org.junit.rules.TemporaryFolder;
42 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
43 import org.onap.policy.common.utils.coder.StandardYamlCoder;
44 import org.onap.policy.common.utils.resources.ResourceUtils;
45 import org.onap.policy.common.utils.resources.TextFileUtils;
46 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
47 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
48 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
49 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
50 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
51 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
52 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
53 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
56
57 public class NativePdpApplicationTest {
58
59     private static final Logger LOGGER = LoggerFactory.getLogger(NativePdpApplicationTest.class);
60     private static final String PERMIT = "Permit";
61     private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
62     private static Properties properties = new Properties();
63     private static File propertiesFile;
64     private static BusTopicParams clientParams = new BusTopicParams();
65     private static NativePdpApplication service;
66     private static Request request;
67
68     @ClassRule
69     public static final TemporaryFolder policyFolder = new TemporaryFolder();
70
71     /**
72      * Copies the xacml.properties and policies files into
73      * temporary folder and loads the service provider saving
74      * instance of provider off for other tests to use.
75      */
76     @BeforeClass
77     public static void setup() throws Exception {
78         LOGGER.info("Setting up class");
79         //
80         // Setup our temporary folder
81         //
82         XacmlPolicyUtils.FileCreator myCreator = (filename) -> policyFolder.newFile(filename);
83         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
84                 properties, myCreator);
85         //
86         // Load service
87         //
88         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
89                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
90         //
91         // Find the native application and save for use in all the tests
92         //
93         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
94         for (XacmlApplicationServiceProvider application : applicationLoader) {
95             //
96             // Is it our service?
97             //
98             if (application instanceof NativePdpApplication) {
99                 //
100                 // Should be the first and only one
101                 //
102                 assertThat(service).isNull();
103                 service = (NativePdpApplication) application;
104             }
105             strDump.append(application.applicationName());
106             strDump.append(" supports ");
107             strDump.append(application.supportedPolicyTypes());
108             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
109         }
110         LOGGER.info("{}", strDump);
111         //
112         // Tell it to initialize based on the properties file
113         // we just built for it.
114         //
115         service.initialize(propertiesFile.toPath().getParent(), clientParams);
116         //
117         // Load XACML Request
118         //
119         request = DOMRequest.load(
120                 TextFileUtils.getTextFileAsString(
121                         "src/test/resources/requests/native.policy.request.xml"));
122     }
123
124     @Test
125     public void testUncommon() {
126         NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
127         assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
128             translator.convertRequest(null)
129         ).withMessageContaining("Do not call native convertRequest");
130
131         assertThat(translator.convertResponse(null)).isNull();
132
133         NativePdpApplication application = new NativePdpApplication();
134         assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
135             "onap.policies.native.Xacml", "1.0.0"))).isTrue();
136         assertThat(application.canSupportPolicyType(new ToscaConceptIdentifier(
137                 "onap.policies.native.SomethingElse", "1.0.0"))).isFalse();
138         assertThat(application.actionDecisionsSupported()).contains("native");
139     }
140
141     @Test
142     public void testBadPolicies() throws Exception {
143         NativePdpApplicationTranslator translator = new NativePdpApplicationTranslator();
144         String policyYaml = ResourceUtils.getResourceAsString("src/test/resources/policies/bad.native.policies.yaml");
145         //
146         // Serialize it into a class
147         //
148         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
149         //
150         // Make sure all the fields are setup properly
151         //
152         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
153         jtst.fromAuthorative(serviceTemplate);
154         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
155         //
156         // Get the policies
157         //
158         for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
159             for (ToscaPolicy policy : policies.values()) {
160                 if ("bad.base64".equals(policy.getName())) {
161                     assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
162                         translator.convertPolicy(policy)
163                     ).withMessageContaining("error on Base64 decoding the native policy");
164                 } else if ("bad.noproperties".equals(policy.getName())) {
165                     assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
166                         translator.convertPolicy(policy)
167                     ).withMessageContaining("no xacml native policy found in the tosca policy");
168                 } else if ("bad.policy".equals(policy.getName())) {
169                     assertThatExceptionOfType(ToscaPolicyConversionException.class).isThrownBy(() ->
170                         translator.convertPolicy(policy)
171                     ).withMessageContaining("Invalid XACML Policy");
172                 }
173             }
174         }
175     }
176
177     @Test
178     public void testNativePolicy() throws Exception {
179
180         LOGGER.info("*********** Running native policy test *************");
181         //
182         // Now load the TOSCA compliant native policy - make sure
183         // the pdp can support it and have it load into the PDP.
184         //
185         TestUtils.loadPolicies("src/test/resources/policies/native.policy.yaml", service);
186         //
187         // Send the request and verify decision result
188         //
189         requestAndCheckDecision(request, PERMIT);
190     }
191
192     /**
193      * Request a decision and check that it matches expectation.
194      *
195      * @param request to send to XACML PDP
196      * @param expected from the response
197      * @throws Exception on errors requesting a decision and checking the returned decision
198      *
199      **/
200     private void requestAndCheckDecision(Request request, String expected) throws Exception {
201         //
202         // Ask for a decision
203         //
204         Response decision = service.makeNativeDecision(request);
205         //
206         // Check decision
207         //
208         checkDecision(expected, decision);
209     }
210
211     /**
212      * Check that decision matches expectation.
213      *
214      * @param expected from the response
215      * @param response received
216      * @throws Exception on errors checking the decision
217      *
218      **/
219     private void checkDecision(String expected, Response response) throws Exception {
220         LOGGER.info("Looking for {} Decision", expected);
221         assertThat(response).isNotNull();
222         Decision decision = response.getResults().iterator().next().getDecision();
223         assertThat(decision).isNotNull();
224         assertThat(decision).hasToString(expected);
225         LOGGER.info("Xacml response we received {}", DOMResponse.toString(response));
226     }
227 }