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