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.event.comm.bus.internal.BusTopicParams;
62 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
63 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
64 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
65 import org.onap.policy.common.gson.GsonMessageBodyHandler;
66 import org.onap.policy.common.utils.coder.CoderException;
67 import org.onap.policy.common.utils.coder.StandardYamlCoder;
68 import org.onap.policy.common.utils.network.NetworkUtil;
69 import org.onap.policy.common.utils.resources.ResourceUtils;
70 import org.onap.policy.models.decisions.concepts.DecisionRequest;
71 import org.onap.policy.models.decisions.concepts.DecisionResponse;
72 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
73 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
74 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
75 import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
76 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
77 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
78 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
79 import org.slf4j.Logger;
80 import org.slf4j.LoggerFactory;
82 public class StdMatchableTranslatorTest {
84 private static final Logger logger = LoggerFactory.getLogger(StdMatchableTranslatorTest.class);
85 private static final String CLIENT_NAME = "policy-api";
86 private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
87 private static int port;
88 private static BusTopicParams clientParams;
89 private static ToscaServiceTemplate testTemplate;
92 public static final TemporaryFolder policyFolder = new TemporaryFolder();
95 * Initializes {@link #clientParams} and starts a simple REST server to handle the
98 * @throws IOException if an error occurs
101 public static void setUpBeforeClass() throws Exception {
102 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
103 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
105 // Setup our api server simulator
107 port = NetworkUtil.allocPort();
109 clientParams = mock(BusTopicParams.class);
110 when(clientParams.getHostname()).thenReturn("localhost");
111 when(clientParams.getPort()).thenReturn(port);
113 Properties props = new Properties();
114 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
116 final String svcpfx =
117 PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
119 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
120 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
121 Integer.toString(clientParams.getPort()));
122 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
123 ApiRestController.class.getName());
124 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
125 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
126 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
127 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
128 GsonMessageBodyHandler.class.getName());
130 HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
132 assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
134 // Load our test policy type
136 String policyYaml = ResourceUtils.getResourceAsString("matchable/onap.policies.Test-1.0.0.yaml");
138 // Serialize it into a class
140 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
142 // Make sure all the fields are setup properly
144 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
145 jtst.fromAuthorative(serviceTemplate);
146 testTemplate = jtst.toAuthorative();
148 // Make sure the Policy Types are there
150 assertEquals(3, testTemplate.getPolicyTypes().size());
151 assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.Base"));
152 assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.base.Middle"));
153 assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.base.middle.Test"));
154 logger.info("Test Policy Type {}{}", XacmlPolicyUtils.LINE_SEPARATOR, testTemplate);
158 public static void tearDownAfterClass() {
159 HttpServletServerFactoryInstance.getServerFactory().destroy();
163 public void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
165 // Create our translator
167 StdMatchableTranslator translator = new StdMatchableTranslator();
168 assertNotNull(translator);
172 translator.setPathForData(policyFolder.getRoot().toPath());
173 translator.setApiRestParameters(clientParams);
175 // Load policies to test
177 String policyYaml = ResourceUtils.getResourceAsString(
178 "src/test/resources/matchable/test.policies.input.tosca.yaml");
180 // Serialize it into a class
182 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
184 // Make sure all the fields are setup properly
186 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
187 jtst.fromAuthorative(serviceTemplate);
188 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
190 // Convert the policy
192 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
193 for (ToscaPolicy policy : policies.values()) {
195 // Test that we can convert the policy - assuming PolicyType
197 PolicyType translatedPolicy = (PolicyType) translator.convertPolicy(policy);
198 assertNotNull(translatedPolicy);
199 assertThat(translatedPolicy.getObligationExpressions().getObligationExpression()).hasSize(1);
200 logger.info("Translated policy {} {}", XacmlPolicyUtils.LINE_SEPARATOR, translatedPolicy);
202 // Shortcut to create an obligation, we are just going to steal
203 // the attributes from the translated policy.
205 List<AttributeAssignment> listAttributes = new ArrayList<>();
206 ObligationExpressionType xacmlObligation = translatedPolicy.getObligationExpressions()
207 .getObligationExpression().get(0);
208 assertThat(xacmlObligation.getAttributeAssignmentExpression()).hasSize(4);
210 // Copy into the list
212 xacmlObligation.getAttributeAssignmentExpression().forEach(assignment -> {
213 Object value = ((AttributeValueType) assignment.getExpression().getValue()).getContent().get(0);
214 listAttributes.add(TestUtilsCommon.createAttributeAssignment(assignment.getAttributeId(),
215 assignment.getCategory(), value));
218 // Pretend we got multiple policies to match a fictional request
220 Obligation obligation1 = TestUtilsCommon.createXacmlObligation(
221 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
223 Obligation obligation2 = TestUtilsCommon.createXacmlObligation(
224 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
227 // Should ignore this obligation
229 Obligation obligation3 = TestUtilsCommon.createXacmlObligation(
233 // Create a test XACML Response
235 Map<String, String> ids = new HashMap<>();
236 ids.put("onap.policies.Test", "1.0.0");
237 Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
239 com.att.research.xacml.api.Response xacmlResponse = TestUtilsCommon.createXacmlResponse(
240 StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT,
241 Arrays.asList(obligation1, obligation2, obligation3), policyIds);
245 DecisionResponse decisionResponse = translator.convertResponse(xacmlResponse);
246 assertNotNull(decisionResponse);
247 assertThat(decisionResponse.getPolicies()).hasSize(1);
251 // Test request decisions
253 DecisionRequest decisionRequest = new DecisionRequest();
254 decisionRequest.setAction("action");
255 decisionRequest.setOnapComponent("onap-component");
256 decisionRequest.setOnapName("onap");
257 Map<String, Object> resource = new HashMap<>();
258 resource.put("matchableString", "I should be matched");
259 decisionRequest.setResource(resource);
260 Request xacmlRequest = translator.convertRequest(decisionRequest);
261 assertNotNull(xacmlRequest);
262 assertThat(xacmlRequest.getRequestAttributes()).hasSize(3);
266 * Simple REST server to handle test requests.
269 @Path("/policy/api/v1")
270 @Produces({"application/json", "application/yaml"})
271 @Consumes({"application/json", "application/yaml"})
272 public static class ApiRestController {
275 * Retrieves the specified version of a particular policy type.
277 * @param policyTypeId ID of desired policy type
278 * @param versionId version of desired policy type
279 * @param requestId optional request ID
281 * @return the Response object containing the results of the API operation
284 @Path("/policytypes/{policyTypeId}/versions/{versionId}")
285 public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
286 @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
287 logger.info("request for policy type={} version={}", policyTypeId, versionId);
288 return Response.status(Response.Status.OK).entity(testTemplate).build();