Fix trailing space in Info.yaml xacml
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / std / StdXacmlApplicationServiceProviderTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
4  * Modifications Copyright (C) 2024 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdp.xacml.application.common.std;
23
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.assertj.core.api.Assertions.assertThatThrownBy;
26 import static org.junit.jupiter.api.Assertions.assertEquals;
27 import static org.junit.jupiter.api.Assertions.assertFalse;
28 import static org.junit.jupiter.api.Assertions.assertNotNull;
29 import static org.junit.jupiter.api.Assertions.assertNull;
30 import static org.junit.jupiter.api.Assertions.assertSame;
31 import static org.junit.jupiter.api.Assertions.assertTrue;
32 import static org.mockito.ArgumentMatchers.any;
33 import static org.mockito.Mockito.lenient;
34 import static org.mockito.Mockito.mock;
35 import static org.mockito.Mockito.times;
36 import static org.mockito.Mockito.verify;
37
38 import com.att.research.xacml.api.Request;
39 import com.att.research.xacml.api.Response;
40 import com.att.research.xacml.api.pdp.PDPEngine;
41 import com.att.research.xacml.api.pdp.PDPEngineFactory;
42 import com.att.research.xacml.api.pdp.PDPException;
43 import com.att.research.xacml.util.FactoryException;
44 import com.att.research.xacml.util.XACMLProperties;
45 import com.google.common.io.Files;
46 import java.io.File;
47 import java.nio.file.Path;
48 import java.util.HashSet;
49 import java.util.Objects;
50 import java.util.Properties;
51 import java.util.Set;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
53 import org.apache.commons.lang3.tuple.Pair;
54 import org.junit.jupiter.api.AfterAll;
55 import org.junit.jupiter.api.BeforeAll;
56 import org.junit.jupiter.api.BeforeEach;
57 import org.junit.jupiter.api.Test;
58 import org.junit.jupiter.api.extension.ExtendWith;
59 import org.mockito.Mock;
60 import org.mockito.junit.jupiter.MockitoExtension;
61 import org.onap.policy.common.endpoints.http.client.HttpClient;
62 import org.onap.policy.models.decisions.concepts.DecisionRequest;
63 import org.onap.policy.models.decisions.concepts.DecisionResponse;
64 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
65 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
66 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyTranslator;
67 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
68 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
71
72 @ExtendWith(MockitoExtension.class)
73 class StdXacmlApplicationServiceProviderTest {
74     private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
75
76     private static final String TEMP_DIR_NAME = "src/test/resources/temp";
77     private static final File TEMP_DIR = new File(TEMP_DIR_NAME);
78     private static final Path TEMP_PATH = TEMP_DIR.toPath();
79     private static final File SOURCE_PROP_FILE = new File("src/test/resources/test.properties");
80     private static final File PROP_FILE = new File(TEMP_DIR, XacmlPolicyUtils.XACML_PROPERTY_FILE);
81     private static final String EXPECTED_EXCEPTION = "expected exception";
82     private static final String POLICY_NAME = "my-name";
83     private static final String POLICY_VERSION = "1.2.3";
84     private static final String POLICY_TYPE = "my-type";
85
86     @Mock
87     private HttpClient apiClient;
88
89     @Mock
90     private ToscaPolicyTranslator trans;
91
92     @Mock
93     private PDPEngineFactory engineFactory;
94
95     @Mock
96     private PDPEngine engine;
97
98     @Mock
99     private Request req;
100
101     @Mock
102     private Response resp;
103
104     private ToscaPolicy policy;
105
106     private StdXacmlApplicationServiceProvider prov;
107
108     /**
109      * Creates the temp directory.
110      */
111     @BeforeAll
112     static void setUpBeforeClass() {
113         assertTrue(TEMP_DIR.mkdir());
114     }
115
116     /**
117      * Deletes the temp directory and its contents.
118      */
119     @AfterAll
120     static void tearDownAfterClass() {
121         for (File file : Objects.requireNonNull(TEMP_DIR.listFiles())) {
122             if (!file.delete()) {
123                 logger.warn("cannot delete: {}", file);
124             }
125         }
126
127         if (!TEMP_DIR.delete()) {
128             logger.warn("cannot delete: {}", TEMP_DIR);
129         }
130     }
131
132     /**
133      * Initializes objects, including the provider.
134      *
135      * @throws Exception if an error occurs
136      */
137     @BeforeEach
138     void setUp() throws Exception {
139         policy = new ToscaPolicy();
140         policy.setType(POLICY_TYPE);
141         policy.setName(POLICY_NAME);
142         policy.setVersion(POLICY_VERSION);
143
144         PolicyType internalPolicy = new PolicyType();
145         internalPolicy.setPolicyId(POLICY_NAME);
146         internalPolicy.setVersion(POLICY_VERSION);
147
148         lenient().when(engineFactory.newEngine(any())).thenReturn(engine);
149
150         lenient().when(engine.decide(req)).thenReturn(resp);
151
152         lenient().when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
153
154         prov = new MyProv();
155
156         Files.copy(SOURCE_PROP_FILE, PROP_FILE);
157     }
158
159     @Test
160     void testApplicationName() {
161         assertNotNull(prov.applicationName());
162     }
163
164     @Test
165     void testActionDecisionsSupported() {
166         assertTrue(prov.actionDecisionsSupported().isEmpty());
167     }
168
169     @Test
170     void testInitialize_testGetXxx() throws XacmlApplicationException {
171         prov.initialize(TEMP_PATH, apiClient);
172
173         assertEquals(TEMP_PATH, prov.getDataPath());
174         assertNotNull(prov.getEngine());
175
176         Properties props = prov.getProperties();
177         assertEquals("rootstart", props.getProperty("xacml.rootPolicies"));
178     }
179
180     @Test
181     void testInitialize_Ex() {
182         assertThatThrownBy(() -> prov.initialize(new File(TEMP_DIR_NAME + "-nonExistent").toPath(), apiClient))
183             .isInstanceOf(XacmlApplicationException.class).hasMessage("Failed to load xacml.properties");
184     }
185
186     @Test
187     void testSupportedPolicyTypes() {
188         assertThat(prov.supportedPolicyTypes()).isEmpty();
189     }
190
191     @Test
192     void testCanSupportPolicyType() {
193         assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
194     }
195
196     @Test
197     void testLoadPolicy_ConversionError() throws ToscaPolicyConversionException {
198         lenient().when(trans.convertPolicy(policy)).thenReturn(null);
199
200         assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
201     }
202
203     @Test
204     void testLoadPolicy_testUnloadPolicy() throws Exception {
205         prov.initialize(TEMP_PATH, apiClient);
206         tryDeletePropFile();
207
208         final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
209
210         // Load policy
211         prov.loadPolicy(policy);
212
213         // policy file should have been created
214         File policyFile = new File(TEMP_DIR, "my-name_1.2.3.xml");
215         assertTrue(policyFile.exists());
216
217         // new property file should have been created
218         assertTrue(PROP_FILE.exists());
219
220         // should have re-created the engine
221         verify(engineFactory, times(2)).newEngine(any());
222
223         final Set<String> set2 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
224         assertEquals(set.size() + 1, set2.size());
225
226         Set<String> set3 = new HashSet<>(set2);
227         set3.removeAll(set);
228         assertEquals("[root1]", set3.toString());
229
230
231         /*
232          * Prepare for unload.
233          */
234         tryDeletePropFile();
235
236         assertTrue(prov.unloadPolicy(policy));
237
238         // policy file should have been removed
239         assertFalse(policyFile.exists());
240
241         // new property file should have been created
242         assertTrue(PROP_FILE.exists());
243
244         // should have re-created the engine
245         verify(engineFactory, times(3)).newEngine(any());
246
247         set3 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
248         assertEquals(set.toString(), set3.toString());
249     }
250
251     @Test
252     void testUnloadPolicy_NotDeployed() throws Exception {
253         prov.initialize(TEMP_PATH, apiClient);
254
255         assertFalse(prov.unloadPolicy(policy));
256
257         // no additional calls
258         verify(engineFactory, times(1)).newEngine(any());
259     }
260
261     @Test
262     void testMakeDecision() throws ToscaPolicyConversionException {
263         prov.createEngine(null);
264
265         DecisionRequest decreq = mock(DecisionRequest.class);
266         lenient().when(trans.convertRequest(decreq)).thenReturn(req);
267
268         DecisionResponse decresp = mock(DecisionResponse.class);
269         lenient().when(trans.convertResponse(resp)).thenReturn(decresp);
270
271         Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
272         assertSame(decresp, result.getKey());
273         assertSame(resp, result.getValue());
274
275         verify(trans).convertRequest(decreq);
276         verify(trans).convertResponse(resp);
277     }
278
279     @Test
280     void testGetTranslator() {
281         assertSame(trans, prov.getTranslator());
282     }
283
284     @Test
285     void testCreateEngine() throws FactoryException {
286         // success
287         prov.createEngine(null);
288         assertSame(engine, prov.getEngine());
289
290         // null - should be unchanged
291         lenient().when(engineFactory.newEngine(any())).thenReturn(null);
292         prov.createEngine(null);
293         assertSame(engine, prov.getEngine());
294
295         // exception - should be unchanged
296         lenient().when(engineFactory.newEngine(any())).thenThrow(new FactoryException(EXPECTED_EXCEPTION));
297         prov.createEngine(null);
298         assertSame(engine, prov.getEngine());
299     }
300
301     @Test
302     void testXacmlDecision() throws PDPException {
303         prov.createEngine(null);
304
305         // success
306         assertSame(resp, prov.xacmlDecision(req));
307
308         // exception
309         lenient().when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
310         assertNull(prov.xacmlDecision(req));
311     }
312
313     @Test
314     void testGetPdpEngineFactory() throws XacmlApplicationException {
315         // use the real engine factory
316         engineFactory = null;
317
318         prov = new MyProv();
319         prov.initialize(TEMP_PATH, apiClient);
320
321         assertNotNull(prov.getEngine());
322     }
323
324     private void tryDeletePropFile() {
325         if (!PROP_FILE.delete()) {
326             logger.warn("{} not deleted", PROP_FILE);
327         }
328     }
329
330     private class MyProv extends StdXacmlApplicationServiceProvider {
331
332         @Override
333         protected ToscaPolicyTranslator getTranslator(String type) {
334             return trans;
335         }
336
337         @Override
338         protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
339             return (engineFactory != null ? engineFactory : super.getPdpEngineFactory());
340         }
341     }
342 }