2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 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.server.HttpServletServer;
62 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
63 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
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.ToscaPolicyType;
74 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
75 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
76 import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
77 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
78 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
79 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
83 public class StdMatchableTranslatorTest {
85 private static final Logger logger = LoggerFactory.getLogger(StdMatchableTranslatorTest.class);
86 private static final String CLIENT_NAME = "policy-api";
87 private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
88 private static int port;
89 private static RestServerParameters clientParams;
90 private static ToscaPolicyType testPolicyType;
93 public static final TemporaryFolder policyFolder = new TemporaryFolder();
96 * Initializes {@link #clientParams} and starts a simple REST server to handle the
99 * @throws IOException if an error occurs
102 public static void setUpBeforeClass() throws Exception {
103 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
104 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
106 // Setup our api server simulator
108 port = NetworkUtil.allocPort();
110 clientParams = mock(RestServerParameters.class);
111 when(clientParams.getHost()).thenReturn("localhost");
112 when(clientParams.getPort()).thenReturn(port);
114 Properties props = new Properties();
115 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
117 final String svcpfx =
118 PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
120 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHost());
121 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
122 Integer.toString(clientParams.getPort()));
123 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
124 ApiRestController.class.getName());
125 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
126 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
127 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
128 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
129 GsonMessageBodyHandler.class.getName());
131 HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
133 assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHost(), clientParams.getPort(), 100, 100));
135 // Load our test policy type
137 String policyYaml = ResourceUtils.getResourceAsString("matchable/onap.policies.Test-1.0.0.yaml");
139 // Serialize it into a class
141 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
143 // Make sure all the fields are setup properly
145 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
146 jtst.fromAuthorative(serviceTemplate);
147 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
149 // Find the Policy Type - SHOULD only be one
151 assertEquals(1, completedJtst.getPolicyTypes().size());
152 testPolicyType = completedJtst.getPolicyTypes().get("onap.policies.Test");
153 assertNotNull(testPolicyType);
154 logger.info("Test Policy Type {}{}", XacmlPolicyUtils.LINE_SEPARATOR, testPolicyType);
158 public static void tearDownAfterClass() {
159 HttpServletServerFactoryInstance.getServerFactory().destroy();
163 public void test() 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()) {
194 PolicyType translatedPolicy = translator.convertPolicy(policy);
195 assertNotNull(translatedPolicy);
196 assertThat(translatedPolicy.getObligationExpressions().getObligationExpression()).hasSize(1);
197 logger.info("Translated policy {} {}", XacmlPolicyUtils.LINE_SEPARATOR, translatedPolicy);
199 // Shortcut to create an obligation, we are just going to steal
200 // the attributes from the translated policy.
202 List<AttributeAssignment> listAttributes = new ArrayList<>();
203 ObligationExpressionType xacmlObligation = translatedPolicy.getObligationExpressions()
204 .getObligationExpression().get(0);
205 assertThat(xacmlObligation.getAttributeAssignmentExpression()).hasSize(4);
207 // Copy into the list
209 xacmlObligation.getAttributeAssignmentExpression().forEach(assignment -> {
210 Object value = ((AttributeValueType) assignment.getExpression().getValue()).getContent().get(0);
211 listAttributes.add(TestUtilsCommon.createAttributeAssignment(assignment.getAttributeId(),
212 assignment.getCategory(), value));
215 // Pretend we got multiple policies to match a fictional request
217 Obligation obligation1 = TestUtilsCommon.createXacmlObligation(
218 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
220 Obligation obligation2 = TestUtilsCommon.createXacmlObligation(
221 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
224 // Should ignore this obligation
226 Obligation obligation3 = TestUtilsCommon.createXacmlObligation(
230 // Create a test XACML Response
232 Map<String, String> ids = new HashMap<>();
233 ids.put("onap.policies.Test", "1.0.0");
234 Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
236 com.att.research.xacml.api.Response xacmlResponse = TestUtilsCommon.createXacmlResponse(
237 StdStatusCode.STATUS_CODE_OK, Decision.PERMIT,
238 Arrays.asList(obligation1, obligation2, obligation3), policyIds);
242 DecisionResponse decisionResponse = translator.convertResponse(xacmlResponse);
243 assertNotNull(decisionResponse);
244 assertThat(decisionResponse.getPolicies()).hasSize(1);
248 // Test request decisions
250 DecisionRequest decisionRequest = new DecisionRequest();
251 decisionRequest.setAction("action");
252 decisionRequest.setOnapComponent("onap-component");
253 decisionRequest.setOnapName("onap");
254 Map<String, Object> resource = new HashMap<>();
255 resource.put("matchableString", "I should be matched");
256 decisionRequest.setResource(resource);
257 Request xacmlRequest = translator.convertRequest(decisionRequest);
258 assertNotNull(xacmlRequest);
259 assertThat(xacmlRequest.getRequestAttributes()).hasSize(3);
263 * Simple REST server to handle test requests.
266 @Path("/policy/api/v1")
267 @Produces({"application/json", "application/yaml"})
268 @Consumes({"application/json", "application/yaml"})
269 public static class ApiRestController {
272 * Retrieves the specified version of a particular policy type.
274 * @param policyTypeId ID of desired policy type
275 * @param versionId version of desired policy type
276 * @param requestId optional request ID
278 * @return the Response object containing the results of the API operation
281 @Path("/policytypes/{policyTypeId}/versions/{versionId}")
282 public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
283 @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
284 logger.info("request for policy type={} version={}", policyTypeId, versionId);
285 return Response.status(Response.Status.OK).entity(testPolicyType).build();