a6f0e944f699d16f7c6fb94799d4d502ebeba7e3
[policy/xacml-pdp.git] / tutorials / tutorial-xacml-application / src / test / java / org / onap / policy / tutorial / tutorial / TutorialApplicationTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020-2021 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  * ============LICENSE_END=========================================================
17  */
18
19 package org.onap.policy.tutorial.tutorial;
20
21 import static org.assertj.core.api.Assertions.assertThat;
22 import static org.junit.Assert.assertEquals;
23
24 import com.att.research.xacml.api.Response;
25 import com.att.research.xacml.api.XACML3;
26 import java.io.File;
27 import java.io.IOException;
28 import java.util.Map;
29 import java.util.Properties;
30 import java.util.ServiceLoader;
31 import org.apache.commons.lang3.tuple.Pair;
32 import org.junit.BeforeClass;
33 import org.junit.ClassRule;
34 import org.junit.Test;
35 import org.junit.rules.TemporaryFolder;
36 import org.onap.policy.common.utils.coder.CoderException;
37 import org.onap.policy.common.utils.coder.StandardCoder;
38 import org.onap.policy.common.utils.resources.TextFileUtils;
39 import org.onap.policy.models.decisions.concepts.DecisionRequest;
40 import org.onap.policy.models.decisions.concepts.DecisionResponse;
41 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationException;
42 import org.onap.policy.pdp.xacml.application.common.XacmlApplicationServiceProvider;
43 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
44 import org.onap.policy.pdp.xacml.xacmltest.TestUtils;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 public class TutorialApplicationTest {
49     private static final Logger LOGGER = LoggerFactory.getLogger(TutorialApplicationTest.class);
50     private static Properties properties = new Properties();
51     private static File propertiesFile;
52     private static XacmlApplicationServiceProvider service;
53     private static StandardCoder gson = new StandardCoder();
54
55     @ClassRule
56     public static final TemporaryFolder policyFolder = new TemporaryFolder();
57
58     /**
59      * setup the tests.
60      *
61      * @throws Exception Should not have exceptions thrown.
62      */
63     @BeforeClass
64     public static void setup() throws Exception {
65         //
66         // Setup our temporary folder
67         //
68         XacmlPolicyUtils.FileCreator myCreator = (String filename) -> policyFolder.newFile(filename);
69         propertiesFile = XacmlPolicyUtils.copyXacmlPropertiesContents("src/test/resources/xacml.properties", properties,
70                 myCreator);
71         //
72         // Load XacmlApplicationServiceProvider service
73         //
74         ServiceLoader<XacmlApplicationServiceProvider> applicationLoader =
75                 ServiceLoader.load(XacmlApplicationServiceProvider.class);
76         //
77         // Look for our class instance and save it
78         //
79         for (XacmlApplicationServiceProvider application : applicationLoader) {
80             //
81             // Is it our service?
82             //
83             if (application instanceof TutorialApplication) {
84                 service = application;
85             }
86         }
87         //
88         // Tell the application to initialize based on the properties file
89         // we just built for it.
90         //
91         service.initialize(propertiesFile.toPath().getParent(), null);
92         //
93         // Now load the tutorial policies.
94         //
95         TestUtils.loadPolicies("src/test/resources/tutorial-policies.yaml", service);
96     }
97
98     @Test
99     public void testSingleDecision() throws CoderException, XacmlApplicationException, IOException {
100         //
101         // Load a Decision request
102         //
103         DecisionRequest decisionRequest =
104                 gson.decode(TextFileUtils.getTextFileAsString("src/test/resources/tutorial-decision-request.json"),
105                         DecisionRequest.class);
106         LOGGER.info("{}", gson.encode(decisionRequest, true));
107         //
108         // Test a decision - should start with a permit
109         //
110         Pair<DecisionResponse, Response> decision = service.makeDecision(decisionRequest, null);
111         LOGGER.info("{}", gson.encode(decision.getLeft(), true));
112         assertEquals("Permit", decision.getLeft().getStatus());
113         //
114         // Check that there are attributes
115         //
116         assertThat(decision.getLeft().getAttributes()).isNotNull().hasSize(1)
117                 .containsKey(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
118         //
119         // This should be a deny
120         //
121         decisionRequest.getResource().put("user", "audit");
122         LOGGER.info("{}", gson.encode(decisionRequest, true));
123         decision = service.makeDecision(decisionRequest, null);
124         LOGGER.info("{}", gson.encode(decision.getLeft(), true));
125         assertEquals("Deny", decision.getLeft().getStatus());
126         //
127         // Check that there are attributes
128         //
129         assertThat(decision.getLeft().getAttributes()).isNotNull().hasSize(1)
130                 .containsKey(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
131     }
132
133
134     @Test
135     public void testMultiDecision() throws CoderException, XacmlApplicationException, IOException {
136         //
137         // Load a Decision request
138         //
139         DecisionRequest decisionRequest = gson.decode(
140                 TextFileUtils.getTextFileAsString("src/test/resources/tutorial-decision-multi-request.json"),
141                 DecisionRequest.class);
142         LOGGER.info("{}", gson.encode(decisionRequest, true));
143         //
144         // Test a decision - should start with a permit
145         //
146         Pair<DecisionResponse, Response> decision = service.makeDecision(decisionRequest, null);
147         LOGGER.info("{}", gson.encode(decision.getLeft(), true));
148         assertEquals("multi", decision.getLeft().getStatus());
149         //
150         // Check that there no attributes for the overall response
151         //
152         assertThat(decision.getLeft().getAttributes()).isNull();
153         //
154         // Check that there are 7 decisions with attributes
155         //
156         assertThat(decision.getLeft()).isInstanceOf(TutorialResponse.class);
157         TutorialResponse tutorialResponse = (TutorialResponse) decision.getLeft();
158         assertThat(tutorialResponse.getPermissions()).hasSize(7);
159         tutorialResponse.getPermissions().forEach(p -> checkPermission(p));
160     }
161
162     private void checkPermission(TutorialResponsePermission permission) {
163         assertThat(permission.getAttributes()).hasSize(1);
164         Object resourceAttributes = permission.getAttributes().get(XACML3.ID_ATTRIBUTE_CATEGORY_RESOURCE.stringValue());
165         assertThat(resourceAttributes).isNotNull().isInstanceOf(Map.class);
166         @SuppressWarnings("unchecked")
167         String multiId = ((Map<String, String>) resourceAttributes).get("urn:org:onap:tutorial-multi-id").toString();
168         assertThat(Integer.parseInt(multiId)).isBetween(1, 7);
169         switch (multiId) {
170             case "1":
171                 assertThat(permission.getStatus()).isEqualTo("Permit");
172                 return;
173             case "2":
174                 assertThat(permission.getStatus()).isEqualTo("Permit");
175                 return;
176             case "3":
177                 assertThat(permission.getStatus()).isEqualTo("Deny");
178                 return;
179             case "4":
180                 assertThat(permission.getStatus()).isEqualTo("Permit");
181                 return;
182             case "5":
183                 assertThat(permission.getStatus()).isEqualTo("Deny");
184                 return;
185             case "6":
186                 assertThat(permission.getStatus()).isEqualTo("Deny");
187                 return;
188             case "7":
189                 assertThat(permission.getStatus()).isEqualTo("Deny");
190                 return;
191             default:
192                 //
193                 // Should not get here as we check the value range in line 168.
194                 // But CodeStyle wants a default.
195                 //
196                 break;
197         }
198     }
199 }