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