Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Re-calculate historical risk score #789

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
* This file is part of Dependency-Track.
*
* 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
* Copyright (c) OWASP Foundation. All Rights Reserved.
*/
package org.dependencytrack.event;

import alpine.event.framework.Event;
import alpine.event.framework.SingletonCapableEvent;

/**
* Defines an {@link Event} used to trigger historical risk score metrics updates.
*
* @since 5.0.0
*/
public class HistoricalRiskScoreUpdateEvent extends SingletonCapableEvent {

private final boolean weightHistoryEnabled;

public HistoricalRiskScoreUpdateEvent() {
this(true);
}

public HistoricalRiskScoreUpdateEvent(final boolean weightHistoryEnabled) {
this.setSingleton(true);
this.weightHistoryEnabled = weightHistoryEnabled;
}

public boolean isWeightHistoryEnabled() {
return weightHistoryEnabled;
}

}
11 changes: 11 additions & 0 deletions src/main/java/org/dependencytrack/metrics/Metrics.java
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,17 @@ public static void updatePortfolioMetrics() {
StoredProcedures.execute(Procedure.UPDATE_PORTFOLIO_METRICS);
}


/**
* Update historical risk scores for the entire portfolio.
* <p>
*
* @since 5.0.0
*/
public static void updateHistoricalRiskScores() {
StoredProcedures.execute(Procedure.UPDATE_HISTORICAL_RISK_SCORES);
}

/**
* Update metrics for a given {@link Project}.
* <p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
public final class StoredProcedures {

public enum Procedure {
UPDATE_HISTORICAL_RISK_SCORES,
UPDATE_COMPONENT_METRICS,
UPDATE_PROJECT_METRICS,
UPDATE_PORTFOLIO_METRICS;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.dependencytrack.auth.Permissions;
import org.dependencytrack.event.ComponentMetricsUpdateEvent;
import org.dependencytrack.event.PortfolioMetricsUpdateEvent;
import org.dependencytrack.event.HistoricalRiskScoreUpdateEvent;
import org.dependencytrack.event.ProjectMetricsUpdateEvent;
import org.dependencytrack.model.Component;
import org.dependencytrack.model.DependencyMetrics;
Expand Down Expand Up @@ -81,6 +82,23 @@
}
}

@GET
@Path("/riskscore/refresh")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Requests a refresh of the historical risk score metrics",
response = PortfolioMetrics.class,
notes = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.PORTFOLIO_MANAGEMENT)
public Response RefreshHistoricalRiskScoreMetrics() {

Check notice on line 97 in src/main/java/org/dependencytrack/resources/v1/MetricsResource.java

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/main/java/org/dependencytrack/resources/v1/MetricsResource.java#L97

The instance method name 'RefreshHistoricalRiskScoreMetrics' doesn't match '[a-z][a-zA-Z0-9]*'
Event.dispatch(new HistoricalRiskScoreUpdateEvent());
return Response.ok().build();
}

@GET
@Path("/portfolio/current")
@Produces(MediaType.APPLICATION_JSON)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/*
* This file is part of Dependency-Track.
*
* 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
* Copyright (c) OWASP Foundation. All Rights Reserved.
*/
package org.dependencytrack.tasks.metrics;

import alpine.common.logging.Logger;
import alpine.event.framework.Event;
import alpine.event.framework.Subscriber;
import net.javacrumbs.shedlock.core.LockingTaskExecutor;
import org.dependencytrack.event.HistoricalRiskScoreUpdateEvent;
import org.dependencytrack.metrics.Metrics;
import org.dependencytrack.util.LockProvider;

import java.time.Duration;
import java.util.UUID;

import static org.dependencytrack.tasks.LockName.PORTFOLIO_METRICS_TASK_LOCK;


/**
* A {@link Subscriber} task that updates portfolio metrics.
*
* @since 4.6.0
*/
public class HistoricalRiskScoreUpdateTask implements Subscriber {

private static final Logger LOGGER = Logger.getLogger(PortfolioMetricsUpdateTask.class);

@Override
public void inform(final Event e) {
if (e instanceof final HistoricalRiskScoreUpdateEvent event) {
try {
LockProvider.executeWithLock(PORTFOLIO_METRICS_TASK_LOCK, (LockingTaskExecutor.Task)() -> updateMetrics(event.isWeightHistoryEnabled()));
} catch (Throwable ex) {
LOGGER.error("Error in acquiring lock and executing portfolio metrics task", ex);
}
}
}

private void updateMetrics(final boolean weightHistoryEnabled) throws Exception {
LOGGER.info("Executing historical risk score metrics update");
final long startTimeNs = System.nanoTime();

try {
if (weightHistoryEnabled) {
LOGGER.info("Refreshing historical risk score metrics");
Metrics.updateHistoricalRiskScores();
}

Metrics.updatePortfolioMetrics();
} finally {
LOGGER.info("Completed historical risk score metrics update in " + Duration.ofNanos(System.nanoTime() - startTimeNs));
}
}

public record ProjectProjection(long id, UUID uuid) {
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
CREATE OR REPLACE PROCEDURE "UPDATE_HISTORICAL_RISK_SCORES"()
LANGUAGE "plpgsql"
AS
$$
DECLARE
"v_critical" INT; -- Number of vulnerabilities with critical severity
"v_high" INT; -- Number of vulnerabilities with high severity
"v_medium" INT; -- Number of vulnerabilities with medium severity
"v_low" INT; -- Number of vulnerabilities with low severity
"v_unassigned" INT; -- Number of vulnerabilities with unassigned severity
"v_risk_score" NUMERIC; -- Inherited risk score
BEGIN
UPDATE "DEPENDENCYMETRICS" SET "v_risk_score" = "CALC_RISK_SCORE"("v_critical", "v_high", "v_medium", "v_low", "v_unassigned");
END;
$$;