2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
4 * Modifications Copyright (C) 2023 Nordix Foundation.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pdp.xacml.application.common.std;
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.when;
31 import com.att.research.xacml.api.AttributeAssignment;
32 import com.att.research.xacml.api.Decision;
33 import com.att.research.xacml.api.IdReference;
34 import com.att.research.xacml.api.Obligation;
35 import com.att.research.xacml.api.Request;
36 import com.att.research.xacml.std.StdStatusCode;
37 import jakarta.ws.rs.Consumes;
38 import jakarta.ws.rs.GET;
39 import jakarta.ws.rs.HeaderParam;
40 import jakarta.ws.rs.Path;
41 import jakarta.ws.rs.PathParam;
42 import jakarta.ws.rs.Produces;
43 import jakarta.ws.rs.core.Response;
44 import java.io.IOException;
45 import java.text.ParseException;
46 import java.util.ArrayList;
47 import java.util.Arrays;
48 import java.util.Collection;
49 import java.util.HashMap;
50 import java.util.List;
52 import java.util.Properties;
53 import java.util.UUID;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
57 import org.junit.AfterClass;
58 import org.junit.BeforeClass;
59 import org.junit.ClassRule;
60 import org.junit.Test;
61 import org.junit.rules.TemporaryFolder;
62 import org.onap.policy.common.endpoints.http.client.HttpClient;
63 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
64 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
65 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
66 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
67 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
68 import org.onap.policy.common.gson.GsonMessageBodyHandler;
69 import org.onap.policy.common.utils.coder.CoderException;
70 import org.onap.policy.common.utils.coder.StandardYamlCoder;
71 import org.onap.policy.common.utils.network.NetworkUtil;
72 import org.onap.policy.common.utils.resources.ResourceUtils;
73 import org.onap.policy.models.decisions.concepts.DecisionRequest;
74 import org.onap.policy.models.decisions.concepts.DecisionResponse;
75 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
76 import org.onap.policy.models.tosca.authorative.concepts.ToscaServiceTemplate;
77 import org.onap.policy.models.tosca.simple.concepts.JpaToscaServiceTemplate;
78 import org.onap.policy.pdp.xacml.application.common.TestUtilsCommon;
79 import org.onap.policy.pdp.xacml.application.common.ToscaDictionary;
80 import org.onap.policy.pdp.xacml.application.common.ToscaPolicyConversionException;
81 import org.onap.policy.pdp.xacml.application.common.XacmlPolicyUtils;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
85 public class StdMatchableTranslatorTest {
87 private static final Logger logger = LoggerFactory.getLogger(StdMatchableTranslatorTest.class);
88 private static final String CLIENT_NAME = "policy-api";
89 private static final StandardYamlCoder yamlCoder = new StandardYamlCoder();
90 private static int port;
91 private static RestClientParameters clientParams;
92 private static ToscaServiceTemplate testTemplate;
93 private static HttpClient apiClient;
96 public static final TemporaryFolder policyFolder = new TemporaryFolder();
99 * Initializes {@link #clientParams} and starts a simple REST server to handle the
102 * @throws IOException if an error occurs
105 public static void setUpBeforeClass() throws Exception {
106 System.setProperty("org.eclipse.jetty.util.log.class", "org.eclipse.jetty.util.log.StdErrLog");
107 System.setProperty("org.eclipse.jetty.LEVEL", "OFF");
109 // Setup our api server simulator
111 port = NetworkUtil.allocPort();
113 clientParams = mock(RestClientParameters.class);
114 when(clientParams.getClientName()).thenReturn("apiClient");
115 when(clientParams.getHostname()).thenReturn("localhost");
116 when(clientParams.getPort()).thenReturn(port);
118 Properties props = new Properties();
119 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
121 final String svcpfx =
122 PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
124 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
125 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
126 Integer.toString(clientParams.getPort()));
127 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
128 ApiRestController.class.getName());
129 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
130 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
131 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
132 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
133 GsonMessageBodyHandler.class.getName());
135 HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
136 apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
138 assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
140 // Load our test policy type
142 String policyYaml = ResourceUtils.getResourceAsString("matchable/onap.policies.Test-1.0.0.yaml");
144 // Serialize it into a class
146 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
148 // Make sure all the fields are setup properly
150 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
151 jtst.fromAuthorative(serviceTemplate);
152 testTemplate = jtst.toAuthorative();
154 // Make sure the Policy Types are there
156 assertEquals(3, testTemplate.getPolicyTypes().size());
157 assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.Base"));
158 assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.base.Middle"));
159 assertNotNull(testTemplate.getPolicyTypes().get("onap.policies.base.middle.Test"));
160 logger.info("Test Policy Type {}{}", XacmlPolicyUtils.LINE_SEPARATOR, testTemplate);
164 public static void tearDownAfterClass() {
165 HttpServletServerFactoryInstance.getServerFactory().destroy();
169 public void testMatchableTranslator() throws CoderException, ToscaPolicyConversionException, ParseException {
171 // Create our translator
173 StdMatchableTranslator translator = new StdMatchableTranslator();
174 assertNotNull(translator);
178 translator.setPathForData(policyFolder.getRoot().toPath());
179 translator.setApiClient(apiClient);
181 // Load policies to test
183 String policyYaml = ResourceUtils.getResourceAsString(
184 "src/test/resources/matchable/test.policies.input.tosca.yaml");
186 // Serialize it into a class
188 ToscaServiceTemplate serviceTemplate = yamlCoder.decode(policyYaml, ToscaServiceTemplate.class);
190 // Make sure all the fields are setup properly
192 JpaToscaServiceTemplate jtst = new JpaToscaServiceTemplate();
193 jtst.fromAuthorative(serviceTemplate);
194 ToscaServiceTemplate completedJtst = jtst.toAuthorative();
196 // Convert the policy
198 for (Map<String, ToscaPolicy> policies : completedJtst.getToscaTopologyTemplate().getPolicies()) {
199 for (ToscaPolicy policy : policies.values()) {
201 // Test that we can convert the policy - assuming PolicyType
203 PolicyType translatedPolicy = (PolicyType) translator.convertPolicy(policy);
204 assertNotNull(translatedPolicy);
205 assertThat(translatedPolicy.getObligationExpressions().getObligationExpression()).hasSize(1);
206 logger.info("Translated policy {} {}", XacmlPolicyUtils.LINE_SEPARATOR, translatedPolicy);
208 // Shortcut to create an obligation, we are just going to steal
209 // the attributes from the translated policy.
211 List<AttributeAssignment> listAttributes = new ArrayList<>();
212 ObligationExpressionType xacmlObligation = translatedPolicy.getObligationExpressions()
213 .getObligationExpression().get(0);
214 assertThat(xacmlObligation.getAttributeAssignmentExpression()).hasSize(4);
216 // Copy into the list
218 xacmlObligation.getAttributeAssignmentExpression().forEach(assignment -> {
219 Object value = ((AttributeValueType) assignment.getExpression().getValue()).getContent().get(0);
220 listAttributes.add(TestUtilsCommon.createAttributeAssignment(assignment.getAttributeId(),
221 assignment.getCategory(), value));
224 // Pretend we got multiple policies to match a fictional request
226 Obligation obligation1 = TestUtilsCommon.createXacmlObligation(
227 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
229 Obligation obligation2 = TestUtilsCommon.createXacmlObligation(
230 ToscaDictionary.ID_OBLIGATION_REST_BODY.stringValue(),
233 // Should ignore this obligation
235 Obligation obligation3 = TestUtilsCommon.createXacmlObligation(
239 // Create a test XACML Response
241 Map<String, String> ids = new HashMap<>();
242 ids.put("onap.policies.Test", "1.0.0");
243 Collection<IdReference> policyIds = TestUtilsCommon.createPolicyIdList(ids);
245 com.att.research.xacml.api.Response xacmlResponse = TestUtilsCommon.createXacmlResponse(
246 StdStatusCode.STATUS_CODE_OK, null, Decision.PERMIT,
247 Arrays.asList(obligation1, obligation2, obligation3), policyIds);
251 DecisionResponse decisionResponse = translator.convertResponse(xacmlResponse);
252 assertNotNull(decisionResponse);
253 assertThat(decisionResponse.getPolicies()).hasSize(1);
257 // Test request decisions
259 DecisionRequest decisionRequest = new DecisionRequest();
260 decisionRequest.setAction("action");
261 decisionRequest.setOnapComponent("onap-component");
262 decisionRequest.setOnapName("onap");
263 Map<String, Object> resource = new HashMap<>();
264 resource.put("matchableString", "I should be matched");
265 decisionRequest.setResource(resource);
266 Request xacmlRequest = translator.convertRequest(decisionRequest);
267 assertNotNull(xacmlRequest);
268 assertThat(xacmlRequest.getRequestAttributes()).hasSize(3);
272 * Simple REST server to handle test requests.
275 @Path("/policy/api/v1")
276 @Produces({"application/json", "application/yaml"})
277 @Consumes({"application/json", "application/yaml"})
278 public static class ApiRestController {
281 * Retrieves the specified version of a particular policy type.
283 * @param policyTypeId ID of desired policy type
284 * @param versionId version of desired policy type
285 * @param requestId optional request ID
287 * @return the Response object containing the results of the API operation
290 @Path("/policytypes/{policyTypeId}/versions/{versionId}")
291 public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
292 @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
293 logger.info("request for policy type={} version={}", policyTypeId, versionId);
294 return Response.status(Response.Status.OK).entity(testTemplate).build();