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

Feature : Support tagged vulnerabilities tags tab #991

Merged
merged 4 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
Expand Up @@ -1505,6 +1505,14 @@ public void untagNotificationRules(final String tagName, final Collection<String
getTagQueryManager().untagNotificationRules(tagName, notificationRuleUuids);
}

public List<TagQueryManager.TaggedVulnerabilityRow> getTaggedVulnerabilities(final String tagName) {
return getTagQueryManager().getTaggedVulnerabilities(tagName);
}

public void untagVulnerabilities(final String tagName, final Collection<String> vulnerabilityUuids) {
getTagQueryManager().untagVulnerabilities(tagName, vulnerabilityUuids);
}

/**
* Fetch multiple objects from the data store by their ID.
*
Expand Down
87 changes: 85 additions & 2 deletions src/main/java/org/dependencytrack/persistence/TagQueryManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.dependencytrack.model.Policy;
import org.dependencytrack.model.Project;
import org.dependencytrack.model.Tag;
import org.dependencytrack.model.Vulnerability;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
Expand Down Expand Up @@ -79,6 +80,7 @@ public record TagListRow(
long projectCount,
long policyCount,
long notificationRuleCount,
long vulnerabilityCount,
long totalCount
) {
}
Expand Down Expand Up @@ -107,6 +109,9 @@ public List<TagListRow> getTags() {
, (SELECT COUNT(*)
FROM "NOTIFICATIONRULE_TAGS"
WHERE "NOTIFICATIONRULE_TAGS"."TAG_ID" = "TAG"."ID") AS "notificationRuleCount"
, (SELECT COUNT(*)
FROM "VULNERABILITIES_TAGS"
WHERE "VULNERABILITIES_TAGS"."TAG_ID" = "TAG"."ID") AS "vulnerabilityCount"
, COUNT(*) OVER() AS "totalCount"
FROM "TAG"
""".formatted(projectAclCondition);
Expand All @@ -123,7 +128,8 @@ public List<TagListRow> getTags() {
} else if ("name".equals(orderBy)
|| "projectCount".equals(orderBy)
|| "policyCount".equals(orderBy)
|| "notificationRuleCount".equals(orderBy)) {
|| "notificationRuleCount".equals(orderBy)
|| "vulnerabilityCount".equals(orderBy)) {
sqlQuery += " ORDER BY \"%s\" %s, \"ID\" ASC".formatted(orderBy,
orderDirection == OrderDirection.DESCENDING ? "DESC" : "ASC");
} else {
Expand Down Expand Up @@ -151,7 +157,8 @@ public record TagDeletionCandidateRow(
long projectCount,
long accessibleProjectCount,
long policyCount,
long notificationRuleCount
long notificationRuleCount,
long vulnerabilityCount
) {
}

Expand Down Expand Up @@ -198,6 +205,11 @@ public void deleteTags(final Collection<String> tagNames) {
INNER JOIN "NOTIFICATIONRULE"
ON "NOTIFICATIONRULE"."ID" = "NOTIFICATIONRULE_TAGS"."NOTIFICATIONRULE_ID"
WHERE "NOTIFICATIONRULE_TAGS"."TAG_ID" = "TAG"."ID") AS "notificationRuleCount"
, (SELECT COUNT(*)
FROM "VULNERABILITIES_TAGS"
INNER JOIN "VULNERABILITY"
ON "VULNERABILITY"."ID" = "VULNERABILITIES_TAGS"."VULNERABILITY_ID"
WHERE "VULNERABILITIES_TAGS"."TAG_ID" = "TAG"."ID") AS "vulnerabilityCount"
FROM "TAG"
WHERE %s
""".formatted(projectAclCondition, String.join(" OR ", tagNameFilters)));
Expand Down Expand Up @@ -276,6 +288,13 @@ public void deleteTags(final Collection<String> tagNames) {
is missing the %s or %s permission.""".formatted(row.notificationRuleCount(),
Permissions.SYSTEM_CONFIGURATION, Permissions.SYSTEM_CONFIGURATION_UPDATE));
}

if (row.vulnerabilityCount() > 0 && !hasPortfolioManagementUpdatePermission) {
errorByTagName.put(row.name(), """
The tag is assigned to %d vulnerabilities, but the authenticated principal \
is missing the %s or %s permission.""".formatted(row.vulnerabilityCount(),
Permissions.PORTFOLIO_MANAGEMENT, Permissions.PORTFOLIO_MANAGEMENT_UPDATE));
}
sahibamittal marked this conversation as resolved.
Show resolved Hide resolved
}

if (!errorByTagName.isEmpty()) {
Expand Down Expand Up @@ -700,4 +719,68 @@ public void untagNotificationRules(final String tagName, final Collection<String
}
});
}

public record TaggedVulnerabilityRow(UUID uuid, String vulnId, String source, long totalCount) {
}

@Override
public List<TaggedVulnerabilityRow> getTaggedVulnerabilities(final String tagName) {
// language=SQL
var sqlQuery = """
SELECT "VULNERABILITY"."UUID" AS "uuid"
, "VULNERABILITY"."VULNID" AS "vulnId"
, "VULNERABILITY"."SOURCE" AS "source"
, COUNT(*) OVER() AS "totalCount"
FROM "VULNERABILITY"
INNER JOIN "VULNERABILITIES_TAGS"
ON "VULNERABILITIES_TAGS"."VULNERABILITY_ID" = "VULNERABILITY"."ID"
INNER JOIN "TAG"
ON "TAG"."ID" = "VULNERABILITIES_TAGS"."TAG_ID"
WHERE "TAG"."NAME" = :tag
""";

final var params = new HashMap<String, Object>();
params.put("tag", tagName);

if (filter != null) {
sqlQuery += " AND \"VULNERABILITY\".\"VULNID\" LIKE :vulnIdFilter";
params.put("vulnIdFilter", "%" + filter + "%");
}

if (orderBy == null) {
sqlQuery += " ORDER BY \"vulnId\" ASC";
} else if ("vulnId".equals(orderBy)) {
sqlQuery += " ORDER BY \"%s\" %s".formatted(orderBy,
orderDirection == OrderDirection.DESCENDING ? "DESC" : "ASC");
} else {
throw new NotSortableException("TaggedVulnerability", orderBy, "Field does not exist or is not sortable");
}

sqlQuery += " " + getOffsetLimitSqlClause();

final Query<?> query = pm.newQuery(Query.SQL, sqlQuery);
query.setNamedParameters(params);
return executeAndCloseResultList(query, TaggedVulnerabilityRow.class);
}

@Override
public void untagVulnerabilities(final String tagName, final Collection<String> vulnerabilityUuids) {
runInTransaction(() -> {
final Tag tag = getTagByName(tagName);
if (tag == null) {
throw new NoSuchElementException("A tag with name %s does not exist".formatted(tagName));
}
final Query<Vulnerability> vulnerabilityQuery = pm.newQuery(Vulnerability.class);
vulnerabilityQuery.setFilter(":uuids.contains(uuid)");
vulnerabilityQuery.setParameters(vulnerabilityUuids);
final List<Vulnerability> vulnerabilities = executeAndCloseList(vulnerabilityQuery);

for (final Vulnerability vulnerability : vulnerabilities) {
if (vulnerability.getTags() == null || vulnerability.getTags().isEmpty()) {
continue;
}
vulnerability.getTags().remove(tag);
}
});
}
}
77 changes: 76 additions & 1 deletion src/main/java/org/dependencytrack/resources/v1/TagResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import org.dependencytrack.resources.v1.vo.TaggedNotificationRuleListResponseItem;
import org.dependencytrack.resources.v1.vo.TaggedPolicyListResponseItem;
import org.dependencytrack.resources.v1.vo.TaggedProjectListResponseItem;
import org.dependencytrack.resources.v1.vo.TaggedVulnerabilityListResponseItem;

import java.util.List;
import java.util.Set;
Expand Down Expand Up @@ -93,7 +94,8 @@ public Response getAllTags() {
row.name(),
row.projectCount(),
row.policyCount(),
row.notificationRuleCount()
row.notificationRuleCount(),
row.vulnerabilityCount()
))
.toList();
final long totalCount = tagListRows.isEmpty() ? 0 : tagListRows.getFirst().totalCount();
Expand Down Expand Up @@ -501,4 +503,77 @@ public Response untagNotificationRules(

return Response.noContent().build();
}

@GET
@Path("/{name}/vulnerability")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns a list of all vulnerabilities assigned to the given tag.",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "A list of all vulnerabilities assigned to the given tag",
headers = @Header(name = TOTAL_COUNT_HEADER, description = "The total number of vulnerabilities", schema = @Schema(format = "integer")),
content = @Content(array = @ArraySchema(schema = @Schema(implementation = TaggedVulnerabilityListResponseItem.class)))
)
})
@PaginatedApi
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getTaggedVulnerabilities(
@Parameter(description = "Name of the tag to get vulnerabilities for.", required = true)
@PathParam("name") final String tagName
) {
// TODO: Should enforce lowercase for tagName once we are sure that
// users don't have any mixed-case tags in their system anymore.
// Will likely need a migration to cleanup existing tags for this.

final List<TagQueryManager.TaggedVulnerabilityRow> taggedVulnerabilityListRows;
try (final var qm = new QueryManager(getAlpineRequest())) {
taggedVulnerabilityListRows = qm.getTaggedVulnerabilities(tagName);
}

final List<TaggedVulnerabilityListResponseItem> tags = taggedVulnerabilityListRows.stream()
.map(row -> new TaggedVulnerabilityListResponseItem(row.uuid(), row.vulnId(), row.source()))
.toList();
final long totalCount = taggedVulnerabilityListRows.isEmpty() ? 0 : taggedVulnerabilityListRows.getFirst().totalCount();
return Response.ok(tags).header(TOTAL_COUNT_HEADER, totalCount).build();
}

@DELETE
@Path("/{name}/vulnerability")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Untags one or more vulnerabilities.",
description = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong> or <strong>PORTFOLIO_MANAGEMENT_UPDATE</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "204",
description = "Vulnerabilities untagged successfully."
),
@ApiResponse(
responseCode = "404",
description = "A tag with the provided name does not exist.",
content = @Content(schema = @Schema(implementation = ProblemDetails.class), mediaType = ProblemDetails.MEDIA_TYPE_JSON)
)
})
@PermissionRequired({Permissions.Constants.VIEW_PORTFOLIO, Permissions.Constants.PORTFOLIO_MANAGEMENT_UPDATE})
public Response untagVulnerabilities(
@Parameter(description = "Name of the tag", required = true)
@PathParam("name") final String tagName,
@Parameter(
description = "UUIDs of vulnerabilities to untag",
required = true,
array = @ArraySchema(schema = @Schema(type = "string", format = "uuid"))
)
@Size(min = 1, max = 100) final Set<@ValidUuid String> vulnerabilityUuids
) {
try (final var qm = new QueryManager(getAlpineRequest())) {
qm.untagVulnerabilities(tagName, vulnerabilityUuids);
}
return Response.noContent().build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public record TagListResponseItem(
@Parameter(description = "Name of the tag", required = true) String name,
@Parameter(description = "Number of projects assigned to this tag") long projectCount,
@Parameter(description = "Number of policies assigned to this tag") long policyCount,
@Parameter(description = "Number of notification rules assigned to this tag") long notificationRuleCount
@Parameter(description = "Number of notification rules assigned to this tag") long notificationRuleCount,
@Parameter(description = "Number of vulnerabilities assigned to this tag") long vulnerabilityCount
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* 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.resources.v1.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.v3.oas.annotations.Parameter;

import java.util.UUID;

/**
* @since 4.12.0
sahibamittal marked this conversation as resolved.
Show resolved Hide resolved
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public record TaggedVulnerabilityListResponseItem(
@Parameter(description = "UUID of the vulnerability", required = true) UUID uuid,
@Parameter(description = "Vulnerability ID", required = true) String vulnId,
@Parameter(description = "Source of the vulnerability", required = true) String source
) {
}
Loading
Loading