summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJim Hahn <jrh3@att.com>2021-06-29 15:17:39 +0000
committerGerrit Code Review <gerrit@onap.org>2021-06-29 15:17:39 +0000
commitaecbdd2e625f6f81344324edffa207b439e9607a (patch)
treea1a107c4b01a1db0898b95c68a6b156d14990b90
parent6eac3876d78c7fac402a4a9081132d1dede6e284 (diff)
parent547cc03a99d5c7392e6be628c8b2d350e715d094 (diff)
Merge "PolicyAudit creation when deploy/undeploy triggered."
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java26
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java4
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java4
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java24
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java10
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java118
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java33
-rw-r--r--main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java27
-rw-r--r--main/src/main/resources/META-INF/persistence.xml3
-rw-r--r--main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java41
-rw-r--r--main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java2
-rw-r--r--main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java30
-rw-r--r--main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java139
-rw-r--r--main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java96
-rw-r--r--main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java2
-rw-r--r--main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java4
-rw-r--r--main/src/test/resources/META-INF/persistence.xml3
17 files changed, 425 insertions, 141 deletions
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java
index 43b6b48b..2dab2996 100644
--- a/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/PapRestControllerV1.java
@@ -1,6 +1,6 @@
/*-
* ============LICENSE_START=======================================================
- * Copyright (C) 2019 Nordix Foundation.
+ * Copyright (C) 2019-2021 Nordix Foundation.
* Modifications Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -31,8 +31,10 @@ import java.net.HttpURLConnection;
import java.util.UUID;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.SecurityContext;
import org.onap.policy.models.base.PfModelException;
/**
@@ -71,12 +73,12 @@ public class PapRestControllerV1 {
public static final String VERSION_MINOR_NAME = "X-MinorVersion";
public static final String VERSION_MINOR_DESCRIPTION =
- "Used to request or communicate a MINOR version back from the client"
- + " to the server, and from the server back to the client";
+ "Used to request or communicate a MINOR version back from the client"
+ + " to the server, and from the server back to the client";
public static final String VERSION_PATCH_NAME = "X-PatchVersion";
public static final String VERSION_PATCH_DESCRIPTION = "Used only to communicate a PATCH version in a response for"
- + " troubleshooting purposes only, and will not be provided by" + " the client on request";
+ + " troubleshooting purposes only, and will not be provided by" + " the client on request";
public static final String VERSION_LATEST_NAME = "X-LatestVersion";
public static final String VERSION_LATEST_DESCRIPTION = "Used only to communicate an API's latest version";
@@ -95,6 +97,9 @@ public class PapRestControllerV1 {
public static final String AUTHORIZATION_ERROR_MESSAGE = "Authorization Error";
public static final String SERVER_ERROR_MESSAGE = "Internal Server Error";
+ @Context
+ SecurityContext securityContext;
+
/**
* Adds version headers to the response.
*
@@ -103,7 +108,7 @@ public class PapRestControllerV1 {
*/
public ResponseBuilder addVersionControlHeaders(ResponseBuilder respBuilder) {
return respBuilder.header(VERSION_MINOR_NAME, "0").header(VERSION_PATCH_NAME, "0").header(VERSION_LATEST_NAME,
- API_VERSION);
+ API_VERSION);
}
/**
@@ -122,6 +127,17 @@ public class PapRestControllerV1 {
}
/**
+ * Get the user principal name from security context.
+ * @return username as {@link String}
+ */
+ public String getPrincipal() {
+ if (securityContext != null) {
+ return securityContext.getUserPrincipal().getName();
+ }
+ return "";
+ }
+
+ /**
* Functions that throw {@link PfModelException}.
*/
@FunctionalInterface
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java
index 8f740117..276408f5 100644
--- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteControllerV1.java
@@ -139,7 +139,7 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 {
@ApiParam(value = "PDP Policy Name", required = true) @PathParam("name") String policyName) {
return doUndeployOperation(requestId, "undeploy policy failed",
- () -> provider.undeploy(new ToscaConceptIdentifierOptVersion(policyName, null)));
+ () -> provider.undeploy(new ToscaConceptIdentifierOptVersion(policyName, null), getPrincipal()));
}
/**
@@ -187,7 +187,7 @@ public class PdpGroupDeleteControllerV1 extends PapRestControllerV1 {
@ApiParam(value = "PDP Policy Version", required = true) @PathParam("version") String version) {
return doUndeployOperation(requestId, "undeploy policy failed",
- () -> provider.undeploy(new ToscaConceptIdentifierOptVersion(policyName, version)));
+ () -> provider.undeploy(new ToscaConceptIdentifierOptVersion(policyName, version), getPrincipal()));
}
/**
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java
index f80b1bd1..6f39a715 100644
--- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeleteProvider.java
@@ -93,8 +93,8 @@ public class PdpGroupDeleteProvider extends ProviderBase {
* @param policyIdent identifier of the policy to be undeployed
* @throws PfModelException if an error occurred
*/
- public void undeploy(ToscaConceptIdentifierOptVersion policyIdent) throws PfModelException {
- process(policyIdent, this::undeployPolicy);
+ public void undeploy(ToscaConceptIdentifierOptVersion policyIdent, String user) throws PfModelException {
+ process(user, policyIdent, this::undeployPolicy);
}
/**
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java
index f0504d71..fe2d8170 100644
--- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployControllerV1.java
@@ -51,8 +51,8 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 {
public static final String POLICY_STATUS_URI = "/policy/pap/v1/policies/status";
public static final String DEPLOYMENT_RESPONSE_MSG = "Use the policy status url to fetch the latest status. "
- + "Kindly note that when a policy is successfully undeployed,"
- + " it will no longer appear in policy status response.";
+ + "Kindly note that when a policy is successfully undeployed,"
+ + " it will no longer appear in policy status response.";
private static final Logger logger = LoggerFactory.getLogger(PdpGroupDeployControllerV1.class);
@@ -97,10 +97,10 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 {
// @formatter:on
public Response updateGroupPolicies(
- @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @ApiParam(value = "List of PDP Group Deployments", required = true) DeploymentGroups groups) {
-
- return doOperation(requestId, "update policy deployments failed", () -> provider.updateGroupPolicies(groups));
+ @HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
+ @ApiParam(value = "List of PDP Group Deployments", required = true) DeploymentGroups groups) {
+ return doOperation(requestId, "update policy deployments failed",
+ () -> provider.updateGroupPolicies(groups, getPrincipal()));
}
/**
@@ -142,10 +142,9 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 {
// @formatter:on
public Response deployPolicies(@HeaderParam(REQUEST_ID_NAME) @ApiParam(REQUEST_ID_PARAM_DESCRIPTION) UUID requestId,
- @ApiParam(value = "PDP Policies; only the name is required",
- required = true) PdpDeployPolicies policies) {
-
- return doOperation(requestId, "deploy policies failed", () -> provider.deployPolicies(policies));
+ @ApiParam(value = "PDP Policies; only the name is required", required = true) PdpDeployPolicies policies) {
+ return doOperation(requestId, "deploy policies failed",
+ () -> provider.deployPolicies(policies, getPrincipal()));
}
/**
@@ -160,15 +159,14 @@ public class PdpGroupDeployControllerV1 extends PapRestControllerV1 {
try {
runnable.run();
return addLoggingHeaders(addVersionControlHeaders(Response.status(Status.ACCEPTED)), requestId)
- .entity(new PdpGroupDeployResponse(DEPLOYMENT_RESPONSE_MSG, POLICY_STATUS_URI))
- .build();
+ .entity(new PdpGroupDeployResponse(DEPLOYMENT_RESPONSE_MSG, POLICY_STATUS_URI)).build();
} catch (PfModelException | PfModelRuntimeException e) {
logger.warn(errmsg, e);
var resp = new PdpGroupDeployResponse();
resp.setErrorDetails(e.getErrorResponse().getErrorMessage());
return addLoggingHeaders(addVersionControlHeaders(Response.status(e.getErrorResponse().getResponseCode())),
- requestId).entity(resp).build();
+ requestId).entity(resp).build();
}
}
}
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java
index 75affaf3..151e5145 100644
--- a/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/PdpGroupDeployProvider.java
@@ -85,16 +85,17 @@ public class PdpGroupDeployProvider extends ProviderBase {
* Updates policies in specific PDP groups.
*
* @param groups PDP group deployments to be updated
+ * @param user user triggering deployment
* @throws PfModelException if an error occurred
*/
- public void updateGroupPolicies(DeploymentGroups groups) throws PfModelException {
+ public void updateGroupPolicies(DeploymentGroups groups, String user) throws PfModelException {
ValidationResult result = groups.validatePapRest();
if (!result.isValid()) {
String msg = result.getResult().trim();
throw new PfModelException(Status.BAD_REQUEST, msg);
}
- process(groups, this::updateGroups);
+ process(user, groups, this::updateGroups);
}
/**
@@ -383,9 +384,10 @@ public class PdpGroupDeployProvider extends ProviderBase {
* Deploys or updates PDP policies using the simple API.
*
* @param policies PDP policies
+ * @param user user triggering deployment
* @throws PfModelException if an error occurred
*/
- public void deployPolicies(PdpDeployPolicies policies) throws PfModelException {
+ public void deployPolicies(PdpDeployPolicies policies, String user) throws PfModelException {
try {
MyPdpDeployPolicies checked = coder.convert(policies, MyPdpDeployPolicies.class);
ValidationResult result = new BeanValidator().validateTop(PdpDeployPolicies.class.getSimpleName(), checked);
@@ -397,7 +399,7 @@ public class PdpGroupDeployProvider extends ProviderBase {
throw new PfModelException(Status.INTERNAL_SERVER_ERROR, "cannot decode request", e);
}
- process(policies, this::deploySimplePolicies);
+ process(user, policies, this::deploySimplePolicies);
}
/**
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java
new file mode 100644
index 00000000..c200bb13
--- /dev/null
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/PolicyAuditManager.java
@@ -0,0 +1,118 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.List;
+import lombok.AccessLevel;
+import lombok.Getter;
+import org.onap.policy.models.pap.concepts.PolicyAudit;
+import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction;
+import org.onap.policy.models.provider.PolicyModelsProvider;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Class to manage operations related to audit of policies.
+ *
+ * @author Adheli Tavares (adheli.tavares@est.tech)
+ *
+ */
+public class PolicyAuditManager {
+ private static final Logger logger = LoggerFactory.getLogger(PolicyAuditManager.class);
+
+ /*
+ * Set of policies to be audited.
+ */
+ @Getter(value = AccessLevel.PROTECTED)
+ private List<PolicyAudit> auditRecords = new ArrayList<>();
+
+ private PolicyModelsProvider provider;
+
+ /**
+ * Default constructor.
+ */
+ public PolicyAuditManager(PolicyModelsProvider provider) {
+ this.provider = provider;
+ }
+
+ /**
+ * Builds an audit object.
+ *
+ * @param policyId policy under action
+ * @param pdpGroup pdpGroup which the policy is related to
+ * @param pdpType pdp type
+ * @param action which action was taken on policy
+ * @param user which user started the action
+ * @return PolicyAudit object
+ */
+ public PolicyAudit buildAudit(ToscaConceptIdentifier policyId, String pdpGroup, String pdpType, AuditAction action,
+ String user) {
+ return PolicyAudit.builder().action(action).pdpGroup(pdpGroup).pdpType(pdpType).policy(policyId)
+ .timestamp(Instant.now().truncatedTo(ChronoUnit.SECONDS)).user(user).build();
+ }
+
+ /**
+ * Add deployments to the list of audits.
+ *
+ * @param policyId policy under deploy
+ * @param pdpGroup PdpGroup
+ * @param pdpType PDP type
+ * @param user user whom triggered the deploy
+ */
+ public void addDeploymentAudit(ToscaConceptIdentifier policyId, String pdpGroup, String pdpType, String user) {
+ logger.info("Registering a deploy for policy {}", policyId);
+ auditRecords.add(buildAudit(policyId, pdpGroup, pdpType, AuditAction.DEPLOYMENT, user));
+ }
+
+ /**
+ * Add deployments to the list of audits.
+ *
+ * @param policyId policy under undeploy
+ * @param pdpGroup pdpGroup which the policy is related to
+ * @param pdpType PDP type
+ * @param user user whom triggered the undeploy
+ */
+ public void addUndeploymentAudit(ToscaConceptIdentifier policyId, String pdpGroup, String pdpType, String user) {
+ logger.info("Registering an undeploy for policy {}", policyId);
+ auditRecords.add(buildAudit(policyId, pdpGroup, pdpType, AuditAction.UNDEPLOYMENT, user));
+ }
+
+ /**
+ * Create audit registers in DB.
+ * If an exception happens, list is not cleared up, exception is logged.
+ */
+ public void saveRecordsToDb() {
+ if (!auditRecords.isEmpty()) {
+ logger.info("sending audit records to database: {}", auditRecords);
+ try {
+ provider.createAuditRecords(auditRecords);
+ auditRecords.clear();
+ } catch (RuntimeException excpt) {
+ // not throwing the exception to not stop the main request.
+ logger.error("Failed saving the audit records in DB.", excpt);
+ }
+ }
+ }
+}
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java b/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java
index 6fa0ef3d..d5ec8563 100644
--- a/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/ProviderBase.java
@@ -52,6 +52,7 @@ import org.onap.policy.pap.main.notification.PolicyNotifier;
*/
public abstract class ProviderBase {
public static final String DB_ERROR_MSG = "DB error";
+ public static final String DEFAULT_USER = "PAP";
/**
* Lock used when updating PDPs.
@@ -86,11 +87,13 @@ public abstract class ProviderBase {
/**
* Processes a policy request.
*
+ * @param user user triggering request
* @param request PDP policy request
* @param processor function that processes the request
* @throws PfModelException if an error occurred
*/
- protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
+ protected <T> void process(String user, T request, BiConsumerWithEx<SessionData, T> processor)
+ throws PfModelException {
synchronized (updateLock) {
SessionData data;
@@ -98,7 +101,7 @@ public abstract class ProviderBase {
try (PolicyModelsProvider dao = daoFactory.create()) {
- data = new SessionData(dao);
+ data = new SessionData(dao, user);
processor.accept(data, request);
// make all of the DB updates
@@ -120,6 +123,17 @@ public abstract class ProviderBase {
}
/**
+ * Processes a policy request.
+ *
+ * @param request PDP policy request
+ * @param processor function that processes the request
+ * @throws PfModelException if an error occurred
+ */
+ protected <T> void process(T request, BiConsumerWithEx<SessionData, T> processor) throws PfModelException {
+ this.process(DEFAULT_USER, request, processor);
+ }
+
+ /**
* Process a single policy from the request.
*
* @param data session data
@@ -127,14 +141,14 @@ public abstract class ProviderBase {
* @throws PfModelException if an error occurred
*/
protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
- throws PfModelException {
+ throws PfModelException {
ToscaPolicy policy = getPolicy(data, desiredPolicy);
Collection<PdpGroup> groups = getGroups(data, policy.getTypeIdentifier());
if (groups.isEmpty()) {
throw new PfModelException(Status.BAD_REQUEST, "policy not supported by any PDP group: "
- + desiredPolicy.getName() + " " + desiredPolicy.getVersion());
+ + desiredPolicy.getName() + " " + desiredPolicy.getVersion());
}
var updater = makeUpdater(data, policy, desiredPolicy);
@@ -155,7 +169,7 @@ public abstract class ProviderBase {
* @return a function to update a subgroup
*/
protected abstract Updater makeUpdater(SessionData data, ToscaPolicy policy,
- ToscaConceptIdentifierOptVersion desiredPolicy);
+ ToscaConceptIdentifierOptVersion desiredPolicy);
/**
* Finds the active PDP group(s) that supports the given policy type.
@@ -167,7 +181,7 @@ public abstract class ProviderBase {
* @throws PfModelException if an error occurred
*/
private Collection<PdpGroup> getGroups(SessionData data, ToscaConceptIdentifier policyType)
- throws PfModelException {
+ throws PfModelException {
return data.getActivePdpGroupsByPolicyType(policyType);
}
@@ -180,8 +194,7 @@ public abstract class ProviderBase {
* @param updater function to update a group
* @throws PfModelException if an error occurred
*/
- private void upgradeGroup(SessionData data, PdpGroup group, Updater updater)
- throws PfModelException {
+ private void upgradeGroup(SessionData data, PdpGroup group, Updater updater) throws PfModelException {
var updated = false;
@@ -251,14 +264,14 @@ public abstract class ProviderBase {
ToscaPolicy policy = data.getPolicy(ident);
if (policy == null) {
throw new PfModelRuntimeException(Status.NOT_FOUND,
- "cannot find policy: " + ident.getName() + " " + ident.getVersion());
+ "cannot find policy: " + ident.getName() + " " + ident.getVersion());
}
return policy;
} catch (PfModelException e) {
throw new PfModelRuntimeException(e.getErrorResponse().getResponseCode(),
- e.getErrorResponse().getErrorMessage(), e);
+ e.getErrorResponse().getErrorMessage(), e);
}
}
diff --git a/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java b/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java
index 235c852e..32103159 100644
--- a/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java
+++ b/main/src/main/java/org/onap/policy/pap/main/rest/SessionData.java
@@ -31,6 +31,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+import lombok.Getter;
import org.apache.commons.lang3.tuple.Pair;
import org.onap.policy.models.base.PfModelException;
import org.onap.policy.models.pap.concepts.PolicyNotification;
@@ -104,19 +105,29 @@ public class SessionData {
private Set<ToscaConceptIdentifier> policiesToBeUndeployed = new HashSet<>();
/**
+ * User starting requests.
+ */
+ @Getter
+ private final String user;
+
+ /**
* Tracks policy deployment status so notifications can be generated.
*/
private final DeploymentStatus deployStatus;
+ private PolicyAuditManager auditManager;
/**
* Constructs the object.
*
* @param dao DAO provider
+ * @param user user triggering the request
*/
- public SessionData(PolicyModelsProvider dao) {
+ public SessionData(PolicyModelsProvider dao, String user) {
this.dao = dao;
this.deployStatus = makeDeploymentStatus(dao);
+ this.auditManager = makePolicyAuditManager(dao);
+ this.user = user;
}
/**
@@ -435,6 +446,9 @@ public class SessionData {
dao.updatePdpGroups(updated.stream().map(GroupData::getGroup).collect(Collectors.toList()));
}
+ // send audits records to DB
+ auditManager.saveRecordsToDb();
+
// flush deployment status records to the DB
deployStatus.flush(notification);
}
@@ -459,12 +473,13 @@ public class SessionData {
* @param pdpType PDP type (i.e., PdpSubGroup) containing the PDP of interest
* @throws PfModelException if an error occurred
*/
- protected void trackDeploy(ToscaPolicy policy, Collection<String> pdps, String pdpGroup,
- String pdpType) throws PfModelException {
+ protected void trackDeploy(ToscaPolicy policy, Collection<String> pdps, String pdpGroup, String pdpType)
+ throws PfModelException {
ToscaConceptIdentifier policyId = policy.getIdentifier();
policiesToBeDeployed.put(policyId, policy);
addData(policyId, pdps, pdpGroup, pdpType, true);
+ auditManager.addDeploymentAudit(policyId, pdpGroup, pdpType, user);
}
/**
@@ -479,7 +494,9 @@ public class SessionData {
protected void trackUndeploy(ToscaConceptIdentifier policyId, Collection<String> pdps, String pdpGroup,
String pdpType) throws PfModelException {
policiesToBeUndeployed.add(policyId);
+
addData(policyId, pdps, pdpGroup, pdpType, false);
+ auditManager.addUndeploymentAudit(policyId, pdpGroup, pdpType, user);
}
/**
@@ -511,4 +528,8 @@ public class SessionData {
protected DeploymentStatus makeDeploymentStatus(PolicyModelsProvider dao) {
return new DeploymentStatus(dao);
}
+
+ protected PolicyAuditManager makePolicyAuditManager(PolicyModelsProvider dao) {
+ return new PolicyAuditManager(dao);
+ }
}
diff --git a/main/src/main/resources/META-INF/persistence.xml b/main/src/main/resources/META-INF/persistence.xml
index a9624f35..f3fdcc4b 100644
--- a/main/src/main/resources/META-INF/persistence.xml
+++ b/main/src/main/resources/META-INF/persistence.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
============LICENSE_START=======================================================
- Copyright (C) 2019-2020 Nordix Foundation.
+ Copyright (C) 2019-2021 Nordix Foundation.
Modifications Copyright (C) 2021 AT&T Intellectual Property.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,6 +32,7 @@
<class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpPolicyStatus</class>
<class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics</class>
<class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup</class>
+ <class>org.onap.policy.models.pap.persistence.concepts.JpaPolicyAudit</class>
<class>org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignment</class>
<class>org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignments</class>
<class>org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityType</class>
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java
index d8e6963f..aafcd40f 100644
--- a/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java
+++ b/main/src/test/java/org/onap/policy/pap/main/rest/PapRestControllerV1Test.java
@@ -3,6 +3,7 @@
* ONAP PAP
* ================================================================================
* Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,24 +24,44 @@ package org.onap.policy.pap.main.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import java.security.Principal;
import java.util.UUID;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.core.SecurityContext;
+import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.mockito.internal.stubbing.answers.Returns;
public class PapRestControllerV1Test {
- private PapRestControllerV1 ctlr;
+ @Mock
+ SecurityContext mockSecurityContext;
+
+ @InjectMocks
+ PapRestControllerV1 mockController;
+
+ private AutoCloseable closeable;
private ResponseBuilder bldr;
@Before
public void setUp() {
- ctlr = new PapRestControllerV1();
bldr = Response.status(Response.Status.OK);
+ closeable = MockitoAnnotations.openMocks(this);
+ }
+
+ @After
+ public void after() throws Exception {
+ closeable.close();
}
@Test
@@ -53,7 +74,7 @@ public class PapRestControllerV1Test {
@Test
public void testAddVersionControlHeaders() {
- Response resp = ctlr.addVersionControlHeaders(bldr).build();
+ Response resp = mockController.addVersionControlHeaders(bldr).build();
assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_MINOR_NAME));
assertEquals("0", resp.getHeaderString(PapRestControllerV1.VERSION_PATCH_NAME));
assertEquals("1.0.0", resp.getHeaderString(PapRestControllerV1.VERSION_LATEST_NAME));
@@ -61,14 +82,24 @@ public class PapRestControllerV1Test {
@Test
public void testAddLoggingHeaders_Null() {
- Response resp = ctlr.addLoggingHeaders(bldr, null).build();
+ Response resp = mockController.addLoggingHeaders(bldr, null).build();
assertNotNull(resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME));
}
@Test
public void testAddLoggingHeaders_NonNull() {
UUID uuid = UUID.randomUUID();
- Response resp = ctlr.addLoggingHeaders(bldr, uuid).build();
+ Response resp = mockController.addLoggingHeaders(bldr, uuid).build();
assertEquals(uuid.toString(), resp.getHeaderString(PapRestControllerV1.REQUEST_ID_NAME));
}
+
+ @Test
+ public void testGetPrincipal() {
+ assertThat(new PapRestControllerV1().getPrincipal()).isEmpty();
+
+ Principal mockUser = mock(Principal.class, new Returns("myFakeUser"));
+ when(mockSecurityContext.getUserPrincipal()).thenReturn(mockUser);
+
+ assertEquals("myFakeUser", mockController.getPrincipal());
+ }
}
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java
index f341b1a9..f5798fd5 100644
--- a/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java
+++ b/main/src/test/java/org/onap/policy/pap/main/rest/ProviderSuper.java
@@ -3,6 +3,7 @@
* ONAP PAP
* ================================================================================
* Copyright (C) 2019-2021 AT&T Intellectual Property. All rights reserved.
+ * Modifications Copyright (C) 2021 Nordix Foundation.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,6 +62,7 @@ import org.onap.policy.pap.main.notification.PolicyNotifier;
*/
public class ProviderSuper {
private static final Coder coder = new StandardCoder();
+ public static final String DEFAULT_USER = "PAP_TEST";
@Mock
protected PolicyModelsProvider dao;
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java
index 30b5b16f..4041de90 100644
--- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java
+++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeleteProvider.java
@@ -38,7 +38,6 @@ import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.ws.rs.core.Response.Status;
-import org.assertj.core.api.Assertions;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
@@ -71,7 +70,6 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
private ToscaConceptIdentifier ident;
private Updater updater;
-
@AfterClass
public static void tearDownAfterClass() {
Registry.newRegistry();
@@ -120,15 +118,15 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
when(session.getGroup(GROUP1_NAME)).thenReturn(group);
assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
- .hasMessage("group is still ACTIVE");
+ .hasMessage("group is still ACTIVE");
}
@Test
public void testDeleteGroup_NotFound() throws Exception {
assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isInstanceOf(PfModelException.class)
- .hasMessage("group not found")
- .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode())
- .isEqualTo(Status.NOT_FOUND);
+ .hasMessage("group not found")
+ .extracting(ex -> ((PfModelException) ex).getErrorResponse().getResponseCode())
+ .isEqualTo(Status.NOT_FOUND);
}
@Test
@@ -157,11 +155,6 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
assertThatThrownBy(() -> prov.deleteGroup(GROUP1_NAME)).isSameAs(ex);
}
- @Test
- public void testUndeploy_testUndeployPolicy() {
- Assertions.assertThatCode(() -> prov.undeploy(optIdent)).doesNotThrowAnyException();
- }
-
/**
* Tests using a real provider, just to verify end-to-end functionality.
*
@@ -176,7 +169,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
when(dao.getFilteredPdpGroups(any())).thenReturn(Arrays.asList(group));
when(dao.getFilteredPolicyList(any())).thenReturn(Arrays.asList(policy1));
- new PdpGroupDeleteProvider().undeploy(fullIdent);
+ new PdpGroupDeleteProvider().undeploy(fullIdent, DEFAULT_USER);
// should have updated the old group
List<PdpGroup> updates = getGroupUpdates();
@@ -201,8 +194,8 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
public void testUndeployPolicy_NotFound() throws Exception {
when(session.isUnchanged()).thenReturn(true);
- assertThatThrownBy(() -> prov.undeploy(optIdent)).isInstanceOf(PfModelException.class)
- .hasMessage("policy does not appear in any PDP group: policyA null");
+ assertThatThrownBy(() -> prov.undeploy(optIdent, DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessage("policy does not appear in any PDP group: policyA null");
}
@Test
@@ -212,7 +205,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
prov = spy(prov);
doThrow(exc).when(prov).processPolicy(any(), any());
- assertThatThrownBy(() -> prov.undeploy(optIdent)).isSameAs(exc);
+ assertThatThrownBy(() -> prov.undeploy(optIdent, null)).isSameAs(exc);
}
@Test
@@ -222,7 +215,9 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
prov = spy(prov);
doThrow(exc).when(prov).processPolicy(any(), any());
- assertThatThrownBy(() -> prov.undeploy(optIdent)).isSameAs(exc);
+ // process method catches RuntimeException and re-throws as PfModelException
+ assertThatThrownBy(() -> prov.undeploy(fullIdent, null)).isInstanceOf(PfModelException.class)
+ .hasRootCauseMessage(EXPECTED_EXCEPTION);
}
@Test
@@ -283,7 +278,6 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
assertEquals(origSize, subgroup.getPolicies().size());
}
-
private class MyProvider extends PdpGroupDeleteProvider {
@Override
@@ -293,7 +287,7 @@ public class TestPdpGroupDeleteProvider extends ProviderSuper {
@Override
protected void processPolicy(SessionData data, ToscaConceptIdentifierOptVersion desiredPolicy)
- throws PfModelException {
+ throws PfModelException {
// do nothing
}
}
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java
index 9edba58b..d0039c6d 100644
--- a/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java
+++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPdpGroupDeployProvider.java
@@ -72,7 +72,6 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
private PdpGroupDeployProvider prov;
-
@AfterClass
public static void tearDownAfterClass() {
Registry.newRegistry();
@@ -111,14 +110,13 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
policies.add(new ToscaConceptIdentifier(POLICY3_NAME, POLICY3_VERSION));
when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json"))
- .thenReturn(loadPolicies("createGroupNewPolicy2.json"))
- .thenReturn(loadPolicies("daoPolicyList.json"));
+ .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json"));
// add = POST
DeploymentGroups depgroups = toDeploymentGroups(groups);
depgroups.getGroups().get(0).getDeploymentSubgroups().get(0).setAction(Action.POST);
- prov.updateGroupPolicies(depgroups);
+ prov.updateGroupPolicies(depgroups, DEFAULT_USER);
assertEquals(newgrp.toString(), dbgroup.toString());
assertGroupUpdate(dbgroup, dbgroup.getPdpSubgroups().get(0));
@@ -144,13 +142,12 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
final ToscaConceptIdentifier policyId1 = policies.remove(0);
when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json"))
- .thenReturn(loadPolicies("createGroupNewPolicy2.json"))
- .thenReturn(loadPolicies("daoPolicyList.json"));
+ .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json"));
DeploymentGroups depgroups = toDeploymentGroups(groups);
depgroups.getGroups().get(0).getDeploymentSubgroups().get(0).setAction(Action.DELETE);
- prov.updateGroupPolicies(depgroups);
+ prov.updateGroupPolicies(depgroups, DEFAULT_USER);
// only the first policy should remain
policies.clear();
@@ -198,10 +195,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
depgroups.setGroups(Arrays.asList(depgroup));
when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json"))
- .thenReturn(loadPolicies("daoPolicyList.json"))
- .thenReturn(loadPolicies("createGroupNewPolicy2.json"));
+ .thenReturn(loadPolicies("daoPolicyList.json")).thenReturn(loadPolicies("createGroupNewPolicy2.json"));
- prov.updateGroupPolicies(depgroups);
+ prov.updateGroupPolicies(depgroups, DEFAULT_USER);
assertEquals(newgrp.toString(), dbgroup.toString());
assertGroupUpdate(dbgroup, dbgroup.getPdpSubgroups().get(0));
@@ -217,7 +213,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
// something different in this subgroup
group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION));
- prov.updateGroupPolicies(toDeploymentGroups(groups));
+ prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER);
assertEquals(newgrp.toString(), group.toString());
assertGroupUpdate(group, group.getPdpSubgroups().get(0));
@@ -225,7 +221,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
@Test
public void testUpdateGroupPolicies_EmptyRequest() throws Exception {
- prov.updateGroupPolicies(toDeploymentGroups(loadPdpGroups("emptyGroups.json")));
+ prov.updateGroupPolicies(toDeploymentGroups(loadPdpGroups("emptyGroups.json")), DEFAULT_USER);
// no groups, so no action should have been taken
assertNoGroupAction();
@@ -233,8 +229,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
@Test
public void testUpdateGroupPolicies_InvalidRequest() throws Exception {
- assertThatThrownBy(() -> prov.updateGroupPolicies(new DeploymentGroups())).isInstanceOf(PfModelException.class)
- .hasMessageContaining("is null");
+ assertThatThrownBy(() -> prov.updateGroupPolicies(new DeploymentGroups(), DEFAULT_USER))
+ .isInstanceOf(PfModelException.class).hasMessageContaining("is null");
assertNoGroupAction();
}
@@ -248,9 +244,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
// group not found
when(dao.getPdpGroups(groupName)).thenReturn(Collections.emptyList());
- assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups)))
- .isInstanceOf(PfModelException.class).hasMessageContaining(groupName)
- .hasMessageContaining("unknown group");
+ assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER))
+ .isInstanceOf(PfModelException.class).hasMessageContaining(groupName)
+ .hasMessageContaining("unknown group");
assertNoGroupAction();
}
@@ -263,7 +259,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
PdpGroup group = new PdpGroup(groups.getGroups().get(0));
when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
- prov.updateGroupPolicies(toDeploymentGroups(groups));
+ prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER);
assertNoGroupAction();
}
@@ -274,10 +270,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
PdpGroup group = loadPdpGroups("deployGroups.json").getGroups().get(0);
when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
- assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups)))
- .isInstanceOf(PfModelException.class).hasMessageContaining("pdpTypeB")
- .hasMessageContaining("unknown subgroup");
-
+ assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER))
+ .isInstanceOf(PfModelException.class).hasMessageContaining("pdpTypeB")
+ .hasMessageContaining("unknown subgroup");
assertNoGroupAction();
}
@@ -292,7 +287,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
// something different in this subgroup
group.getPdpSubgroups().get(0).getPolicies().add(new ToscaConceptIdentifier(POLICY2_NAME, POLICY2_VERSION));
- prov.updateGroupPolicies(toDeploymentGroups(groups));
+ prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER);
assertEquals(newgrp.toString(), group.toString());
assertGroupUpdate(group, group.getPdpSubgroups().get(0));
@@ -311,10 +306,10 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
// unknown policy
when(dao.getFilteredPolicyList(any())).thenReturn(Collections.emptyList());
- assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups)))
- .isInstanceOf(PfModelException.class)
- .hasMessageContaining(newgrp.getPdpSubgroups().get(0).getPolicies().get(0).getName())
- .hasMessageContaining("unknown policy");
+ assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER))
+ .isInstanceOf(PfModelException.class)
+ .hasMessageContaining(newgrp.getPdpSubgroups().get(0).getPolicies().get(0).getName())
+ .hasMessageContaining("unknown policy");
assertNoGroupAction();
}
@@ -341,10 +336,9 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
subgrp.getPolicies().add(policyId3);
when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("createGroupNewPolicy.json"))
- .thenReturn(loadPolicies("createGroupNewPolicy2.json"))
- .thenReturn(loadPolicies("daoPolicyList.json"));
+ .thenReturn(loadPolicies("createGroupNewPolicy2.json")).thenReturn(loadPolicies("daoPolicyList.json"));
- prov.updateGroupPolicies(toDeploymentGroups(groups));
+ prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER);
Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
Collections.sort(group.getPdpSubgroups().get(0).getPolicies());
@@ -372,7 +366,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
String version = ident.getVersion();
ident.setVersion("1");
- prov.updateGroupPolicies(toDeploymentGroups(groups));
+ prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER);
// restore full type before comparing
ident.setVersion(version);
@@ -396,9 +390,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
// use incorrect version prefix
newgrp.getPdpSubgroups().get(0).getPolicies().get(0).setVersion("9");
- assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups)))
- .isInstanceOf(PfModelException.class)
- .hasMessageContaining("different version already deployed");
+ assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(groups), DEFAULT_USER))
+ .isInstanceOf(PfModelException.class).hasMessageContaining("different version already deployed");
assertNoGroupAction();
}
@@ -410,7 +403,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
PdpGroup group = new PdpGroup(newgrp);
when(dao.getPdpGroups(group.getName())).thenReturn(Arrays.asList(group));
- prov.updateGroupPolicies(toDeploymentGroups(dbgroups));
+ prov.updateGroupPolicies(toDeploymentGroups(dbgroups), DEFAULT_USER);
Collections.sort(newgrp.getPdpSubgroups().get(0).getPolicies());
Collections.sort(group.getPdpSubgroups().get(0).getPolicies());
@@ -437,9 +430,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json"));
- assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(dbgroups)))
- .isInstanceOf(PfModelException.class)
- .hasMessageContaining("different version already deployed");
+ assertThatThrownBy(() -> prov.updateGroupPolicies(toDeploymentGroups(dbgroups), DEFAULT_USER))
+ .isInstanceOf(PfModelException.class).hasMessageContaining("different version already deployed");
assertNoGroupAction();
}
@@ -463,16 +455,16 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
when(dao.getFilteredPolicyList(any())).thenReturn(loadPolicies("daoPolicyList.json"));
- assertThatThrownBy(() -> prov.updateGroupPolicies(groups)).isInstanceOf(PfModelException.class)
- .hasMessageContaining(newgrp.getPdpSubgroups().get(0).getPolicies().get(0).getName())
- .hasMessageContaining("not a supported policy for the subgroup");
+ assertThatThrownBy(() -> prov.updateGroupPolicies(groups, DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining(newgrp.getPdpSubgroups().get(0).getPolicies().get(0).getName())
+ .hasMessageContaining("not a supported policy for the subgroup");
assertNoGroupAction();
}
@Test
public void testDeployPolicies() throws PfModelException {
- assertThatCode(() -> prov.deployPolicies(loadEmptyRequest())).doesNotThrowAnyException();
+ assertThatCode(() -> prov.deployPolicies(loadEmptyRequest(), DEFAULT_USER)).doesNotThrowAnyException();
}
/**
@@ -482,35 +474,35 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
public void testDeployPoliciesInvalidPolicies() throws Exception {
// valid list
PdpDeployPolicies policies0 = loadFile("PapPoliciesList.json", PdpDeployPolicies.class);
- assertThatCode(() -> prov.deployPolicies(policies0)).doesNotThrowAnyException();
+ assertThatCode(() -> prov.deployPolicies(policies0, DEFAULT_USER)).doesNotThrowAnyException();
// null list
PdpDeployPolicies policies = new PdpDeployPolicies();
- assertThatThrownBy(() -> prov.deployPolicies(policies)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("policies");
+ assertThatThrownBy(() -> prov.deployPolicies(policies, DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("policies");
// list containing null item
PdpDeployPolicies policies2 = loadFile("PapPoliciesNullItem.json", PdpDeployPolicies.class);
- assertThatThrownBy(() -> prov.deployPolicies(policies2)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("policies").hasMessageContaining("null");
+ assertThatThrownBy(() -> prov.deployPolicies(policies2, DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("policies").hasMessageContaining("null");
// list containing a policy with a null name
PdpDeployPolicies policies3 = loadFile("PapPoliciesNullPolicyName.json", PdpDeployPolicies.class);
- assertThatThrownBy(() -> prov.deployPolicies(policies3)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("policies").hasMessageContaining("policy-id").hasMessageContaining("null")
- .hasMessageNotContaining("\"value\"");
+ assertThatThrownBy(() -> prov.deployPolicies(policies3, DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("policies").hasMessageContaining("policy-id").hasMessageContaining("null")
+ .hasMessageNotContaining("\"value\"");
// list containing a policy with an invalid name
PdpDeployPolicies policies4 = loadFile("PapPoliciesInvalidPolicyName.json", PdpDeployPolicies.class);
- assertThatThrownBy(() -> prov.deployPolicies(policies4)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("policies").hasMessageContaining("policy-id")
- .hasMessageContaining("$ abc").hasMessageNotContaining("version");
+ assertThatThrownBy(() -> prov.deployPolicies(policies4, DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("policies").hasMessageContaining("policy-id").hasMessageContaining("$ abc")
+ .hasMessageNotContaining("version");
// list containing a policy with an invalid version
PdpDeployPolicies policies5 = loadFile("PapPoliciesInvalidPolicyVersion.json", PdpDeployPolicies.class);
- assertThatThrownBy(() -> prov.deployPolicies(policies5)).isInstanceOf(PfModelException.class)
- .hasMessageContaining("policies").hasMessageContaining("version").hasMessageContaining("abc123")
- .hasMessageNotContaining("policy-id");
+ assertThatThrownBy(() -> prov.deployPolicies(policies5, DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessageContaining("policies").hasMessageContaining("version").hasMessageContaining("abc123")
+ .hasMessageNotContaining("policy-id");
}
/**
@@ -532,7 +524,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
PdpDeployPolicies depreq = loadRequest();
depreq.getPolicies().get(0).setName("policy.some");
- prov.deployPolicies(depreq);
+ prov.deployPolicies(depreq, DEFAULT_USER);
assertGroup(getGroupUpdates(), GROUP1_NAME);
@@ -545,7 +537,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
@Test
public void testDeploySimplePolicies() throws Exception {
- assertThatCode(() -> prov.deployPolicies(loadEmptyRequest())).doesNotThrowAnyException();
+ assertThatCode(() -> prov.deployPolicies(loadEmptyRequest(), DEFAULT_USER)).doesNotThrowAnyException();
}
@Test
@@ -553,7 +545,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
PfModelException exc = new PfModelException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
when(dao.getFilteredPdpGroups(any())).thenThrow(exc);
- assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isSameAs(exc);
+ assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isSameAs(exc);
}
@Test
@@ -561,7 +553,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
PfModelRuntimeException exc = new PfModelRuntimeException(Status.BAD_REQUEST, EXPECTED_EXCEPTION);
when(dao.getFilteredPdpGroups(any())).thenThrow(exc);
- assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isSameAs(exc);
+ assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isSameAs(exc);
}
@Test
@@ -569,15 +561,16 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
RuntimeException exc = new RuntimeException(EXPECTED_EXCEPTION);
when(dao.getFilteredPolicyList(any())).thenThrow(exc);
- assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isInstanceOf(PfModelException.class).hasCause(exc);
+ assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasCause(exc);
}
@Test
public void testDeploySimplePolicies_NoGroups() throws Exception {
when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("emptyGroups.json"));
- assertThatThrownBy(() -> prov.deployPolicies(loadRequest())).isInstanceOf(PfModelException.class)
- .hasMessage("policy not supported by any PDP group: policyA 1.2.3");
+ assertThatThrownBy(() -> prov.deployPolicies(loadRequest(), DEFAULT_USER)).isInstanceOf(PfModelException.class)
+ .hasMessage("policy not supported by any PDP group: policyA 1.2.3");
}
@Test
@@ -596,7 +589,7 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao.json"));
- prov.deployPolicies(loadRequest());
+ prov.deployPolicies(loadRequest(), DEFAULT_USER);
assertGroup(getGroupUpdates(), GROUP1_NAME);
@@ -615,8 +608,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroupDao_DiffVers.json"));
PdpDeployPolicies req = loadRequest();
- assertThatThrownBy(() -> prov.deployPolicies(req)).isInstanceOf(PfModelRuntimeException.class)
- .hasMessageContaining("pdpTypeC").hasMessageContaining("different version already deployed");
+ assertThatThrownBy(() -> prov.deployPolicies(req, DEFAULT_USER)).isInstanceOf(PfModelRuntimeException.class)
+ .hasMessageContaining("pdpTypeC").hasMessageContaining("different version already deployed");
verify(dao, never()).createPdpGroups(any());
verify(dao, never()).updatePdpGroups(any());
@@ -630,15 +623,14 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
when(dao.getFilteredPdpGroups(any())).thenReturn(loadGroups("upgradeGroup_NoPdpsDao.json"));
PdpDeployPolicies req = loadRequest();
- assertThatThrownBy(() -> prov.deployPolicies(req)).isInstanceOf(PfModelRuntimeException.class)
- .hasMessage("group " + GROUP1_NAME + " subgroup " + PDP1_TYPE + " has no active PDPs");
+ assertThatThrownBy(() -> prov.deployPolicies(req, DEFAULT_USER)).isInstanceOf(PfModelRuntimeException.class)
+ .hasMessage("group " + GROUP1_NAME + " subgroup " + PDP1_TYPE + " has no active PDPs");
verify(dao, never()).createPdpGroups(any());
verify(dao, never()).updatePdpGroups(any());
verify(reqmap, never()).addRequest(any(PdpUpdate.class));
}
-
protected void assertUpdate(List<PdpUpdate> updates, String groupName, String pdpType, String pdpName) {
PdpUpdate update = updates.remove(0);
@@ -669,9 +661,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
assertEquals(subgrp.getPdpType(), pdpUpdate.getPdpSubgroup());
- List<ToscaConceptIdentifier> pdpPolicies =
- pdpUpdate.getPoliciesToBeDeployed().stream().map(ToscaPolicy::getIdentifier)
- .collect(Collectors.toList());
+ List<ToscaConceptIdentifier> pdpPolicies = pdpUpdate.getPoliciesToBeDeployed().stream()
+ .map(ToscaPolicy::getIdentifier).collect(Collectors.toList());
Collections.sort(pdpPolicies);
assertThat(subgrp.getPolicies()).containsAll(pdpPolicies);
@@ -720,8 +711,8 @@ public class TestPdpGroupDeployProvider extends ProviderSuper {
DeploymentGroup group = new DeploymentGroup();
group.setName(dbgroup.getName());
- group.setDeploymentSubgroups(dbgroup.getPdpSubgroups().stream().map(this::toDeploymentSubGroup)
- .collect(Collectors.toList()));
+ group.setDeploymentSubgroups(
+ dbgroup.getPdpSubgroups().stream().map(this::toDeploymentSubGroup).collect(Collectors.toList()));
return group;
}
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java
new file mode 100644
index 00000000..b33c0ef6
--- /dev/null
+++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestPolicyAuditManager.java
@@ -0,0 +1,96 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * Copyright (C) 2021 Nordix Foundation.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ * ============LICENSE_END=========================================================
+ */
+
+package org.onap.policy.pap.main.rest;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doThrow;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.policy.common.utils.services.Registry;
+import org.onap.policy.models.base.PfModelRuntimeException;
+import org.onap.policy.models.pap.concepts.PolicyAudit.AuditAction;
+import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
+
+
+public class TestPolicyAuditManager extends ProviderSuper {
+
+ private static final ToscaConceptIdentifier MY_POLICY = new ToscaConceptIdentifier("myPolicy", "1.0.0");
+ private static final String GROUP_A = "pdpGroup-A";
+ private static final String GROUP_B = "pdpGroup-B";
+ private static final String PDP_TYPE = "typeABC";
+ private static final String USER = "healthcheck";
+
+ PolicyAuditManager auditManager;
+
+ /**
+ * Setup the test variables.
+ */
+ @Override
+ @Before
+ public void setUp() throws Exception {
+ super.setUp();
+ auditManager = new PolicyAuditManager(dao);
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() {
+ Registry.newRegistry();
+ }
+
+ @Test
+ public void testDeployments() {
+ auditManager.addDeploymentAudit(MY_POLICY, GROUP_A, PDP_TYPE, USER);
+ auditManager.addUndeploymentAudit(MY_POLICY, GROUP_B, PDP_TYPE, USER);
+
+ assertThat(auditManager.getAuditRecords()).hasSize(2);
+ assertEquals(AuditAction.DEPLOYMENT, auditManager.getAuditRecords().get(0).getAction());
+ assertEquals(AuditAction.UNDEPLOYMENT, auditManager.getAuditRecords().get(1).getAction());
+
+ auditManager.saveRecordsToDb();
+
+ assertThat(auditManager.getAuditRecords()).isEmpty();
+ }
+
+ @Test
+ public void testSaveRecordsToDb_EmptyList() {
+ assertThat(auditManager.getAuditRecords()).isEmpty();;
+ auditManager.saveRecordsToDb();
+
+ assertThatCode(() -> auditManager.saveRecordsToDb()).doesNotThrowAnyException();
+ }
+
+ @Test
+ public void testSaveRecordsToDb_Exception() {
+ auditManager.addDeploymentAudit(MY_POLICY, GROUP_A, PDP_TYPE, USER);
+
+ assertThat(auditManager.getAuditRecords()).hasSize(1);
+
+ doThrow(PfModelRuntimeException.class).when(dao).createAuditRecords(any());
+ auditManager.saveRecordsToDb();
+
+ assertThat(auditManager.getAuditRecords()).isNotEmpty();
+ }
+}
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java
index ce032647..ec7977c6 100644
--- a/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java
+++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestProviderBase.java
@@ -138,7 +138,7 @@ public class TestProviderBase extends ProviderSuper {
public void testProcessPolicy_NoGroups() throws Exception {
when(dao.getFilteredPdpGroups(any())).thenReturn(Collections.emptyList());
- SessionData session = new SessionData(dao);
+ SessionData session = new SessionData(dao, DEFAULT_USER);
ToscaConceptIdentifierOptVersion ident = new ToscaConceptIdentifierOptVersion(POLICY1_NAME, POLICY1_VERSION);
assertThatThrownBy(() -> prov.processPolicy(session, ident)).isInstanceOf(PfModelException.class)
.hasMessage("policy not supported by any PDP group: policyA 1.2.3");
diff --git a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java
index ad249164..952a861d 100644
--- a/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java
+++ b/main/src/test/java/org/onap/policy/pap/main/rest/TestSessionData.java
@@ -99,7 +99,7 @@ public class TestSessionData extends ProviderSuper {
group1 = loadGroup("group1.json");
group2 = loadGroup("group2.json");
- session = new SessionData(dao);
+ session = new SessionData(dao, DEFAULT_USER);
}
@Test
@@ -561,7 +561,7 @@ public class TestSessionData extends ProviderSuper {
DeploymentStatus status = mock(DeploymentStatus.class);
- session = new SessionData(dao) {
+ session = new SessionData(dao, DEFAULT_USER) {
@Override
protected DeploymentStatus makeDeploymentStatus(PolicyModelsProvider dao) {
return status;
diff --git a/main/src/test/resources/META-INF/persistence.xml b/main/src/test/resources/META-INF/persistence.xml
index e49dafa4..21a3a8b7 100644
--- a/main/src/test/resources/META-INF/persistence.xml
+++ b/main/src/test/resources/META-INF/persistence.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
============LICENSE_START=======================================================
- Copyright (C) 2019-2020 Nordix Foundation.
+ Copyright (C) 2019-2021 Nordix Foundation.
Modifications Copyright (C) 2021 AT&T Intellectual Property.
================================================================================
Licensed under the Apache License, Version 2.0 (the "License");
@@ -32,6 +32,7 @@
<class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpPolicyStatus</class>
<class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpStatistics</class>
<class>org.onap.policy.models.pdp.persistence.concepts.JpaPdpSubGroup</class>
+ <class>org.onap.policy.models.pap.persistence.concepts.JpaPolicyAudit</class>
<class>org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignment</class>
<class>org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityAssignments</class>
<class>org.onap.policy.models.tosca.simple.concepts.JpaToscaCapabilityType</class>