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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.pdp.xacml.application.common.std;
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;
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;
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;
84 public class StdMatchableTranslatorTest {
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;
95 public static final TemporaryFolder policyFolder = new TemporaryFolder();
98 * Initializes {@link #clientParams} and starts a simple REST server to handle the
101 * @throws IOException if an error occurs
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");
108 // Setup our api server simulator
110 port = NetworkUtil.allocPort();
112 clientParams = mock(RestClientParameters.class);
113 when(clientParams.getClientName()).thenReturn("apiClient");
114 when(clientParams.getHostname()).thenReturn("localhost");
115 when(clientParams.getPort()).thenReturn(port);
117 Properties props = new Properties();
118 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
120 final String svcpfx =
121 PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
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());
134 HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
135 apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
137 assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
139 // Load our test policy type
141 String policyYaml = ResourceUtils.getResourceAsString("matchable/onap.policies.Test-1.0.0.yaml");
143 // Serialize it into a class
145 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
147 // Make sure all the fields are setup properly
149 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
150 jtst.fromAuthorative(serviceTemplate);
151 testTemplate = jtst.toAuthorative();
153 // Make sure the Policy Types are there
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);
163 public static void tearDownAfterClass() {
164 HttpServletServerFactoryInstance.getServerFactory().destroy();
168 public void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
170 // Create our translator
172 StdMatchableTranslator translator = new StdMatchableTranslator();
173 assertNotNull(translator);
177 translator.setPathForData(policyFolder.getRoot().toPath());
178 translator.setApiClient(apiClient);
180 // Load policies to test
182 String policyYaml = ResourceUtils.getResourceAsString(
183 "src/test/resources/matchable/test.policies.input.tosca.yaml");
185 // Serialize it into a class
187 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
189 // Make sure all the fields are setup properly
191 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
192 jtst.fromAuthorative(serviceTemplate);
193 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
195 // Convert the policy
197 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
198 for (ToscaPolicy policy : policies.values()) {
200 // Test that we can convert the policy - assuming PolicyType
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);
207 // Shortcut to create an obligation, we are just going to steal
208 // the attributes from the translated policy.
210 List<AttributeAssignment> listAttributes = new ArrayList<>();
211 ObligationExpressionType xacmlObligation = translatedPolicy.getObligationExpressions()
212 .getObligationExpression().get(0);
213 assertThat(xacmlObligation.getAttributeAssignmentExpression()).hasSize(4);
215 // Copy into the list
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));
223 // Pretend we got multiple policies to match a fictional request
225 Obligation obligation1 = TestUtilsCommon.createXacmlObligation(
226 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
228 Obligation obligation2 = TestUtilsCommon.createXacmlObligation(
229 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
232 // Should ignore this obligation
234 Obligation obligation3 = TestUtilsCommon.createXacmlObligation(
238 // Create a test XACML Response
240 Map<String, String> ids = new HashMap<>();
241 ids.put("onap.policies.Test", "1.0.0");
242 Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
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);
250 DecisionResponse decisionResponse = translator.convertResponse(xacmlResponse);
251 assertNotNull(decisionResponse);
252 assertThat(decisionResponse.getPolicies()).hasSize(1);
256 // Test request decisions
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);
271 * Simple REST server to handle test requests.
274 @Path("/policy/api/v1")
275 @Produces({"application/json", "application/yaml"})
276 @Consumes({"application/json", "application/yaml"})
277 public static class ApiRestController {
280 * Retrieves the specified version of a particular policy type.
282 * @param policyTypeId ID of desired policy type
283 * @param versionId version of desired policy type
284 * @param requestId optional request ID
286 * @return the Response object containing the results of the API operation
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();