Fixing sonar issues in xacml-pdp
[policy/xacml-pdp.git] / applications / match / src / test / java / org / onap / policy / xacml / pdp / application / match / MatchPdpApplicationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2022 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.match;
25
26 import static org.assertj.core.api.Assertions.assertThat;
27
28 import com.att.research.xacml.api.Response;
29 import java.io.File;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
32 import java.nio.file.Files;
33 import java.nio.file.Paths;
34 import java.util.Map;
35 import java.util.Map.Entry;
36 import java.util.Properties;
37 import java.util.ServiceLoader;
38 import org.apache.commons.lang3.tuple.Pair;
39 import org.junit.BeforeClass;
40 import org.junit.ClassRule;
41 import org.junit.FixMethodOrder;
42 import org.junit.Test;
43 import org.junit.rules.TemporaryFolder;
44 import org.junit.runners.MethodSorters;
45 import org.onap.policy.common.utils.coder.CoderException;
46 import org.onap.policy.common.utils.coder.StandardCoder;
47 import org.onap.policy.common.utils.resources.ResourceUtils;
48 import org.onap.policy.common.utils.resources.TextFileUtils;
49 import org.onap.policy.models.decisions.concepts.DecisionRequest;
50 import org.onap.policy.models.decisions.concepts.DecisionResponse;
51 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
52 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
53 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
54 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
55 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
60 public class MatchPdpApplicationTest {
61     private static final Logger LOGGER = LoggerFactory.getLogger(MatchPdpApplicationTest.class);
62     private static Properties properties = new Properties();
63     private static File propertiesFile;
64     private static XacmlApplicationServiceProvider service;
65     private static StandardCoder gson = new StandardCoder();
66     private static DecisionRequest baseRequest;
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         //
79         // Load Single Decision Request
80         //
81         baseRequest = gson.decode(
82                 TextFileUtils
83                     .getTextFileAsString(
84                             "src/test/resources/decision.match.input.json"),
85                     DecisionRequest.class);
86         //
87         // Setup our temporary folder
88         //
89         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
90         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties",
91                 properties, myCreator);
92         //
93         // Copy the test policy types into data area
94         //
95         String policy = "onap.policies.match.Test";
96         String policyType = ResourceUtils.getResourceAsString("src/test/resources/" + policy + ".yaml");
97         LOGGER.info("Copying {}", policyType);
98         Files.write(Paths.get(policyFolder.getRoot().getAbsolutePath(), policy + "-1.0.0.yaml"),
99                 policyType.getBytes());
100         //
101         // Load service
102         //
103         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
104                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
105         //
106         // Iterate through Xacml application services and find
107         // the optimization service. Save it for use throughout
108         // all the Junit tests.
109         //
110         StringBuilder strDump = new StringBuilder("Loaded applications:" + XacmlPolicyUtils.LINE_SEPARATOR);
111         for (XacmlApplicationServiceProvider application : applicationLoader) {
112             //
113             // Is it our service?
114             //
115             if (application instanceof MatchPdpApplication) {
116                 //
117                 // Should be the first and only one
118                 //
119                 assertThat(service).isNull();
120                 service = application;
121             }
122             strDump.append(application.applicationName());
123             strDump.append(" supports ");
124             strDump.append(application.supportedPolicyTypes());
125             strDump.append(XacmlPolicyUtils.LINE_SEPARATOR);
126         }
127         LOGGER.debug("{}", strDump);
128         assertThat(service).isNotNull();
129         //
130         // Tell it to initialize based on the properties file
131         // we just built for it.
132         //
133         service.initialize(propertiesFile.toPath().getParent(), null);
134     }
135
136     @Test
137     public void test01Basics() {
138         //
139         // Make sure there's an application name
140         //
141         assertThat(service.applicationName()).isNotEmpty();
142         //
143         // Decisions
144         //
145         assertThat(service.actionDecisionsSupported()).hasSize(1);
146         assertThat(service.actionDecisionsSupported()).contains("match");
147         //
148         // Ensure it has the supported policy types and
149         // can support the correct policy types.
150         //
151         assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
152                 "onap.policies.match.Test", "1.0.0"))).isTrue();
153         assertThat(service.canSupportPolicyType(new ToscaConceptIdentifier(
154                 "onap.foobar", "1.0.0"))).isFalse();
155     }
156
157     @Test
158     public void test02NoPolicies() throws CoderException {
159         //
160         // Ask for a decision when there are no policies loaded
161         //
162         LOGGER.info("Request {}", gson.encode(baseRequest));
163         Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
164         LOGGER.info("Decision {}", decision.getKey());
165
166         assertThat(decision.getKey()).isNotNull();
167         assertThat(decision.getKey().getPolicies()).isEmpty();
168     }
169
170     @Test
171     public void test03Match() throws CoderException, FileNotFoundException, IOException,
172         XacmlApplicationException {
173         //
174         // Now load all the test match policies
175         //
176         TestUtils.loadPolicies("src/test/resources/test-match-policies.yaml", service);
177         //
178         // Ask for a decision
179         //
180         DecisionResponse response = makeDecision();
181         //
182         // There is no default policy
183         //
184         assertThat(response).isNotNull();
185         assertThat(response.getPolicies()).isEmpty();
186         //
187         // Match applications should not have this information returned
188         //
189         assertThat(response.getAdvice()).isNull();
190         assertThat(response.getObligations()).isNull();
191         assertThat(response.getAttributes()).isNull();
192         //
193         // Ask for foo
194         //
195         baseRequest.getResource().put("matchable", "foo");
196         //
197         // Get the decision
198         //
199         response = makeDecision();
200         assertThat(response).isNotNull();
201         assertThat(response.getPolicies()).hasSize(1);
202         //
203         // Match applications should not have this information returned
204         //
205         assertThat(response.getAdvice()).isNull();
206         assertThat(response.getObligations()).isNull();
207         assertThat(response.getAttributes()).isNull();
208         //
209         // Validate it
210         //
211         validateDecision(response, baseRequest, "value1");
212         //
213         // Ask for bar
214         //
215         baseRequest.getResource().put("matchable", "bar");
216         //
217         // Get the decision
218         //
219         response = makeDecision();
220         assertThat(response).isNotNull();
221         assertThat(response.getPolicies()).hasSize(1);
222         //
223         // Validate it
224         //
225         validateDecision(response, baseRequest, "value2");
226         //
227         // Ask for hello (should return nothing)
228         //
229         baseRequest.getResource().put("matchable", "hello");
230         //
231         // Get the decision
232         //
233         response = makeDecision();
234         assertThat(response).isNotNull();
235         assertThat(response.getPolicies()).isEmpty();
236     }
237
238     private DecisionResponse makeDecision() {
239         Pair<DecisionResponse, Response> decision = service.makeDecision(baseRequest, null);
240         LOGGER.info("Request Resources {}", baseRequest.getResource());
241         LOGGER.info("Decision {}", decision.getKey());
242         for (Entry<String, Object> entrySet : decision.getKey().getPolicies().entrySet()) {
243             LOGGER.info("Policy {}", entrySet.getKey());
244         }
245         return decision.getKey();
246     }
247
248     @SuppressWarnings("unchecked")
249     private void validateDecision(DecisionResponse decision, DecisionRequest request, String value) {
250         for (Entry<String, Object> entrySet : decision.getPolicies().entrySet()) {
251             LOGGER.info("Decision Returned Policy {}", entrySet.getKey());
252             assertThat(entrySet.getValue()).isInstanceOf(Map.class);
253             Map<String, Object> policyContents = (Map<String, Object>) entrySet.getValue();
254             assertThat(policyContents).containsKey("properties");
255             assertThat(policyContents.get("properties")).isInstanceOf(Map.class);
256             Map<String, Object> policyProperties = (Map<String, Object>) policyContents.get("properties");
257
258             assertThat(policyProperties.get("nonmatchable").toString()).hasToString(value);
259         }
260     }
261 }