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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pdp.xacml.application.common.std;
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;
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;
47 import java.nio.file.Path;
48 import java.util.HashSet;
49 import java.util.Objects;
50 import java.util.Properties;
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;
72 @ExtendWith(MockitoExtension.class)
73 class StdXacmlApplicationServiceProviderTest {
74 private static final Logger logger = LoggerFactory.getLogger(StdXacmlApplicationServiceProviderTest.class);
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";
87 private HttpClient apiClient;
90 private ToscaPolicyTranslator trans;
93 private PDPEngineFactory engineFactory;
96 private PDPEngine engine;
102 private Response resp;
104 private ToscaPolicy policy;
106 private StdXacmlApplicationServiceProvider prov;
109 * Creates the temp directory.
112 static void setUpBeforeClass() {
113 assertTrue(TEMP_DIR.mkdir());
117 * Deletes the temp directory and its contents.
120 static void tearDownAfterClass() {
121 for (File file : Objects.requireNonNull(TEMP_DIR.listFiles())) {
122 if (!file.delete()) {
123 logger.warn("cannot delete: {}", file);
127 if (!TEMP_DIR.delete()) {
128 logger.warn("cannot delete: {}", TEMP_DIR);
133 * Initializes objects, including the provider.
135 * @throws Exception if an error occurs
138 void setUp() throws Exception {
139 policy = new ToscaPolicy();
140 policy.setType(POLICY_TYPE);
141 policy.setName(POLICY_NAME);
142 policy.setVersion(POLICY_VERSION);
144 PolicyType internalPolicy = new PolicyType();
145 internalPolicy.setPolicyId(POLICY_NAME);
146 internalPolicy.setVersion(POLICY_VERSION);
148 lenient().when(engineFactory.newEngine(any())).thenReturn(engine);
150 lenient().when(engine.decide(req)).thenReturn(resp);
152 lenient().when(trans.convertPolicy(policy)).thenReturn(internalPolicy);
156 Files.copy(SOURCE_PROP_FILE, PROP_FILE);
160 void testApplicationName() {
161 assertNotNull(prov.applicationName());
165 void testActionDecisionsSupported() {
166 assertTrue(prov.actionDecisionsSupported().isEmpty());
170 void testInitialize_testGetXxx() throws XacmlApplicationException {
171 prov.initialize(TEMP_PATH, apiClient);
173 assertEquals(TEMP_PATH, prov.getDataPath());
174 assertNotNull(prov.getEngine());
176 Properties props = prov.getProperties();
177 assertEquals("rootstart", props.getProperty("xacml.rootPolicies"));
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");
187 void testSupportedPolicyTypes() {
188 assertThat(prov.supportedPolicyTypes()).isEmpty();
192 void testCanSupportPolicyType() {
193 assertThatThrownBy(() -> prov.canSupportPolicyType(null)).isInstanceOf(UnsupportedOperationException.class);
197 void testLoadPolicy_ConversionError() throws ToscaPolicyConversionException {
198 lenient().when(trans.convertPolicy(policy)).thenReturn(null);
200 assertThatThrownBy(() -> prov.loadPolicy(policy)).isInstanceOf(XacmlApplicationException.class);
204 void testLoadPolicy_testUnloadPolicy() throws Exception {
205 prov.initialize(TEMP_PATH, apiClient);
208 final Set<String> set = XACMLProperties.getRootPolicyIDs(prov.getProperties());
211 prov.loadPolicy(policy);
213 // policy file should have been created
214 File policyFile = new File(TEMP_DIR, "my-name_1.2.3.xml");
215 assertTrue(policyFile.exists());
217 // new property file should have been created
218 assertTrue(PROP_FILE.exists());
220 // should have re-created the engine
221 verify(engineFactory, times(2)).newEngine(any());
223 final Set<String> set2 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
224 assertEquals(set.size() + 1, set2.size());
226 Set<String> set3 = new HashSet<>(set2);
228 assertEquals("[root1]", set3.toString());
232 * Prepare for unload.
236 assertTrue(prov.unloadPolicy(policy));
238 // policy file should have been removed
239 assertFalse(policyFile.exists());
241 // new property file should have been created
242 assertTrue(PROP_FILE.exists());
244 // should have re-created the engine
245 verify(engineFactory, times(3)).newEngine(any());
247 set3 = XACMLProperties.getRootPolicyIDs(prov.getProperties());
248 assertEquals(set.toString(), set3.toString());
252 void testUnloadPolicy_NotDeployed() throws Exception {
253 prov.initialize(TEMP_PATH, apiClient);
255 assertFalse(prov.unloadPolicy(policy));
257 // no additional calls
258 verify(engineFactory, times(1)).newEngine(any());
262 void testMakeDecision() throws ToscaPolicyConversionException {
263 prov.createEngine(null);
265 DecisionRequest decreq = mock(DecisionRequest.class);
266 lenient().when(trans.convertRequest(decreq)).thenReturn(req);
268 DecisionResponse decresp = mock(DecisionResponse.class);
269 lenient().when(trans.convertResponse(resp)).thenReturn(decresp);
271 Pair<DecisionResponse, Response> result = prov.makeDecision(decreq, any());
272 assertSame(decresp, result.getKey());
273 assertSame(resp, result.getValue());
275 verify(trans).convertRequest(decreq);
276 verify(trans).convertResponse(resp);
280 void testGetTranslator() {
281 assertSame(trans, prov.getTranslator());
285 void testCreateEngine() throws FactoryException {
287 prov.createEngine(null);
288 assertSame(engine, prov.getEngine());
290 // null - should be unchanged
291 lenient().when(engineFactory.newEngine(any())).thenReturn(null);
292 prov.createEngine(null);
293 assertSame(engine, prov.getEngine());
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());
302 void testXacmlDecision() throws PDPException {
303 prov.createEngine(null);
306 assertSame(resp, prov.xacmlDecision(req));
309 lenient().when(engine.decide(req)).thenThrow(new PDPException(EXPECTED_EXCEPTION));
310 assertNull(prov.xacmlDecision(req));
314 void testGetPdpEngineFactory() throws XacmlApplicationException {
315 // use the real engine factory
316 engineFactory = null;
319 prov.initialize(TEMP_PATH, apiClient);
321 assertNotNull(prov.getEngine());
324 private void tryDeletePropFile() {
325 if (!PROP_FILE.delete()) {
326 logger.warn("{} not deleted", PROP_FILE);
330 private class MyProv extends StdXacmlApplicationServiceProvider {
333 protected ToscaPolicyTranslator getTranslator(String type) {
338 protected PDPEngineFactory getPdpEngineFactory() throws FactoryException {
339 return (engineFactory != null ? engineFactory : super.getPdpEngineFactory());