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