From f15f54b93718d7cefce2a81689662fc0f09e8958 Mon Sep 17 00:00:00 2001 From: Jim Hahn Date: Tue, 20 Jul 2021 14:07:35 -0400 Subject: 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 --- .../actor/guard/DecisionOperationTest.java | 8 +- .../model-actors/actor.xacml/pom.xml | 83 +++++++ .../controlloop/actor/xacml/DecisionConfig.java | 68 ++++++ .../controlloop/actor/xacml/DecisionOperator.java | 52 ++++ .../controlloop/actor/xacml/DecisionParams.java | 48 ++++ .../controlloop/actor/xacml/GuardOperation.java | 167 +++++++++++++ .../policy/controlloop/actor/xacml/XacmlActor.java | 39 +++ .../controlloop/actor/xacml/XacmlActorParams.java | 48 ++++ ...licy.controlloop.actorserviceprovider.spi.Actor | 1 + .../actor/xacml/DecisionActorParamsTest.java | 117 +++++++++ .../controlloop/actor/xacml/DecisionActorTest.java | 48 ++++ .../actor/xacml/DecisionConfigTest.java | 101 ++++++++ .../actor/xacml/DecisionOperatorTest.java | 106 ++++++++ .../actor/xacml/DecisionParamsTest.java | 97 ++++++++ .../actor/xacml/GuardOperationTest.java | 270 +++++++++++++++++++++ .../src/test/resources/makeReqDefault.json | 10 + .../actor.xacml/src/test/resources/makeReqStd.json | 13 + .../actor.xacml/src/test/resources/service.yaml | 35 +++ models-interactions/model-actors/pom.xml | 11 +- .../policy/simulators/GuardSimulatorJaxRs.java | 67 ----- .../main/java/org/onap/policy/simulators/Util.java | 20 +- .../policy/simulators/XacmlSimulatorJaxRs.java | 67 +++++ .../onap/policy/simulators/GuardSimulatorTest.java | 96 -------- .../onap/policy/simulators/XacmlSimulatorTest.java | 96 ++++++++ .../src/test/resources/simParameters.json | 4 +- 25 files changed, 1493 insertions(+), 179 deletions(-) create mode 100644 models-interactions/model-actors/actor.xacml/pom.xml create mode 100644 models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionConfig.java create mode 100644 models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionOperator.java create mode 100644 models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/DecisionParams.java create mode 100644 models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/GuardOperation.java create mode 100644 models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActor.java create mode 100644 models-interactions/model-actors/actor.xacml/src/main/java/org/onap/policy/controlloop/actor/xacml/XacmlActorParams.java create mode 100644 models-interactions/model-actors/actor.xacml/src/main/resources/META-INF/services/org.onap.policy.controlloop.actorserviceprovider.spi.Actor create mode 100644 models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorParamsTest.java create mode 100644 models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionActorTest.java create mode 100644 models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionConfigTest.java create mode 100644 models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionOperatorTest.java create mode 100644 models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/DecisionParamsTest.java create mode 100644 models-interactions/model-actors/actor.xacml/src/test/java/org/onap/policy/controlloop/actor/xacml/GuardOperationTest.java create mode 100644 models-interactions/model-actors/actor.xacml/src/test/resources/makeReqDefault.json create mode 100644 models-interactions/model-actors/actor.xacml/src/test/resources/makeReqStd.json create mode 100644 models-interactions/model-actors/actor.xacml/src/test/resources/service.yaml delete mode 100644 models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/GuardSimulatorJaxRs.java create mode 100644 models-interactions/model-simulators/src/main/java/org/onap/policy/simulators/XacmlSimulatorJaxRs.java delete mode 100644 models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/GuardSimulatorTest.java create mode 100644 models-interactions/model-simulators/src/test/java/org/onap/policy/simulators/XacmlSimulatorTest.java 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 @@ + + + + + 4.0.0 + + + org.onap.policy.models.policy-models-interactions.model-actors + model-actors + 2.5.0-SNAPSHOT + + + actor.xacml + + + + org.onap.policy.models.policy-models-interactions.model-actors + actorServiceProvider + ${project.version} + provided + + + org.onap.policy.models.policy-models-interactions.model-impl + aai + ${project.version} + provided + + + org.onap.policy.models + policy-models-decisions + ${project.version} + provided + + + org.onap.policy.common + policy-endpoints + ${policy.common.version} + provided + + + junit + junit + test + + + org.onap.policy.models.policy-models-interactions.model-actors + actor.test + ${project.version} + test + + + org.onap.policy.models.policy-models-interactions + simulators + ${project.version} + test + + + org.powermock + powermock-api-mockito2 + test + + + 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> operationMaker) { + super(actorName, name, operationMaker); + } + + @Override + protected HttpConfig makeConfiguration(Map 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. + *

+ * 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: + *

+ *
action
+ *
"guard"
+ *
request ID
+ *
generated
+ *
+ */ +public class GuardOperation extends HttpOperation { + 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 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 startOperationAsync(int attempt, OperationOutcome outcome) { + DecisionRequest request = makeRequest(); + + Map headers = makeHeaders(); + + headers.put("Accept", MediaType.APPLICATION_JSON); + String url = getUrl(); + + String strRequest = prettyPrint(request); + logMessage(EventType.OUT, CommInfrastructure.REST, url, strRequest); + + Entity 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 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 { + // 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> 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 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 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 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 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 started; + @Mock + private Consumer 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 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 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 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 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 @@