1d2754b8e64814a27bd98ad9f3ed6a52384a95e1
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / std / StdMatchableTranslatorTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019-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  *
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.assertThat;
24 import static org.junit.Assert.assertEquals;
25 import static org.junit.Assert.assertNotNull;
26 import static org.junit.Assert.assertTrue;
27 import static org.mockito.Mockito.mock;
28 import static org.mockito.Mockito.when;
29
30 import com.att.research.xacml.api.AttributeAssignment;
31 import com.att.research.xacml.api.Decision;
32 import com.att.research.xacml.api.IdReference;
33 import com.att.research.xacml.api.Obligation;
34 import com.att.research.xacml.api.Request;
35 import com.att.research.xacml.std.StdStatusCode;
36 import java.io.IOException;
37 import java.text.ParseException;
38 import java.util.ArrayList;
39 import java.util.Arrays;
40 import java.util.Collection;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Properties;
45 import java.util.UUID;
46 import javax.ws.rs.Consumes;
47 import javax.ws.rs.GET;
48 import javax.ws.rs.HeaderParam;
49 import javax.ws.rs.Path;
50 import javax.ws.rs.PathParam;
51 import javax.ws.rs.Produces;
52 import javax.ws.rs.core.Response;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
56 import org.junit.AfterClass;
57 import org.junit.BeforeClass;
58 import org.junit.ClassRule;
59 import org.junit.Test;
60 import org.junit.rules.TemporaryFolder;
61 import org.onap.policy.common.endpoints.http.client.HttpClient;
62 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
63 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
64 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
65 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
66 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
67 import org.onap.policy.common.gson.GsonMessageBodyHandler;
68 import org.onap.policy.common.utils.coder.CoderException;
69 import org.onap.policy.common.utils.coder.StandardYamlCoder;
70 import org.onap.policy.common.utils.network.NetworkUtil;
71 import org.onap.policy.common.utils.resources.ResourceUtils;
72 import org.onap.policy.models.decisions.concepts.DecisionRequest;
73 import org.onap.policy.models.decisions.concepts.DecisionResponse;
74 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
75 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
76 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
77 import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
78 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
79 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
80 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
81 import org.slf4j.Logger;
82 import org.slf4j.LoggerFactory;
83
84 public class StdMatchableTranslatorTest {
85
86     private static final Logger logger = LoggerFactory.getLogger(StdMatchableTranslatorTest.class);
87     private static final String CLIENT_NAME = "policy-api";
88     private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
89     private static int port;
90     private static RestClientParameters clientParams;
91     private static ToscaServiceTemplate testTemplate;
92     private static HttpClient apiClient;
93
94     @ClassRule
95     public static final TemporaryFolder policyFolder = new TemporaryFolder();
96
97     /**
98      * Initializes {@link #clientParams} and starts a simple REST server to handle the
99      * test requests.
100      *
101      * @throws IOException if an error occurs
102      */
103     @BeforeClass
104     public static void setUpBeforeClass() throws Exception {
105         System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
106         System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
107         //
108         // Setup our api server simulator
109         //
110         port = NetworkUtil.allocPort();
111
112         clientParams = mock(RestClientParameters.class);
113         when(clientParams.getClientName()).thenReturn("apiClient");
114         when(clientParams.getHostname()).thenReturn("localhost");
115         when(clientParams.getPort()).thenReturn(port);
116
117         Properties props = new Properties();
118         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
119
120         final String svcpfx =
121                         PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
122
123         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
124         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
125                         Integer.toString(clientParams.getPort()));
126         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
127                         ApiRestController.class.getName());
128         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
129         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
130         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
131         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
132                         GsonMessageBodyHandler.class.getName());
133
134         HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
135         apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
136
137         assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
138         //
139         // Load our test policy type
140         //
141         String policyYaml = ResourceUtils.getResourceAsString("matchable/onap.policies.Test-1.0.0.yaml");
142         //
143         // Serialize it into a class
144         //
145         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
146         //
147         // Make sure all the fields are setup properly
148         //
149         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
150         jtst.fromAuthorative(serviceTemplate);
151         testTemplate = jtst.toAuthorative();
152         //
153         // Make sure the Policy Types are there
154         //
155         assertEquals(3, testTemplate.getPolicyTypes().size());
156         assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.Base"));
157         assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.base.Middle"));
158         assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.base.middle.Test"));
159         logger.info("Test Policy Type {}{}", XacmlPolicyUtils.LINE_SEPARATOR, testTemplate);
160     }
161
162     @AfterClass
163     public static void tearDownAfterClass() {
164         HttpServletServerFactoryInstance.getServerFactory().destroy();
165     }
166
167     @Test
168     public void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
169         //
170         // Create our translator
171         //
172         StdMatchableTranslator translator = new StdMatchableTranslator();
173         assertNotNull(translator);
174         //
175         // Set it up
176         //
177         translator.setPathForData(policyFolder.getRoot().toPath());
178         translator.setApiClient(apiClient);
179         //
180         // Load policies to test
181         //
182         String policyYaml = ResourceUtils.getResourceAsString(
183                 "src/test/resources/matchable/test.policies.input.tosca.yaml");
184         //
185         // Serialize it into a class
186         //
187         ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
188         //
189         // Make sure all the fields are setup properly
190         //
191         JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
192         jtst.fromAuthorative(serviceTemplate);
193         ToscaServiceTemplate completedJtst = jtst.toAuthorative();
194         //
195         // Convert the policy
196         //
197         for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
198             for (ToscaPolicy policy : policies.values()) {
199                 //
200                 // Test that we can convert the policy - assuming PolicyType
201                 //
202                 PolicyType translatedPolicy = (PolicyType) translator.convertPolicy(policy);
203                 assertNotNull(translatedPolicy);
204                 assertThat(translatedPolicy.getObligationExpressions().getObligationExpression()).hasSize(1);
205                 logger.info("Translated policy {} {}", XacmlPolicyUtils.LINE_SEPARATOR, translatedPolicy);
206                 //
207                 // Shortcut to create an obligation, we are just going to steal
208                 // the attributes from the translated policy.
209                 //
210                 List<AttributeAssignment> listAttributes = new ArrayList<>();
211                 ObligationExpressionType xacmlObligation = translatedPolicy.getObligationExpressions()
212                         .getObligationExpression().get(0);
213                 assertThat(xacmlObligation.getAttributeAssignmentExpression()).hasSize(4);
214                 //
215                 // Copy into the list
216                 //
217                 xacmlObligation.getAttributeAssignmentExpression().forEach(assignment -> {
218                     Object value = ((AttributeValueType) assignment.getExpression().getValue()).getContent().get(0);
219                     listAttributes.add(TestUtilsCommon.createAttributeAssignment(assignment.getAttributeId(),
220                             assignment.getCategory(), value));
221                 });
222                 //
223                 // Pretend we got multiple policies to match a fictional request
224                 //
225                 Obligation obligation1 = TestUtilsCommon.createXacmlObligation(
226                         ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
227                         listAttributes);
228                 Obligation obligation2 = TestUtilsCommon.createXacmlObligation(
229                         ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
230                         listAttributes);
231                 //
232                 // Should ignore this obligation
233                 //
234                 Obligation obligation3 = TestUtilsCommon.createXacmlObligation(
235                         "nobody:cares",
236                         listAttributes);
237                 //
238                 // Create a test XACML Response
239                 //
240                 Map<String, String> ids = new HashMap<>();
241                 ids.put("onap.policies.Test", "1.0.0");
242                 Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
243
244                 com.att.research.xacml.api.Response xacmlResponse = TestUtilsCommon.createXacmlResponse(
245                         StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT,
246                         Arrays.asList(obligation1, obligation2, obligation3), policyIds);
247                 //
248                 // Test the response
249                 //
250                 DecisionResponse decisionResponse = translator.convertResponse(xacmlResponse);
251                 assertNotNull(decisionResponse);
252                 assertThat(decisionResponse.getPolicies()).hasSize(1);
253             }
254         }
255         //
256         // Test request decisions
257         //
258         DecisionRequest decisionRequest = new DecisionRequest();
259         decisionRequest.setAction("action");
260         decisionRequest.setOnapComponent("onap-component");
261         decisionRequest.setOnapName("onap");
262         Map<String, Object> resource = new HashMap<>();
263         resource.put("matchableString", "I should be matched");
264         decisionRequest.setResource(resource);
265         Request xacmlRequest = translator.convertRequest(decisionRequest);
266         assertNotNull(xacmlRequest);
267         assertThat(xacmlRequest.getRequestAttributes()).hasSize(3);
268     }
269
270     /**
271      * Simple REST server to handle test requests.
272      */
273
274     @Path("/policy/api/v1")
275     @Produces({"application/json", "application/yaml"})
276     @Consumes({"application/json", "application/yaml"})
277     public static class ApiRestController {
278
279         /**
280          * Retrieves the specified version of a particular policy type.
281          *
282          * @param policyTypeId ID of desired policy type
283          * @param versionId version of desired policy type
284          * @param requestId optional request ID
285          *
286          * @return the Response object containing the results of the API operation
287          */
288         @GET
289         @Path("/policytypes/{policyTypeId}/versions/{versionId}")
290         public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
291                         @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
292             logger.info("request for policy type={} version={}", policyTypeId, versionId);
293             return Response.status(Response.Status.OK).entity(testTemplate).build();
294
295         }
296     }
297 }