diff options
author | Jim Hahn <jrh3@att.com> | 2021-07-20 14:07:35 -0400 |
---|---|---|
committer | Jim Hahn <jrh3@att.com> | 2021-07-21 16:58:06 -0400 |
commit | f15f54b93718d7cefce2a81689662fc0f09e8958 (patch) | |
tree | d6d6fbbcbcfefbe7424a6aad04ecb98c5c883631 /models-interactions | |
parent | 1755cdd3b3b44dce9369358cdc89f76a5bf848fe (diff) |
Added Xacml actor
Cloned the guard actor to use as a starting point for creating a more
generic actor for interacting with the xacml-pdp.
Also renamed various classes.
Issue-ID: POLICY-3501
Change-Id: I9bd0107845de41a349d56259e6cfa6a3180efa25
Signed-off-by: Jim Hahn <jrh3@att.com>
Diffstat (limited to 'models-interactions')
22 files changed, 1333 insertions, 19 deletions
diff --git a/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/DecisionOperationTest.java b/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/DecisionOperationTest.java index 5502ec6aa..9b13fa558 100644 --- a/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/DecisionOperationTest.java +++ b/models-interactions/model-actors/actor.guard/src/test/java/org/onap/policy/controlloop/actor/guard/DecisionOperationTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP * ================================================================================ - * Copyright (C) 2020 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. @@ -53,7 +53,7 @@ import org.onap.policy.controlloop.actorserviceprovider.OperationResult; import org.onap.policy.controlloop.actorserviceprovider.Util; import org.onap.policy.models.decisions.concepts.DecisionRequest; import org.onap.policy.models.decisions.concepts.DecisionResponse; -import org.onap.policy.simulators.GuardSimulatorJaxRs; +import org.onap.policy.simulators.XacmlSimulatorJaxRs; public class DecisionOperationTest extends BasicHttpOperation { @@ -73,7 +73,7 @@ public class DecisionOperationTest extends BasicHttpOperation { org.onap.policy.simulators.Util.buildGuardSim(); BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/") - .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.GUARDSIM_SERVER_PORT) + .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.XACMLSIM_SERVER_PORT) .build(); HttpClientFactoryInstance.getClientFactory().build(clientParams); } @@ -134,7 +134,7 @@ public class DecisionOperationTest extends BasicHttpOperation { config = new GuardConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory()); params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor) - .payload(Map.of("clname", GuardSimulatorJaxRs.DENY_CLNAME)).build(); + .payload(Map.of("clname", XacmlSimulatorJaxRs.DENY_CLNAME)).build(); oper = new DecisionOperation(params, config); outcome = oper.start().get(); diff --git a/models-interactions/model-actors/actor.xacml/pom.xml b/models-interactions/model-actors/actor.xacml/pom.xml new file mode 100644 index 000000000..76e529eb8 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/pom.xml @@ -0,0 +1,83 @@ +<?xml version="1.0"?> +<!-- + ============LICENSE_START======================================================= + ONAP + ================================================================================ + Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + ============LICENSE_END========================================================= + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> + <artifactId>model-actors</artifactId> + <version>2.5.0-SNAPSHOT</version> + </parent> + + <artifactId>actor.xacml</artifactId> + + <dependencies> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> + <artifactId>actorServiceProvider</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-impl</groupId> + <artifactId>aai</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models</groupId> + <artifactId>policy-models-decisions</artifactId> + <version>${project.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.common</groupId> + <artifactId>policy-endpoints</artifactId> + <version>${policy.common.version}</version> + <scope>provided</scope> + </dependency> + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions.model-actors</groupId> + <artifactId>actor.test</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.policy.models.policy-models-interactions</groupId> + <artifactId>simulators</artifactId> + <version>${project.version}</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.powermock</groupId> + <artifactId>powermock-api-mockito2</artifactId> + <scope>test</scope> + </dependency> + </dependencies> +</project> diff --git a/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionConfig.java b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionConfig.java new file mode 100644 index 000000000..1fe16fa13 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionConfig.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import java.util.concurrent.Executor; +import lombok.Getter; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.models.decisions.concepts.DecisionRequest; + +/** + * Configuration for Decision Operators. + */ +public class DecisionConfig extends HttpConfig { + private final DecisionRequest defaultRequest = new DecisionRequest(); + + /** + * {@code True} if the associated decision operation is disabled. + */ + @Getter + private boolean disabled; + + /** + * Constructs the object. + * + * @param blockingExecutor executor to be used for tasks that may perform blocking I/O + * @param params operator parameters + * @param clientFactory factory from which to obtain the {@link HttpClient} + */ + public DecisionConfig(Executor blockingExecutor, DecisionParams params, HttpClientFactory clientFactory) { + super(blockingExecutor, params, clientFactory); + + defaultRequest.setOnapComponent(params.getOnapComponent()); + defaultRequest.setOnapInstance(params.getOnapInstance()); + defaultRequest.setOnapName(params.getOnapName()); + defaultRequest.setAction(params.getAction()); + + this.disabled = params.isDisabled(); + } + + /** + * Creates a new request, with the default values. + * + * @return a new request + */ + public DecisionRequest makeRequest() { + return new DecisionRequest(defaultRequest); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionOperator.java b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionOperator.java new file mode 100644 index 000000000..f385764d5 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionOperator.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import java.util.Map; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperator; +import org.onap.policy.controlloop.actorserviceprovider.impl.OperationMaker; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; + +/** + * Decision Operator. + */ +public class DecisionOperator extends HttpOperator { + + public DecisionOperator(String actorName, String name, + OperationMaker<HttpConfig, HttpOperation<?>> operationMaker) { + super(actorName, name, operationMaker); + } + + @Override + protected HttpConfig makeConfiguration(Map<String, Object> parameters) { + DecisionParams params = Util.translate(getFullName(), parameters, DecisionParams.class); + ValidationResult result = params.validate(getFullName()); + if (!result.isValid()) { + throw new ParameterValidationRuntimeException("invalid parameters", result); + } + + return new DecisionConfig(getBlockingExecutor(), params, getClientFactory()); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionParams.java b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionParams.java new file mode 100644 index 000000000..c154497f1 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionParams.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.SuperBuilder; +import org.onap.policy.common.parameters.annotations.NotBlank; +import org.onap.policy.common.parameters.annotations.NotNull; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams; + +/** + * Decision parameters. + */ +@NotBlank +@NotNull +@Data +@EqualsAndHashCode(callSuper = true) +@SuperBuilder(toBuilder = true) +public class DecisionParams extends HttpParams { + private String onapName; + private String onapComponent; + private String onapInstance; + private String action; + + /** + * {@code True} if the associated decision operation is disabled. + */ + private boolean disabled; +} diff --git a/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/GuardOperation.java b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/GuardOperation.java new file mode 100644 index 000000000..6da970968 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/GuardOperation.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure; +import org.onap.policy.common.endpoints.utils.NetLoggerUtil.EventType; +import org.onap.policy.controlloop.actorserviceprovider.CallbackManager; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.OperationResult; +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpOperation; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ControlLoopOperationParams; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpConfig; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Guard Operation. The outcome message is set to the guard response. If the guard is + * permitted or indeterminate, then the outcome is set to SUCCESS. + * <p/> + * The input to the request is taken from the payload, where properties are mapped to the + * field names in the {@link DecisionRequest} object. Properties whose names begin with + * "resource." are placed into the "resource" field of the {@link DecisionRequest}. The + * following will be provided, if not specified in the payload: + * <dl> + * <dt>action</dt> + * <dd>"guard"</dd> + * <dt>request ID</dt> + * <dd>generated</dd> + * </dl> + */ +public class GuardOperation extends HttpOperation<DecisionResponse> { + private static final Logger logger = LoggerFactory.getLogger(GuardOperation.class); + + // operation name + public static final String NAME = "Guard"; + + public static final String PERMIT = "Permit"; + public static final String DENY = "Deny"; + public static final String INDETERMINATE = "Indeterminate"; + + /** + * Prefix for properties in the payload that should be copied to the "resource" field + * of the request. + */ + public static final String RESOURCE_PREFIX = "resource."; + + private final DecisionConfig config; + + + /** + * Constructs the object. + * + * @param params operation parameters + * @param config configuration for this operation + */ + public GuardOperation(ControlLoopOperationParams params, HttpConfig config) { + super(params, config, DecisionResponse.class, Collections.emptyList()); + this.config = (DecisionConfig) config; + } + + @Override + public CompletableFuture<OperationOutcome> start() { + if (!config.isDisabled()) { + // enabled - do full guard operation + return super.start(); + } + + // guard is disabled, thus it is always treated as a success + logger.info("{}: guard disabled, always succeeds for {}", getFullName(), params.getRequestId()); + + final var executor = params.getExecutor(); + final var callbacks = new CallbackManager(); + + return CompletableFuture.completedFuture(makeOutcome()) + .whenCompleteAsync(callbackStarted(callbacks), executor) + .whenCompleteAsync(callbackCompleted(callbacks), executor); + } + + @Override + protected CompletableFuture<OperationOutcome> startOperationAsync(int attempt, OperationOutcome outcome) { + DecisionRequest request = makeRequest(); + + Map<String, Object> headers = makeHeaders(); + + headers.put("Accept", MediaType.APPLICATION_JSON); + String url = getUrl(); + + String strRequest = prettyPrint(request); + logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest); + + Entity<String> entity = Entity.entity(strRequest, MediaType.APPLICATION_JSON); + + // @formatter:off + return handleResponse(outcome, url, + callback -> getClient().post(callback, getPath(), entity, headers)); + // @formatter:on + } + + /** + * Makes a request from the payload. + * + * @return a new request + */ + protected DecisionRequest makeRequest() { + if (params.getPayload() == null) { + throw new IllegalArgumentException("missing payload"); + } + + DecisionRequest req = config.makeRequest(); + req.setRequestId(getSubRequestId()); + req.setResource(Map.of("guard", params.getPayload())); + + return req; + } + + @Override + protected CompletableFuture<OperationOutcome> postProcessResponse(OperationOutcome outcome, String url, + Response rawResponse, DecisionResponse response) { + + outcome.setResponse(response); + + // determine the result + String status = response.getStatus(); + if (status == null) { + outcome.setResult(OperationResult.FAILURE); + outcome.setMessage("response contains no status"); + return CompletableFuture.completedFuture(outcome); + } + + if (PERMIT.equalsIgnoreCase(status) || INDETERMINATE.equalsIgnoreCase(status)) { + outcome.setResult(OperationResult.SUCCESS); + } else { + outcome.setResult(OperationResult.FAILURE); + } + + // set the message + outcome.setMessage(response.getStatus()); + + return CompletableFuture.completedFuture(outcome); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActor.java b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActor.java new file mode 100644 index 000000000..ab7452266 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActor.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2018-2019 Huawei Intellectual Property. All rights reserved. + * Modifications Copyright (C) 2019 Nordix Foundation. + * Modifications Copyright (C) 2019-2021 AT&T Intellectual Property. + * ================================================================================ + * 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import org.onap.policy.controlloop.actorserviceprovider.impl.HttpActor; + +public class XacmlActor extends HttpActor<XacmlActorParams> { + // actor name + public static final String NAME = "XACML"; + + /** + * Constructs the object. + */ + public XacmlActor() { + super(NAME, XacmlActorParams.class); + + addOperator(new DecisionOperator(NAME, GuardOperation.NAME, GuardOperation::new)); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActorParams.java b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActorParams.java new file mode 100644 index 000000000..e668fa3db --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActorParams.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.Setter; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpActorParams; + +@Getter +@Setter +@EqualsAndHashCode(callSuper = true) +public class XacmlActorParams extends HttpActorParams { + public static final String DEFAULT_ACTION = "guard"; + + /* + * Optional, default values that are used if missing from the operation-specific + * parameters. + */ + + private String onapName; + private String onapComponent; + private String onapInstance; + private String action = DEFAULT_ACTION; + + /** + * {@code True} if xacml operations are disabled. + */ + private boolean disabled = false; +} diff --git a/models-interactions/model-actors/actor.xacml/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorserviceprovider.spi.Actor b/models-interactions/model-actors/actor.xacml/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorserviceprovider.spi.Actor new file mode 100644 index 000000000..497f785f4 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorserviceprovider.spi.Actor @@ -0,0 +1 @@ +org.onap.policy.controlloop.actor.xacml.XacmlActor diff --git a/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorParamsTest.java b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorParamsTest.java new file mode 100644 index 000000000..0b0495620 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorParamsTest.java @@ -0,0 +1,117 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Map; +import java.util.TreeMap; +import java.util.function.Consumer; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actor.xacml.XacmlActorParams; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ActorParams; + +public class DecisionActorParamsTest { + private static final String CONTAINER = "my-container"; + private static final String CLIENT = "my-client"; + private static final int TIMEOUT = 10; + private static final String ONAP_NAME = "onap-nap"; + private static final String ONAP_COMP = "onap-component"; + private static final String ONAP_INST = "onap-instance"; + private static final String MY_ACTION = "my-action"; + + private static final String PATH1 = "path #1"; + private static final String PATH2 = "path #2"; + private static final String URI1 = "uri #1"; + private static final String URI2 = "uri #2"; + + private Map<String, Map<String, Object>> operations; + private XacmlActorParams params; + + /** + * Initializes {@link #operations} with two items and {@link params} with a fully + * populated object. + */ + @Before + public void setUp() { + operations = new TreeMap<>(); + operations.put(PATH1, Map.of("path", URI1)); + operations.put(PATH2, Map.of("path", URI2)); + + params = makeXacmlActorParams(); + } + + @Test + public void testIsDisabled() { + // disabled by default + assertFalse(params.isDisabled()); + } + + @Test + public void testValidate() { + assertTrue(params.validate(CONTAINER).isValid()); + + // only a few fields are required + XacmlActorParams sparse = Util.translate(CONTAINER, Map.of(ActorParams.OPERATIONS_FIELD, operations), + XacmlActorParams.class); + assertTrue(sparse.validate(CONTAINER).isValid()); + + assertEquals(XacmlActorParams.DEFAULT_ACTION, sparse.getAction()); + + // check fields from superclass + testValidateField(ActorParams.OPERATIONS_FIELD, "null", params2 -> params2.setOperations(null)); + testValidateField("timeoutSec", "minimum", params2 -> params2.setTimeoutSec(-1)); + } + + private void testValidateField(String fieldName, String expected, Consumer<XacmlActorParams> makeInvalid) { + + // original params should be valid + ValidationResult result = params.validate(CONTAINER); + assertTrue(fieldName, result.isValid()); + + // make invalid params + XacmlActorParams params2 = makeXacmlActorParams(); + makeInvalid.accept(params2); + result = params2.validate(CONTAINER); + assertFalse(fieldName, result.isValid()); + assertThat(result.getResult()).contains(CONTAINER).contains(fieldName).contains(expected); + } + + private XacmlActorParams makeXacmlActorParams() { + XacmlActorParams params2 = new XacmlActorParams(); + params2.setClientName(CLIENT); + params2.setTimeoutSec(TIMEOUT); + params2.setOperations(operations); + + params2.setOnapName(ONAP_NAME); + params2.setOnapComponent(ONAP_COMP); + params2.setOnapInstance(ONAP_INST); + params2.setAction(MY_ACTION); + + return params2; + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorTest.java b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorTest.java new file mode 100644 index 000000000..47c294c24 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorTest.java @@ -0,0 +1,48 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.stream.Collectors; +import org.junit.Test; +import org.onap.policy.controlloop.actor.test.BasicActor; + +public class DecisionActorTest extends BasicActor { + + @Test + public void test() { + final XacmlActor prov = new XacmlActor(); + + // verify that it has the operators we expect + var expected = Arrays.asList(GuardOperation.NAME).stream().sorted().collect(Collectors.toList()); + var actual = prov.getOperationNames().stream().sorted().collect(Collectors.toList()); + + assertEquals(expected.toString(), actual.toString()); + + // verify that it all plugs into the ActorService + verifyActorService(XacmlActor.NAME, "service.yaml"); + + assertTrue(prov.getOperator(GuardOperation.NAME) instanceof DecisionOperator); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionConfigTest.java b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionConfigTest.java new file mode 100644 index 000000000..e03e1029d --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionConfigTest.java @@ -0,0 +1,101 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.concurrent.Executor; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.controlloop.actor.xacml.DecisionConfig; +import org.onap.policy.controlloop.actor.xacml.DecisionParams; +import org.onap.policy.models.decisions.concepts.DecisionRequest; + +@RunWith(MockitoJUnitRunner.class) +public class DecisionConfigTest { + private static final String MY_CLIENT = "my-client"; + private static final String PATH = "my-path"; + private static final int TIMEOUT = 10; + private static final String ONAP_NAME = "onap-nap"; + private static final String ONAP_COMP = "onap-component"; + private static final String ONAP_INST = "onap-instance"; + private static final String MY_ACTION = "my-action"; + + @Mock + private HttpClient client; + @Mock + private HttpClientFactory factory; + @Mock + private Executor executor; + + private DecisionParams params; + private DecisionConfig config; + + /** + * Sets up. + */ + @Before + public void setUp() { + when(factory.get(MY_CLIENT)).thenReturn(client); + + params = DecisionParams.builder().onapName(ONAP_NAME).onapComponent(ONAP_COMP).onapInstance(ONAP_INST) + .action(MY_ACTION).clientName(MY_CLIENT).path(PATH).timeoutSec(TIMEOUT).build(); + config = new DecisionConfig(executor, params, factory); + } + + @Test + public void test() { + DecisionRequest expected = new DecisionRequest(); + expected.setOnapComponent(ONAP_COMP); + expected.setOnapInstance(ONAP_INST); + expected.setOnapName(ONAP_NAME); + expected.setAction(MY_ACTION); + + DecisionRequest actual = config.makeRequest(); + assertEquals(expected, actual); + + // check value from superclass + assertSame(executor, config.getBlockingExecutor()); + assertSame(client, config.getClient()); + + // repeat, with minimal parameters + params = DecisionParams.builder().clientName(MY_CLIENT).path(PATH).timeoutSec(TIMEOUT).build(); + config = new DecisionConfig(executor, params, factory); + assertFalse(config.isDisabled()); + + actual = config.makeRequest(); + assertEquals(new DecisionRequest(), actual); + + // try with disabled=true + params = params.toBuilder().disabled(true).build(); + config = new DecisionConfig(executor, params, factory); + assertTrue(config.isDisabled()); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionOperatorTest.java b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionOperatorTest.java new file mode 100644 index 000000000..ab8535ae4 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionOperatorTest.java @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +import java.util.Map; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.policy.common.endpoints.http.client.HttpClient; +import org.onap.policy.common.endpoints.http.client.HttpClientFactory; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.controlloop.actorserviceprovider.parameters.ParameterValidationRuntimeException; + +@RunWith(MockitoJUnitRunner.class) +public class DecisionOperatorTest { + private static final String ACTOR = "my-actor"; + private static final String OPERATION = "my-name"; + private static final String CLIENT = "my-client"; + private static final String PATH = "my-path"; + private static final int TIMEOUT = 10; + private static final String ONAP_NAME = "onap-nap"; + private static final String ONAP_COMP = "onap-component"; + private static final String ONAP_INST = "onap-instance"; + private static final String MY_ACTION = "my-action"; + + @Mock + private HttpClient client; + + @Mock + private HttpClientFactory factory; + + + private DecisionOperator oper; + + /** + * Initializes fields, including {@link #oper}, and resets the static fields used by + * the REST server. + */ + @Before + public void setUp() { + when(factory.get(CLIENT)).thenReturn(client); + + oper = new MyOperator(); + + DecisionParams params = + DecisionParams.builder().onapName(ONAP_NAME).onapComponent(ONAP_COMP).onapInstance(ONAP_INST) + .action(MY_ACTION).clientName(CLIENT).path(PATH).timeoutSec(TIMEOUT).build(); + Map<String, Object> paramMap = Util.translateToMap(OPERATION, params); + oper.configure(paramMap); + + assertTrue(oper.makeConfiguration(paramMap) instanceof DecisionConfig); + } + + @Test + public void testConstructor() { + assertEquals(ACTOR, oper.getActorName()); + assertEquals(OPERATION, oper.getName()); + assertEquals(ACTOR + "." + OPERATION, oper.getFullName()); + } + + @Test + public void testDoConfigure_testGetters() { + assertTrue(oper.getCurrentConfig() instanceof DecisionConfig); + + // test invalid parameters + Map<String, Object> paramMap2 = Util.translateToMap(OPERATION, DecisionParams.builder().build()); + assertThatThrownBy(() -> oper.configure(paramMap2)).isInstanceOf(ParameterValidationRuntimeException.class); + } + + + private class MyOperator extends DecisionOperator { + public MyOperator() { + super(ACTOR, OPERATION, null); + } + + @Override + protected HttpClientFactory getClientFactory() { + return factory; + } + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionParamsTest.java b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionParamsTest.java new file mode 100644 index 000000000..01c7d5899 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionParamsTest.java @@ -0,0 +1,97 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.function.Function; +import org.junit.Before; +import org.junit.Test; +import org.onap.policy.common.parameters.ValidationResult; +import org.onap.policy.controlloop.actor.xacml.DecisionParams; +import org.onap.policy.controlloop.actor.xacml.DecisionParams.DecisionParamsBuilder; +import org.onap.policy.controlloop.actorserviceprovider.parameters.HttpParams.HttpParamsBuilder; + +public class DecisionParamsTest { + private static final String CONTAINER = "my-container"; + private static final String CLIENT = "my-client"; + private static final String PATH = "my-path"; + private static final int TIMEOUT = 10; + private static final String ONAP_NAME = "onap-nap"; + private static final String ONAP_COMP = "onap-component"; + private static final String ONAP_INST = "onap-instance"; + private static final String MY_ACTION = "my-action"; + + private DecisionParams params; + + @Before + public void setUp() { + params = DecisionParams.builder().onapName(ONAP_NAME).onapComponent(ONAP_COMP).onapInstance(ONAP_INST) + .action(MY_ACTION).clientName(CLIENT).path(PATH).timeoutSec(TIMEOUT).build(); + } + + @Test + public void testIsDisabled() { + // disabled by default + assertFalse(params.isDisabled()); + } + + @Test + public void testValidate() { + assertTrue(params.validate(CONTAINER).isValid()); + + testValidateField("onapName", "null", bldr -> bldr.onapName(null)); + testValidateField("onapComponent", "null", bldr -> bldr.onapComponent(null)); + testValidateField("onapInstance", "null", bldr -> bldr.onapInstance(null)); + testValidateField("action", "null", bldr -> bldr.action(null)); + + // validate one of the superclass fields + testValidateField("clientName", "null", bldr -> bldr.clientName(null)); + } + + @Test + public void testBuilder_testToBuilder() { + assertEquals(CLIENT, params.getClientName()); + + assertEquals(ONAP_NAME, params.getOnapName()); + assertEquals(ONAP_COMP, params.getOnapComponent()); + assertEquals(ONAP_INST, params.getOnapInstance()); + assertEquals(MY_ACTION, params.getAction()); + + assertEquals(params, params.toBuilder().build()); + } + + private void testValidateField(String fieldName, String expected, + @SuppressWarnings("rawtypes") Function<DecisionParamsBuilder, HttpParamsBuilder> makeInvalid) { + + // original params should be valid + ValidationResult result = params.validate(CONTAINER); + assertTrue(fieldName, result.isValid()); + + // make invalid params + result = makeInvalid.apply(params.toBuilder()).build().validate(CONTAINER); + assertFalse(fieldName, result.isValid()); + assertThat(result.getResult()).contains(fieldName).contains(expected); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/GuardOperationTest.java b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/GuardOperationTest.java new file mode 100644 index 000000000..e69b62d2a --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/GuardOperationTest.java @@ -0,0 +1,270 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP + * ================================================================================ + * Copyright (C) 2020-2021 AT&T Intellectual Property. 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. + * ============LICENSE_END========================================================= + */ + +package org.onap.policy.controlloop.actor.xacml; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.Map; +import java.util.TreeMap; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mock; +import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams; +import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance; +import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance; +import org.onap.policy.common.utils.coder.CoderException; +import org.onap.policy.controlloop.actor.test.BasicHttpOperation; +import org.onap.policy.controlloop.actorserviceprovider.OperationOutcome; +import org.onap.policy.controlloop.actorserviceprovider.OperationResult; +import org.onap.policy.controlloop.actorserviceprovider.Util; +import org.onap.policy.models.decisions.concepts.DecisionRequest; +import org.onap.policy.models.decisions.concepts.DecisionResponse; +import org.onap.policy.simulators.XacmlSimulatorJaxRs; + +public class GuardOperationTest extends BasicHttpOperation { + + @Mock + private Consumer<OperationOutcome> started; + @Mock + private Consumer<OperationOutcome> completed; + + private DecisionConfig guardConfig; + private GuardOperation oper; + + /** + * Starts the simulator. + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + org.onap.policy.simulators.Util.buildXacmlSim(); + + BusTopicParams clientParams = BusTopicParams.builder().clientName(MY_CLIENT).basePath("policy/pdpx/v1/") + .hostname("localhost").managed(true).port(org.onap.policy.simulators.Util.XACMLSIM_SERVER_PORT) + .build(); + HttpClientFactoryInstance.getClientFactory().build(clientParams); + } + + @AfterClass + public static void tearDownAfterClass() { + HttpClientFactoryInstance.getClientFactory().destroy(); + HttpServletServerFactoryInstance.getServerFactory().destroy(); + } + + /** + * Sets up. + */ + @Before + public void setUp() throws Exception { + super.setUpBasic(); + + guardConfig = mock(DecisionConfig.class); + when(guardConfig.makeRequest()).thenAnswer(args -> { + DecisionRequest req = new DecisionRequest(); + req.setAction("guard"); + req.setOnapComponent("my-onap-component"); + req.setOnapInstance("my-onap-instance"); + req.setOnapName("my-onap-name"); + return req; + }); + + config = guardConfig; + initConfig(); + + params = params.toBuilder().startCallback(started).completeCallback(completed).build(); + + oper = new GuardOperation(params, config); + } + + /** + * Tests "success" case with simulator. + */ + @Test + public void testSuccess() throws Exception { + DecisionParams opParams = DecisionParams.builder().clientName(MY_CLIENT).path("decision").build(); + config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory()); + + params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor).build(); + oper = new GuardOperation(params, config); + + outcome = oper.start().get(); + assertEquals(OperationResult.SUCCESS, outcome.getResult()); + assertTrue(outcome.getResponse() instanceof DecisionResponse); + } + + /** + * Tests "failure" case with simulator. + */ + @Test + public void testFailure() throws Exception { + DecisionParams opParams = DecisionParams.builder().clientName(MY_CLIENT).path("decision").build(); + config = new DecisionConfig(blockingExecutor, opParams, HttpClientFactoryInstance.getClientFactory()); + + params = params.toBuilder().retry(0).timeoutSec(5).executor(blockingExecutor) + .payload(Map.of("clname", XacmlSimulatorJaxRs.DENY_CLNAME)).build(); + oper = new GuardOperation(params, config); + + outcome = oper.start().get(); + assertEquals(OperationResult.FAILURE, outcome.getResult()); + assertTrue(outcome.getResponse() instanceof DecisionResponse); + } + + @Test + public void testConstructor() { + assertEquals(DEFAULT_ACTOR, oper.getActorName()); + assertEquals(DEFAULT_OPERATION, oper.getName()); + } + + @Test + public void testGetPropertyNames() { + assertThat(oper.getPropertyNames()).isEmpty(); + } + + @Test + public void testStartOperationAsync() throws Exception { + CompletableFuture<OperationOutcome> future2 = oper.start(); + executor.runAll(100); + assertFalse(future2.isDone()); + + DecisionResponse resp = new DecisionResponse(); + resp.setStatus(GuardOperation.PERMIT); + when(rawResponse.readEntity(String.class)).thenReturn(Util.translate("", resp, String.class)); + + verify(client).post(callbackCaptor.capture(), any(), requestCaptor.capture(), any()); + callbackCaptor.getValue().completed(rawResponse); + + executor.runAll(100); + assertTrue(future2.isDone()); + + outcome = future2.get(); + assertEquals(OperationResult.SUCCESS, outcome.getResult()); + assertEquals(resp, outcome.getResponse()); + + assertNotNull(oper.getSubRequestId()); + assertEquals(oper.getSubRequestId(), future2.get().getSubRequestId()); + } + + /** + * Tests startOperationAsync() when the guard is disabled. + */ + @Test + public void testStartOperationAsyncDisabled() throws Exception { + // indicate that it's disabled + when(guardConfig.isDisabled()).thenReturn(true); + + CompletableFuture<OperationOutcome> future2 = oper.start(); + executor.runAll(100); + + verify(client, never()).post(any(), any(), any(), any()); + + // should already be done + assertTrue(future2.isDone()); + + outcome = future2.get(); + assertEquals(OperationResult.SUCCESS, outcome.getResult()); + assertNull(outcome.getResponse()); + + // ensure callbacks were invoked + verify(started).accept(any()); + verify(completed).accept(any()); + } + + @Test + public void testMakeRequest() throws CoderException { + oper.generateSubRequestId(2); + + verifyPayload("makeReqStd.json", makePayload()); + verifyPayload("makeReqDefault.json", new TreeMap<>()); + + // null payload - start with fresh parameters and operation + params = params.toBuilder().payload(null).build(); + oper = new GuardOperation(params, config); + assertThatIllegalArgumentException().isThrownBy(() -> oper.makeRequest()); + } + + private void verifyPayload(String expectedJsonFile, Map<String, Object> payload) throws CoderException { + params.getPayload().clear(); + params.getPayload().putAll(payload); + + DecisionRequest request = oper.makeRequest(); + + assertEquals("guard", request.getAction()); + assertEquals("my-onap-component", request.getOnapComponent()); + assertEquals("my-onap-instance", request.getOnapInstance()); + assertEquals("my-onap-name", request.getOnapName()); + assertNotNull(request.getRequestId()); + assertEquals(Map.of("guard", payload), request.getResource()); + + verifyRequest(expectedJsonFile, request, "requestId"); + } + + @Test + public void testPostProcessResponse() { + DecisionResponse response = new DecisionResponse(); + + // null status + response.setStatus(null); + verifyOutcome(response, OperationResult.FAILURE, "response contains no status"); + + // permit, mixed case + response.setStatus("peRmit"); + verifyOutcome(response, OperationResult.SUCCESS, "peRmit"); + + // indeterminate, mixed case + response.setStatus("inDETerminate"); + verifyOutcome(response, OperationResult.SUCCESS, "inDETerminate"); + + // deny, mixed case + response.setStatus("deNY"); + verifyOutcome(response, OperationResult.FAILURE, "deNY"); + + // unknown status + response.setStatus("unknown"); + verifyOutcome(response, OperationResult.FAILURE, "unknown"); + } + + private void verifyOutcome(DecisionResponse response, OperationResult expectedResult, String expectedMessage) { + oper.postProcessResponse(outcome, BASE_URI, rawResponse, response); + assertEquals(expectedResult, outcome.getResult()); + assertEquals(expectedMessage, outcome.getMessage()); + assertSame(response, outcome.getResponse()); + } + + @Override + protected Map<String, Object> makePayload() { + return new TreeMap<>(Map.of("hello", "world", "abc", "123")); + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/resources/makeReqDefault.json b/models-interactions/model-actors/actor.xacml/src/test/resources/makeReqDefault.json new file mode 100644 index 000000000..a08f13f43 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/resources/makeReqDefault.json @@ -0,0 +1,10 @@ +{ + "ONAPName": "my-onap-name", + "ONAPComponent": "my-onap-component", + "ONAPInstance": "my-onap-instance", + "requestId": "abcdefghi", + "action": "guard", + "resource": { + "guard": {} + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/resources/makeReqStd.json b/models-interactions/model-actors/actor.xacml/src/test/resources/makeReqStd.json new file mode 100644 index 000000000..fd1f4c716 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/resources/makeReqStd.json @@ -0,0 +1,13 @@ +{ + "ONAPName": "my-onap-name", + "ONAPComponent": "my-onap-component", + "ONAPInstance": "my-onap-instance", + "requestId": "abcdefghi", + "action": "guard", + "resource": { + "guard": { + "abc": "123", + "hello": "world" + } + } +} diff --git a/models-interactions/model-actors/actor.xacml/src/test/resources/service.yaml b/models-interactions/model-actors/actor.xacml/src/test/resources/service.yaml new file mode 100644 index 000000000..81f4b8413 --- /dev/null +++ b/models-interactions/model-actors/actor.xacml/src/test/resources/service.yaml @@ -0,0 +1,35 @@ +# +# ============LICENSE_START====================================================== +# ONAP +# =============================================================================== +# Copyright (C) 2020-2021 AT&T Intellectual Property. 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. +# ============LICENSE_END======================================================== +# +httpClients: +- clientName: my-client + hostname: localhost + port: 80 + basePath: base-url + managed: true +actors: + XACML: + clientName: my-client + onapName: my-onap-name + onapComponent: my-onap-component + onapInstance: my-onap-instance + action: guard + operations: + Guard: + path: decide diff --git a/models-interactions/model-actors/pom.xml b/models-interactions/model-actors/pom.xml index 09bc5bad2..2a9698472 100644 --- a/models-interactions/model-actors/pom.xml +++ b/models-interactions/model-actors/pom.xml @@ -1,6 +1,6 @@ <!-- ============LICENSE_START======================================================= - Copyright (C) 2017-2020 AT&T Intellectual Property. All rights reserved. + Copyright (C) 2017-2021 AT&T Intellectual Property. All rights reserved. Modifications Copyright (C) 2020 Nordix Foundation. ================================================================================ Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,14 +38,15 @@ <module>actorServiceProvider</module> <module>actor.test</module> <module>actor.aai</module> - <module>actor.guard</module> + <module>actor.cds</module> <module>actor.appc</module> - <module>actor.vfc</module> - <module>actor.sdnc</module> <module>actor.appclcm</module> + <module>actor.guard</module> + <module>actor.sdnc</module> <module>actor.sdnr</module> <module>actor.so</module> - <module>actor.cds</module> + <module>actor.vfc</module> + <module>actor.xacml</module> </modules> <dependencies> <dependency> diff --git a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java index 29d665416..24fd7ece5 100644 --- a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java +++ b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/Util.java @@ -40,13 +40,13 @@ public final class Util { public static final String AAISIM_SERVER_NAME = "aaiSim"; public static final String SOSIM_SERVER_NAME = "soSim"; public static final String VFCSIM_SERVER_NAME = "vfcSim"; - public static final String GUARDSIM_SERVER_NAME = "guardSim"; + public static final String XACMLSIM_SERVER_NAME = "xacmlSim"; public static final String SDNCSIM_SERVER_NAME = "sdncSim"; public static final int AAISIM_SERVER_PORT = 6666; public static final int SOSIM_SERVER_PORT = 6667; public static final int VFCSIM_SERVER_PORT = 6668; - public static final int GUARDSIM_SERVER_PORT = 6669; + public static final int XACMLSIM_SERVER_PORT = 6669; public static final int SDNCSIM_SERVER_PORT = 6670; public static final int CDSSIM_SERVER_PORT = 6671; public static final int DMAAPSIM_SERVER_PORT = 3904; @@ -137,9 +137,19 @@ public final class Util { * @throws InterruptedException if a thread is interrupted */ public static HttpServletServer buildGuardSim() throws InterruptedException { - HttpServletServer testServer = HttpServletServerFactoryInstance.getServerFactory().build(GUARDSIM_SERVER_NAME, - LOCALHOST, GUARDSIM_SERVER_PORT, "/", false, true); - testServer.addServletClass("/*", GuardSimulatorJaxRs.class.getName()); + return buildXacmlSim(); + } + + /** + * Build a xacml simulator. + * + * @return the simulator + * @throws InterruptedException if a thread is interrupted + */ + public static HttpServletServer buildXacmlSim() throws InterruptedException { + HttpServletServer testServer = HttpServletServerFactoryInstance.getServerFactory().build(XACMLSIM_SERVER_NAME, + LOCALHOST, XACMLSIM_SERVER_PORT, "/", false, true); + testServer.addServletClass("/*", XacmlSimulatorJaxRs.class.getName()); testServer.waitedStart(5000); waitForServerToListen(testServer.getPort()); return testServer; diff --git a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/XacmlSimulatorJaxRs.java index 7a33a1950..f25b65c04 100644 --- a/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java +++ b/models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/XacmlSimulatorJaxRs.java @@ -32,7 +32,7 @@ import org.onap.policy.models.decisions.concepts.DecisionRequest; import org.onap.policy.models.decisions.concepts.DecisionResponse; @Path("/policy/pdpx/v1") -public class GuardSimulatorJaxRs { +public class XacmlSimulatorJaxRs { public static final String DENY_CLNAME = "denyGuard"; /** diff --git a/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java b/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/XacmlSimulatorTest.java index e553636ec..53b476fb2 100644 --- a/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java +++ b/models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/XacmlSimulatorTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * simulators * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019, 2021 AT&T Intellectual Property. All rights reserved. * Modifications Copyright (C) 2019-2020 Nordix Foundation. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -38,7 +38,7 @@ import org.onap.policy.models.decisions.concepts.DecisionRequest; import org.onap.policy.models.decisions.concepts.DecisionResponse; import org.onap.policy.rest.RestManager; -public class GuardSimulatorTest { +public class XacmlSimulatorTest { private static final StandardCoder coder = new StandardCoder(); /** @@ -47,7 +47,7 @@ public class GuardSimulatorTest { @BeforeClass public static void setupSimulator() { try { - org.onap.policy.simulators.Util.buildGuardSim(); + org.onap.policy.simulators.Util.buildXacmlSim(); } catch (Exception e) { fail(e.getMessage()); } @@ -61,7 +61,7 @@ public class GuardSimulatorTest { @Test public void testGuard() throws CoderException { String request = makeRequest("test_actor_id", "test_op_id", "test_target", "test_clName"); - String url = "http://localhost:" + Util.GUARDSIM_SERVER_PORT + "/policy/pdpx/v1/decision"; + String url = "http://localhost:" + Util.XACMLSIM_SERVER_PORT + "/policy/pdpx/v1/decision"; Pair<Integer, String> response = new RestManager().post(url, "testUname", "testPass", null, "application/json", request); assertNotNull(response); |