diff options
author | mmis <michael.morris@ericsson.com> | 2018-08-27 23:29:24 +0100 |
---|---|---|
committer | mmis <michael.morris@ericsson.com> | 2018-08-30 16:52:30 +0100 |
commit | de6124af19910e5ebb1de6698843b8ab64b5931a (patch) | |
tree | 0a7ecfa5c8199e01108345bbd8957db46441b59d /plugins/forwarding-plugins | |
parent | e705197bb18af558fb7ea853b01e1297521763f2 (diff) |
Create code infrastructure for policy forwarding
Added sending of polices from the policy forwarder to the xacml PDP and
added handling of parameters for configuring the policy forwarders
Issue-ID: POLICY-926
Change-Id: I26effe70769f7edc765470a1a9ad40ed9faad82d
Signed-off-by: mmis <michael.morris@ericsson.com>
Diffstat (limited to 'plugins/forwarding-plugins')
10 files changed, 1002 insertions, 10 deletions
diff --git a/plugins/forwarding-plugins/pom.xml b/plugins/forwarding-plugins/pom.xml index 24985bbe..006caa95 100644 --- a/plugins/forwarding-plugins/pom.xml +++ b/plugins/forwarding-plugins/pom.xml @@ -36,5 +36,25 @@ <artifactId>forwarding</artifactId> <version>${project.version}</version> </dependency> + <dependency> + <groupId>org.onap.policy.distribution</groupId> + <artifactId>main</artifactId> + <version>${project.version}</version> + </dependency> + <dependency> + <groupId>org.onap.policy.engine</groupId> + <artifactId>PolicyEngineAPI</artifactId> + <version>1.3.0-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>com.thoughtworks</groupId> + <artifactId>web-stub</artifactId> + <version>1.1.0</version> + </dependency> + <dependency> + <groupId>org.mockito</groupId> + <artifactId>mockito-all</artifactId> + <scope>test</scope> + </dependency> </dependencies> </project> diff --git a/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyAdapter.java b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyAdapter.java new file mode 100644 index 00000000..c50eac12 --- /dev/null +++ b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyAdapter.java @@ -0,0 +1,53 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp; + +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.distribution.model.Policy; + +/** + * Adapts {@link Policy} objects to objects compatible with the XACML PDP API. + */ +public interface XacmlPdpPolicyAdapter<T extends Policy> { + + /** + * Get the policy. + * + * @return the policy + */ + T getPolicy(); + + /** + * Get as a {@link PolicyParameters} object. + * + * @returna {@link PolicyParameters} object + */ + PolicyParameters getAsPolicyParameters(); + + /** + * Get as a {@link PushPolicyParameters} object. + * + * @returna {@link PushPolicyParameters} object + */ + PushPolicyParameters getAsPushPolicyParameters(final String pdpGroups); + +} diff --git a/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyForwarder.java b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyForwarder.java new file mode 100644 index 00000000..30d8f3ae --- /dev/null +++ b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyForwarder.java @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp; + +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.util.Collection; +import java.util.Collections; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.distribution.forwarding.PolicyForwarder; +import org.onap.policy.distribution.forwarding.xacml.pdp.adapters.XacmlPdpOptimizationPolicyAdapter; +import org.onap.policy.distribution.model.OptimizationPolicy; +import org.onap.policy.distribution.model.Policy; +import org.springframework.http.HttpStatus; + +/** + * Forwards policies to the XACML PDP. + */ +public class XacmlPdpPolicyForwarder implements PolicyForwarder { + + private static final Logger LOGGER = FlexLogger.getLogger(XacmlPdpPolicyForwarder.class); + private static final String BASE_PATH = "pdp/api/"; + + private XacmlPdpPolicyForwarderParameterGroup configurationParameters = null; + + + @Override + public void forward(final Collection<Policy> policies) { + for (Policy policy : policies) { + forward(policy); + } + } + + private void forward(Policy policy) { + XacmlPdpPolicyAdapter<?> policyAdapter = getXacmlPdpPolicyAdapter(policy); + + if (policyAdapter == null) { + LOGGER.error("Cannot forward policy " + policy + ". Unsupported policy type " + + policy.getClass().getSimpleName()); + return; + } + + boolean policyCreated = createPolicy(policyAdapter); + if (policyCreated) { + pushPolicy(policyAdapter); + } + } + + private XacmlPdpPolicyAdapter<?> getXacmlPdpPolicyAdapter(Policy policy) { + if (policy instanceof OptimizationPolicy) { + return new XacmlPdpOptimizationPolicyAdapter((OptimizationPolicy) policy); + } + return null; + } + + private boolean createPolicy(XacmlPdpPolicyAdapter<?> policyAdapter) { + PolicyParameters policyParameters = policyAdapter.getAsPolicyParameters(); + Entity<PolicyParameters> entity = Entity.entity(policyParameters, MediaType.APPLICATION_JSON); + + return invokeHttpClient(entity, "createPolicy", policyAdapter.getPolicy().getPolicyName()); + } + + private boolean pushPolicy(XacmlPdpPolicyAdapter<?> policyAdapter) { + PushPolicyParameters pushPolicyParameters = + policyAdapter.getAsPushPolicyParameters(configurationParameters.getPdpGroup()); + Entity<PushPolicyParameters> entity = Entity.entity(pushPolicyParameters, MediaType.APPLICATION_JSON); + + return invokeHttpClient(entity, "pushPolicy", policyAdapter.getPolicy().getPolicyName()); + } + + private boolean invokeHttpClient(final Entity<?> entity, final String method, final String policyName) { + + try { + Response response = getHttpClient().put(method, entity, + Collections.singletonMap("ClientAuth", configurationParameters.getClientAuth())); + + if (response.getStatus() != HttpStatus.OK.value()) { + LOGGER.error( + "Invocation of method " + method + " failed for policy " + policyName + ". Response status: " + + response.getStatus() + ", Response status info: " + response.getStatusInfo()); + return false; + } + } catch (KeyManagementException | NoSuchAlgorithmException exception) { + LOGGER.error("Invocation of method " + method + " failed for policy " + policyName + + " due to error opening Http client", exception); + return false; + } + return true; + } + + private HttpClient getHttpClient() throws KeyManagementException, NoSuchAlgorithmException { + boolean useHttps = configurationParameters.isUseHttps(); + String hostname = configurationParameters.getHostname(); + int port = configurationParameters.getPort(); + String userName = configurationParameters.getUserName(); + String password = configurationParameters.getPassword(); + boolean managed = configurationParameters.isManaged(); + BusTopicParams params = BusTopicParams.builder().clientName("SDC Dist").useHttps(useHttps).hostname(hostname) + .port(port).userName(userName).password(password).basePath(BASE_PATH).managed(managed).build(); + return HttpClient.factory.build(params); + } + + @Override + public void configure(String parameterGroupName) { + configurationParameters = ParameterService.get(parameterGroupName); + } + +} diff --git a/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyForwarderParameterGroup.java b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyForwarderParameterGroup.java new file mode 100644 index 00000000..e72e64ae --- /dev/null +++ b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/XacmlPdpPolicyForwarderParameterGroup.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp; + +import org.onap.policy.common.parameters.GroupValidationResult; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.common.utils.validation.ParameterValidationUtils; +import org.onap.policy.distribution.main.parameters.PolicyForwarderConfigurationParameterGroup; + +/** + * Holds the parameters for the{@link XacmlPdpPolicyForwarder} + */ +public class XacmlPdpPolicyForwarderParameterGroup extends PolicyForwarderConfigurationParameterGroup { + + public static final String POLICY_FORWARDER_PLUGIN_CLASS = XacmlPdpPolicyForwarder.class.getCanonicalName(); + + private boolean useHttps; + private String hostname; + private int port; + private String userName; + private String password; + private String clientAuth; + private boolean isManaged; + private String pdpGroup; + + public boolean isUseHttps() { + return useHttps; + } + + public String getHostname() { + return hostname; + } + + public int getPort() { + return port; + } + + public String getUserName() { + return userName; + } + + public String getPassword() { + return password; + } + + public String getClientAuth() { + return clientAuth; + } + + public boolean isManaged() { + return isManaged; + } + + public String getPdpGroup() { + return pdpGroup; + } + + /** + * Builder for XacmlPdpPolicyForwarderParameterGroup. + */ + public static class XacmlPdpPolicyForwarderParameterGroupBuilder { + private boolean useHttps = false; + private String hostname; + private int port; + private String userName; + private String password; + private String clientAuth; + private boolean isManaged = true; + private String pdpGroup; + + public XacmlPdpPolicyForwarderParameterGroupBuilder setUseHttps(final boolean useHttps) { + this.useHttps = useHttps; + return this; + } + + public XacmlPdpPolicyForwarderParameterGroupBuilder setHostname(final String hostname) { + this.hostname = hostname; + return this; + } + + public XacmlPdpPolicyForwarderParameterGroupBuilder setPort(final int port) { + this.port = port; + return this; + } + + public XacmlPdpPolicyForwarderParameterGroupBuilder setUserName(final String userName) { + this.userName = userName; + return this; + } + + public XacmlPdpPolicyForwarderParameterGroupBuilder setPassword(final String password) { + this.password = password; + return this; + } + + public XacmlPdpPolicyForwarderParameterGroupBuilder setClientAuth(final String clientAuth) { + this.clientAuth = clientAuth; + return this; + } + + public XacmlPdpPolicyForwarderParameterGroupBuilder setIsManaged(final boolean isManaged) { + this.isManaged = isManaged; + return this; + } + + public XacmlPdpPolicyForwarderParameterGroupBuilder setPdpGroup(final String pdpGroup) { + this.pdpGroup = pdpGroup; + return this; + } + + /** + * Creates a new XacmlPapServletPolicyForwarderParameterGroup instance. + */ + public XacmlPdpPolicyForwarderParameterGroup build() { + return new XacmlPdpPolicyForwarderParameterGroup(this); + } + } + + /** + * Construct an instance + * + * @param builder the builder create the instance from + */ + private XacmlPdpPolicyForwarderParameterGroup(final XacmlPdpPolicyForwarderParameterGroupBuilder builder) { + this.useHttps = builder.useHttps; + this.hostname = builder.hostname; + this.port = builder.port; + this.userName = builder.userName; + this.password = builder.password; + this.clientAuth = builder.clientAuth; + this.isManaged = builder.isManaged; + this.pdpGroup = builder.pdpGroup; + } + + @Override + public GroupValidationResult validate() { + final GroupValidationResult validationResult = new GroupValidationResult(this); + if (!ParameterValidationUtils.validateStringParameter(hostname)) { + validationResult.setResult("hostname", ValidationStatus.INVALID, + "must be a non-blank string containing hostname/ipaddress"); + } + if (!ParameterValidationUtils.validateIntParameter(port)) { + validationResult.setResult("port", ValidationStatus.INVALID, "must be a positive integer containing port"); + } + if (!ParameterValidationUtils.validateStringParameter(userName)) { + validationResult.setResult("userName", ValidationStatus.INVALID, + "must be a non-blank string containing userName"); + } + if (!ParameterValidationUtils.validateStringParameter(password)) { + validationResult.setResult("password", ValidationStatus.INVALID, + "must be a non-blank string containing password"); + } + if (!ParameterValidationUtils.validateStringParameter(clientAuth)) { + validationResult.setResult("clientAuth", ValidationStatus.INVALID, + "must be a non-blank string containing clientAuth"); + } + if (!ParameterValidationUtils.validateStringParameter(pdpGroup)) { + validationResult.setResult("pdpGroup", ValidationStatus.INVALID, + "must be a non-blank string containing pdpGroup"); + } + return validationResult; + } + +} diff --git a/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/adapters/AbstractXacmlPdpPolicyAdapter.java b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/adapters/AbstractXacmlPdpPolicyAdapter.java new file mode 100644 index 00000000..c1365166 --- /dev/null +++ b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/adapters/AbstractXacmlPdpPolicyAdapter.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp.adapters; + +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.distribution.forwarding.xacml.pdp.XacmlPdpPolicyAdapter; +import org.onap.policy.distribution.model.Policy; + +/** + * Base class for {@link XacmlPdpPolicyAdapter} implementations. + * + * @param <T> the type of policy the adapter handles + */ +public abstract class AbstractXacmlPdpPolicyAdapter<T extends Policy> implements XacmlPdpPolicyAdapter<T> { + + private T policy; + + protected AbstractXacmlPdpPolicyAdapter(T policy) { + this.policy = policy; + } + + @Override + public T getPolicy() { + return policy; + } + + @Override + public PushPolicyParameters getAsPushPolicyParameters(String pdpGroups) { + PushPolicyParameters pushPolicyParameters = new PushPolicyParameters(); + pushPolicyParameters.setPolicyName(policy.getPolicyName()); + pushPolicyParameters.setPolicyType(policy.getPolicyType()); + pushPolicyParameters.setPdpGroup(pdpGroups); + return pushPolicyParameters; + } + +} diff --git a/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/adapters/XacmlPdpOptimizationPolicyAdapter.java b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/adapters/XacmlPdpOptimizationPolicyAdapter.java new file mode 100644 index 00000000..1ec654fa --- /dev/null +++ b/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/xacml/pdp/adapters/XacmlPdpOptimizationPolicyAdapter.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp.adapters; + +import org.onap.policy.api.PolicyConfigType; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.distribution.model.OptimizationPolicy; + +/** + * Adapts {@link OptimizationPolicy} objects to objects compatible with the XACML PDP API. + */ +public class XacmlPdpOptimizationPolicyAdapter extends AbstractXacmlPdpPolicyAdapter<OptimizationPolicy> { + + /** + * Create an instance to adapt the given {@link OptimizationPolicy}. + * + * @param optimizationPolicy the {@link OptimizationPolicy} to be adapted + */ + public XacmlPdpOptimizationPolicyAdapter(final OptimizationPolicy optimizationPolicy) { + super(optimizationPolicy); + } + + @Override + public PolicyParameters getAsPolicyParameters() { + PolicyParameters policyParameters = new PolicyParameters(); + policyParameters.setPolicyName(getPolicy().getPolicyName()); + policyParameters.setPolicyDescription(getPolicy().getPolicyDescription()); + policyParameters.setPolicyConfigType(PolicyConfigType.valueOf(getPolicy().getPolicyConfigType())); + policyParameters.setOnapName(getPolicy().getOnapName()); + policyParameters.setRiskLevel(getPolicy().getRiskLevel()); + policyParameters.setConfigBody(getPolicy().getConfigBody()); + policyParameters.setRiskType(getPolicy().getRiskType()); + return policyParameters; + } + +} diff --git a/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/engine/XacmlPdpPolicyForwarderParameterGroupTest.java b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/engine/XacmlPdpPolicyForwarderParameterGroupTest.java new file mode 100644 index 00000000..1241b7f3 --- /dev/null +++ b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/engine/XacmlPdpPolicyForwarderParameterGroupTest.java @@ -0,0 +1,98 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp.engine; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationStatus; +import org.onap.policy.distribution.forwarding.xacml.pdp.XacmlPdpPolicyForwarderParameterGroup; +import org.onap.policy.distribution.forwarding.xacml.pdp.XacmlPdpPolicyForwarderParameterGroup.XacmlPdpPolicyForwarderParameterGroupBuilder; + +public class XacmlPdpPolicyForwarderParameterGroupTest { + + @Test + public void testBuilderAndGetters() { + XacmlPdpPolicyForwarderParameterGroupBuilder builder = + new XacmlPdpPolicyForwarderParameterGroupBuilder(); + XacmlPdpPolicyForwarderParameterGroup configurationParameters = + builder.setUseHttps(true).setHostname("10.10.10.10").setPort(1234).setUserName("myUser") + .setPassword("myPassword").setClientAuth("myClientAuth").setIsManaged(false).build(); + + assertTrue(configurationParameters.isUseHttps()); + assertEquals("10.10.10.10", configurationParameters.getHostname()); + assertEquals(1234, configurationParameters.getPort()); + assertEquals("myUser", configurationParameters.getUserName()); + assertEquals("myPassword", configurationParameters.getPassword()); + assertEquals("myClientAuth", configurationParameters.getClientAuth()); + assertFalse(configurationParameters.isManaged()); + } + + @Test + public void testInvalidHostName() { + XacmlPdpPolicyForwarderParameterGroupBuilder builder = + new XacmlPdpPolicyForwarderParameterGroupBuilder(); + XacmlPdpPolicyForwarderParameterGroup configurationParameters = builder.setUseHttps(true).setHostname("") + .setPort(1234).setUserName("myUser").setPassword("myPassword").setIsManaged(false).build(); + configurationParameters.setName("myConfiguration"); + + assertEquals(ValidationStatus.INVALID, configurationParameters.validate().getStatus()); + } + + @Test + public void testInvalidPort() { + XacmlPdpPolicyForwarderParameterGroupBuilder builder = + new XacmlPdpPolicyForwarderParameterGroupBuilder(); + XacmlPdpPolicyForwarderParameterGroup configurationParameters = + builder.setUseHttps(true).setHostname("10.10.10.10").setPort(-1234).setUserName("myUser") + .setPassword("myPassword").setIsManaged(false).build(); + configurationParameters.setName("myConfiguration"); + + assertEquals(ValidationStatus.INVALID, configurationParameters.validate().getStatus()); + } + + @Test + public void testInvalidUserName() { + XacmlPdpPolicyForwarderParameterGroupBuilder builder = + new XacmlPdpPolicyForwarderParameterGroupBuilder(); + XacmlPdpPolicyForwarderParameterGroup configurationParameters = + builder.setUseHttps(true).setHostname("10.10.10.10").setPort(1234).setUserName("") + .setPassword("myPassword").setIsManaged(false).build(); + configurationParameters.setName("myConfiguration"); + + assertEquals(ValidationStatus.INVALID, configurationParameters.validate().getStatus()); + } + + @Test + public void testInvalidPassword() { + XacmlPdpPolicyForwarderParameterGroupBuilder builder = + new XacmlPdpPolicyForwarderParameterGroupBuilder(); + XacmlPdpPolicyForwarderParameterGroup configurationParameters = + builder.setUseHttps(true).setHostname("10.10.10.10").setPort(1234).setUserName("myUser").setPassword("") + .setIsManaged(false).build(); + configurationParameters.setName("myConfiguration"); + + assertEquals(ValidationStatus.INVALID, configurationParameters.validate().getStatus()); + } + +} diff --git a/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/engine/XacmlPdpPolicyForwarderTest.java b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/engine/XacmlPdpPolicyForwarderTest.java new file mode 100644 index 00000000..d851b640 --- /dev/null +++ b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/engine/XacmlPdpPolicyForwarderTest.java @@ -0,0 +1,338 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp.engine; + +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.argThat; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.Response; +import org.hamcrest.BaseMatcher; +import org.hamcrest.Description; +import org.junit.BeforeClass; +import org.junit.Test; +import org.onap.policy.api.PolicyParameters; +import org.onap.policy.api.PushPolicyParameters; +import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.common.parameters.ParameterGroup; +import org.onap.policy.common.parameters.ParameterService; +import org.onap.policy.distribution.forwarding.xacml.pdp.XacmlPdpPolicyForwarder; +import org.onap.policy.distribution.forwarding.xacml.pdp.XacmlPdpPolicyForwarderParameterGroup.XacmlPdpPolicyForwarderParameterGroupBuilder; +import org.onap.policy.distribution.main.PolicyDistributionException; +import org.onap.policy.distribution.model.OptimizationPolicy; +import org.onap.policy.distribution.model.Policy; + +public class XacmlPdpPolicyForwarderTest { + + private static final BusTopicParams BUS_TOPIC_PARAMS = BusTopicParams.builder().useHttps(false).hostname("myHost") + .port(1234).userName("myUser").password("myPassword").managed(true).build(); + private static final String CLIENT_AUTH = "ClientAuth"; + private static final String CLIENT_AUTH_VALUE = "myClientAuth"; + private static final String PDP_GROUP_VALUE = "myPdpGroup"; + private HashMap<String, Object> headers = new HashMap<>(); + private BusTopicParamsMatcher matcher = new BusTopicParamsMatcher(BUS_TOPIC_PARAMS); + + /** + * Set up. + */ + @BeforeClass + public static void setUp() { + ParameterGroup parameterGroup = new XacmlPdpPolicyForwarderParameterGroupBuilder() + .setUseHttps(BUS_TOPIC_PARAMS.isUseHttps()).setHostname(BUS_TOPIC_PARAMS.getHostname()) + .setPort(BUS_TOPIC_PARAMS.getPort()).setUserName(BUS_TOPIC_PARAMS.getUserName()) + .setPassword(BUS_TOPIC_PARAMS.getPassword()).setClientAuth(CLIENT_AUTH_VALUE) + .setIsManaged(BUS_TOPIC_PARAMS.isManaged()).setPdpGroup(PDP_GROUP_VALUE).build(); + parameterGroup.setName("xacmlPdpConfiguration"); + ParameterService.register(parameterGroup); + } + + @Test + public void testForwardPolicy() throws KeyManagementException, NoSuchAlgorithmException, NoSuchFieldException, + SecurityException, IllegalArgumentException, IllegalAccessException, PolicyDistributionException { + + HttpClient httpClientMock = mock(HttpClient.class); + headers.put(CLIENT_AUTH, CLIENT_AUTH_VALUE); + when(httpClientMock.put(eq("createPolicy"), anyObject(), eq(headers))).thenReturn(Response.ok().build()); + when(httpClientMock.put(eq("pushPolicy"), anyObject(), eq(headers))).thenReturn(Response.ok().build()); + + HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class); + when(httpClientFactoryMock.build(argThat(matcher))).thenReturn(httpClientMock); + + overwriteField(HttpClient.class, "factory", null, httpClientFactoryMock); + + XacmlPdpPolicyForwarder forwarder = new XacmlPdpPolicyForwarder(); + forwarder.configure("xacmlPdpConfiguration"); + + Collection<Policy> policies = new ArrayList<>(); + + OptimizationPolicy policy1 = new OptimizationPolicy(); + policy1.setPolicyName("policy1"); + policy1.setPolicyConfigType("Optimization"); + policies.add(policy1); + + Policy policy2 = new UnsupportedPolicy(); + policies.add(policy2); + + OptimizationPolicy policy3 = new OptimizationPolicy(); + policy3.setPolicyName("policy3"); + policy3.setPolicyConfigType("Optimization"); + policies.add(policy3); + + forwarder.forward(policies); + + verify(httpClientMock).put(eq("createPolicy"), argThat(new PolicyParametersEntityMatcher(policy1)), + eq(headers)); + verify(httpClientMock).put(eq("createPolicy"), argThat(new PolicyParametersEntityMatcher(policy3)), + eq(headers)); + verify(httpClientMock).put(eq("pushPolicy"), argThat(new PushPolicyParametersEntityMatcher(policy1)), + eq(headers)); + verify(httpClientMock).put(eq("pushPolicy"), argThat(new PushPolicyParametersEntityMatcher(policy3)), + eq(headers)); + } + + @Test + public void testForwardPolicy_CreateFailsPushNotInvoked() + throws KeyManagementException, NoSuchAlgorithmException, NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException, PolicyDistributionException { + + HttpClient httpClientMock = mock(HttpClient.class); + headers.put(CLIENT_AUTH, CLIENT_AUTH_VALUE); + when(httpClientMock.put(eq("createPolicy"), anyObject(), eq(headers))).thenReturn(Response.status(400).build()); + when(httpClientMock.put(eq("pushPolicy"), anyObject(), eq(headers))).thenReturn(Response.ok().build()); + + HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class); + when(httpClientFactoryMock.build(argThat(matcher))).thenReturn(httpClientMock); + + overwriteField(HttpClient.class, "factory", null, httpClientFactoryMock); + + XacmlPdpPolicyForwarder forwarder = new XacmlPdpPolicyForwarder(); + forwarder.configure("xacmlPdpConfiguration"); + + Collection<Policy> policies = new ArrayList<>(); + OptimizationPolicy policy = new OptimizationPolicy(); + policy.setPolicyName("policy"); + policy.setPolicyConfigType("Optimization"); + policies.add(policy); + forwarder.forward(policies); + + verify(httpClientMock).put(eq("createPolicy"), argThat(new PolicyParametersEntityMatcher(policy)), eq(headers)); + verify(httpClientMock, times(0)).put(eq("pushPolicy"), anyObject(), anyObject()); + } + + @Test + public void testForwardPolicy_PushFails() + throws KeyManagementException, NoSuchAlgorithmException, NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException, PolicyDistributionException { + + HttpClient httpClientMock = mock(HttpClient.class); + headers.put(CLIENT_AUTH, CLIENT_AUTH_VALUE); + when(httpClientMock.put(eq("createPolicy"), anyObject(), eq(headers))).thenReturn(Response.ok().build()); + when(httpClientMock.put(eq("pushPolicy"), anyObject(), eq(headers))).thenReturn(Response.status(400).build()); + + HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class); + when(httpClientFactoryMock.build(argThat(matcher))).thenReturn(httpClientMock); + + overwriteField(HttpClient.class, "factory", null, httpClientFactoryMock); + + XacmlPdpPolicyForwarder forwarder = new XacmlPdpPolicyForwarder(); + forwarder.configure("xacmlPdpConfiguration"); + + Collection<Policy> policies = new ArrayList<>(); + OptimizationPolicy policy = new OptimizationPolicy(); + policy.setPolicyName("policy"); + policy.setPolicyConfigType("Optimization"); + policies.add(policy); + forwarder.forward(policies); + + verify(httpClientMock).put(eq("createPolicy"), argThat(new PolicyParametersEntityMatcher(policy)), eq(headers)); + verify(httpClientMock).put(eq("pushPolicy"), argThat(new PushPolicyParametersEntityMatcher(policy)), + eq(headers)); + } + + @Test + public void testForwardPolicy_HttpClientInitFailureForPolicyCreate() + throws KeyManagementException, NoSuchAlgorithmException, NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException, PolicyDistributionException { + + HttpClient httpClientMock = mock(HttpClient.class); + headers.put(CLIENT_AUTH, CLIENT_AUTH_VALUE); + when(httpClientMock.put(eq("createPolicy"), anyObject(), eq(headers))).thenReturn(Response.ok().build()); + when(httpClientMock.put(eq("pushPolicy"), anyObject(), eq(headers))).thenReturn(Response.status(400).build()); + + HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class); + when(httpClientFactoryMock.build(argThat(matcher))).thenThrow(new KeyManagementException()); + + overwriteField(HttpClient.class, "factory", null, httpClientFactoryMock); + + XacmlPdpPolicyForwarder forwarder = new XacmlPdpPolicyForwarder(); + forwarder.configure("xacmlPdpConfiguration"); + + Collection<Policy> policies = new ArrayList<>(); + OptimizationPolicy policy = new OptimizationPolicy(); + policy.setPolicyName("policy"); + policy.setPolicyConfigType("Optimization"); + policies.add(policy); + forwarder.forward(policies); + + verify(httpClientMock, times(0)).put(eq("createPolicy"), anyObject(), anyObject()); + verify(httpClientMock, times(0)).put(eq("pushPolicy"), anyObject(), anyObject()); + } + + @Test + public void testForwardPolicy_HttpClientInitFailureForPolicyPush() + throws KeyManagementException, NoSuchAlgorithmException, NoSuchFieldException, SecurityException, + IllegalArgumentException, IllegalAccessException, PolicyDistributionException { + + HttpClient httpClientMock = mock(HttpClient.class); + headers.put(CLIENT_AUTH, CLIENT_AUTH_VALUE); + when(httpClientMock.put(eq("createPolicy"), anyObject(), eq(headers))).thenReturn(Response.ok().build()); + when(httpClientMock.put(eq("pushPolicy"), anyObject(), eq(headers))).thenReturn(Response.status(400).build()); + + HttpClientFactory httpClientFactoryMock = mock(HttpClientFactory.class); + when(httpClientFactoryMock.build(argThat(matcher))).thenReturn(httpClientMock) + .thenThrow(new KeyManagementException()); + + overwriteField(HttpClient.class, "factory", null, httpClientFactoryMock); + + XacmlPdpPolicyForwarder forwarder = new XacmlPdpPolicyForwarder(); + forwarder.configure("xacmlPdpConfiguration"); + + Collection<Policy> policies = new ArrayList<>(); + OptimizationPolicy policy = new OptimizationPolicy(); + policy.setPolicyName("policy"); + policy.setPolicyConfigType("Optimization"); + policies.add(policy); + forwarder.forward(policies); + + verify(httpClientMock).put(eq("createPolicy"), argThat(new PolicyParametersEntityMatcher(policy)), eq(headers)); + verify(httpClientMock, times(0)).put(eq("pushPolicy"), anyObject(), anyObject()); + } + + private void overwriteField(final Class<?> clazz, final String fieldName, final Object object, final Object value) + throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { + Field field = clazz.getField(fieldName); + field.setAccessible(true); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(object, value); + } + + class BusTopicParamsMatcher extends BaseMatcher<BusTopicParams> { + + private BusTopicParams busTopicParams; + + BusTopicParamsMatcher(final BusTopicParams busTopicParams) { + this.busTopicParams = busTopicParams; + } + + @Override + public boolean matches(Object arg0) { + if (arg0 instanceof BusTopicParams) { + BusTopicParams toCompareTo = (BusTopicParams) arg0; + return toCompareTo.isUseHttps() == busTopicParams.isUseHttps() + && toCompareTo.getHostname().equals(busTopicParams.getHostname()) + && toCompareTo.getPort() == busTopicParams.getPort() + && toCompareTo.getUserName().equals(busTopicParams.getUserName()) + && toCompareTo.getPassword().equals(busTopicParams.getPassword()) + && toCompareTo.isManaged() == busTopicParams.isManaged(); + } + return false; + } + + @Override + public void describeTo(Description arg0) {} + } + + class PolicyParametersEntityMatcher extends BaseMatcher<Entity<PolicyParameters>> { + + private OptimizationPolicy policy; + + PolicyParametersEntityMatcher(final OptimizationPolicy policy) { + this.policy = policy; + } + + @SuppressWarnings("unchecked") + @Override + public boolean matches(Object arg0) { + if (arg0 instanceof Entity) { + PolicyParameters toCompareTo = ((Entity<PolicyParameters>) arg0).getEntity(); + return toCompareTo.getPolicyName().equals(policy.getPolicyName()) + && toCompareTo.getPolicyConfigType().toString().equals(policy.getPolicyConfigType()); + } + return false; + } + + @Override + public void describeTo(Description arg0) {} + } + + class PushPolicyParametersEntityMatcher extends BaseMatcher<Entity<PushPolicyParameters>> { + + private Policy policy; + + PushPolicyParametersEntityMatcher(final Policy policy) { + this.policy = policy; + } + + @SuppressWarnings("unchecked") + @Override + public boolean matches(Object arg0) { + if (arg0 instanceof Entity) { + PushPolicyParameters toCompareTo = ((Entity<PushPolicyParameters>) arg0).getEntity(); + return toCompareTo.getPolicyName().equals(policy.getPolicyName()) + && toCompareTo.getPolicyType().equals(policy.getPolicyType()) + && toCompareTo.getPdpGroup().equals(PDP_GROUP_VALUE); + } + return false; + } + + @Override + public void describeTo(Description arg0) {} + } + + class UnsupportedPolicy implements Policy { + + @Override + public String getPolicyName() { + return "unsupported"; + } + + @Override + public String getPolicyType() { + return "unsupported"; + } + } +} diff --git a/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/testclasses/DummyDecoder.java b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/testclasses/DummyDecoder.java new file mode 100644 index 00000000..e09357cf --- /dev/null +++ b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/testclasses/DummyDecoder.java @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2018 Ericsson. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.distribution.forwarding.xacml.pdp.testclasses; + +import java.util.Collection; + +import org.onap.policy.distribution.model.Policy; +import org.onap.policy.distribution.model.PolicyInput; +import org.onap.policy.distribution.reception.decoding.PolicyDecoder; +import org.onap.policy.distribution.reception.decoding.PolicyDecodingException; + +/** + * Class to create a dummy decoder for test cases. + * + * @author Ram Krishna Verma (ram.krishna.verma@ericsson.com) + */ +public class DummyDecoder implements PolicyDecoder<PolicyInput, Policy> { + + private boolean canHandleValue; + private Collection<Policy> policesToReturn; + + public DummyDecoder() { + this.canHandleValue = false; + this.policesToReturn = null; + } + + public DummyDecoder(final boolean canHandleValue, final Collection<Policy> policesToReturn) { + this.canHandleValue = canHandleValue; + this.policesToReturn = policesToReturn; + } + + @Override + public boolean canHandle(final PolicyInput policyInput) { + return canHandleValue; + } + + @Override + public Collection<Policy> decode(final PolicyInput input) throws PolicyDecodingException { + return policesToReturn; + } +} diff --git a/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/pap/engine/XacmlPapServletPolicyForwarder.java b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/testclasses/DummyReceptionHandler.java index eb33a852..c0934812 100644 --- a/plugins/forwarding-plugins/src/main/java/org/onap/policy/distribution/forwarding/pap/engine/XacmlPapServletPolicyForwarder.java +++ b/plugins/forwarding-plugins/src/test/java/org/onap/policy/distribution/forwarding/xacml/pdp/testclasses/DummyReceptionHandler.java @@ -18,21 +18,20 @@ * ============LICENSE_END========================================================= */ -package org.onap.policy.distribution.forwarding.pap.engine; +package org.onap.policy.distribution.forwarding.xacml.pdp.testclasses; -import java.util.Collection; - -import org.onap.policy.distribution.forwarding.PolicyForwarder; -import org.onap.policy.distribution.model.Policy; +import org.onap.policy.distribution.reception.handling.AbstractReceptionHandler; /** - * Forwards policies to the XACML PAP Servlet. + * Class to create a dummy reception handler for test cases. + * + * @author Ram Krishna Verma (ram.krishna.verma@ericsson.com) */ -public class XacmlPapServletPolicyForwarder implements PolicyForwarder { +public class DummyReceptionHandler extends AbstractReceptionHandler { @Override - public void forward(final Collection<Policy> policies) { - // Send policies to PAP using common/policy-endpoints - } + public void initializeReception(final String parameterGroupName) {} + @Override + public void destroy() {} } |