diff --git a/src/main/java/org/dependencytrack/event/NewVulnerableDependencyAnalysisEvent.java b/src/main/java/org/dependencytrack/event/NewVulnerableDependencyAnalysisEvent.java deleted file mode 100644 index 3b52682a4..000000000 --- a/src/main/java/org/dependencytrack/event/NewVulnerableDependencyAnalysisEvent.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 org.dependencytrack.model.Component; - -import java.util.List; -import java.util.Objects; - -/** - * Defines an {@link Event} triggered when one or more new components have been added to a project. - *

- * The main purpose of this event is the delayed evaluation of notification criteria - * for the {@link org.dependencytrack.notification.NotificationGroup#NEW_VULNERABLE_DEPENDENCY} group.@ - * - * @since 4.6.0 - */ -public record NewVulnerableDependencyAnalysisEvent(List components) implements Event { - - /** - * @param components A {@link List} of {@link Component}s that are considered to be new - */ - public NewVulnerableDependencyAnalysisEvent(final List components) { - this.components = Objects.requireNonNull(components); - } - -} diff --git a/src/main/java/org/dependencytrack/notification/vo/ComponentVulnAnalysisComplete.java b/src/main/java/org/dependencytrack/notification/vo/ComponentVulnAnalysisComplete.java deleted file mode 100644 index 141b15395..000000000 --- a/src/main/java/org/dependencytrack/notification/vo/ComponentVulnAnalysisComplete.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * 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.notification.vo; - -import org.dependencytrack.model.Component; -import org.dependencytrack.model.Vulnerability; - -import java.util.List; - -public class ComponentVulnAnalysisComplete { - private final List vulnerabilityList; - private final Component component; - - public ComponentVulnAnalysisComplete(List vulnerabilityList, Component component) { - this.vulnerabilityList = vulnerabilityList; - this.component = component; - } - - public List getVulnerabilityList() { - return vulnerabilityList; - } - - public Component getComponent() { - return this.component; - } -} diff --git a/src/main/java/org/dependencytrack/notification/vo/ProjectVulnAnalysisComplete.java b/src/main/java/org/dependencytrack/notification/vo/ProjectVulnAnalysisComplete.java deleted file mode 100644 index 45829b186..000000000 --- a/src/main/java/org/dependencytrack/notification/vo/ProjectVulnAnalysisComplete.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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.notification.vo; - -import org.dependencytrack.model.Project; -import org.dependencytrack.proto.notification.v1.ProjectVulnAnalysisStatus; - -import java.util.List; -import java.util.UUID; - -public class ProjectVulnAnalysisComplete { - - private UUID token; - private final Project project; - private final List findingsList; - private final ProjectVulnAnalysisStatus status; - - public ProjectVulnAnalysisComplete(final UUID token, Project project, List findingsList, ProjectVulnAnalysisStatus status) { - this.token = token; - this.project = project; - this.findingsList = findingsList; - this.status = status; - } - - public UUID getToken() { - return token; - } - - public List getComponentAnalysisCompleteList() { - return findingsList; - } - - public Project getProject() { - return this.project; - } - - public ProjectVulnAnalysisStatus getStatus() { - return status; - } -} diff --git a/src/main/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverter.java b/src/main/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverter.java index 04add5042..41c6a69c2 100644 --- a/src/main/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverter.java +++ b/src/main/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverter.java @@ -30,11 +30,9 @@ import org.dependencytrack.notification.vo.AnalysisDecisionChange; import org.dependencytrack.notification.vo.BomConsumedOrProcessed; import org.dependencytrack.notification.vo.BomProcessingFailed; -import org.dependencytrack.notification.vo.ComponentVulnAnalysisComplete; import org.dependencytrack.notification.vo.NewVulnerabilityIdentified; import org.dependencytrack.notification.vo.NewVulnerableDependency; import org.dependencytrack.notification.vo.PolicyViolationIdentified; -import org.dependencytrack.notification.vo.ProjectVulnAnalysisComplete; import org.dependencytrack.notification.vo.VexConsumedOrProcessed; import org.dependencytrack.notification.vo.ViolationAnalysisDecisionChange; import org.dependencytrack.parser.common.resolver.CweResolver; @@ -42,7 +40,6 @@ import org.dependencytrack.proto.notification.v1.BomConsumedOrProcessedSubject; import org.dependencytrack.proto.notification.v1.BomProcessingFailedSubject; import org.dependencytrack.proto.notification.v1.Component; -import org.dependencytrack.proto.notification.v1.ComponentVulnAnalysisCompleteSubject; import org.dependencytrack.proto.notification.v1.Group; import org.dependencytrack.proto.notification.v1.Level; import org.dependencytrack.proto.notification.v1.NewVulnerabilitySubject; @@ -55,7 +52,6 @@ import org.dependencytrack.proto.notification.v1.PolicyViolationAnalysisDecisionChangeSubject; import org.dependencytrack.proto.notification.v1.PolicyViolationSubject; import org.dependencytrack.proto.notification.v1.Project; -import org.dependencytrack.proto.notification.v1.ProjectVulnAnalysisCompleteSubject; import org.dependencytrack.proto.notification.v1.Scope; import org.dependencytrack.proto.notification.v1.VexConsumedOrProcessedSubject; import org.dependencytrack.proto.notification.v1.Vulnerability; @@ -66,7 +62,6 @@ import java.math.BigDecimal; import java.time.ZoneOffset; import java.util.Collections; -import java.util.List; import java.util.Objects; import java.util.Optional; @@ -185,8 +180,6 @@ private static Optional convert(final Object subject) { return Optional.of(Any.pack(convert(vcop))); } else if (subject instanceof final PolicyViolationIdentified pvi) { return Optional.of(Any.pack(convert(pvi))); - } else if (subject instanceof final ProjectVulnAnalysisComplete pac) { - return Optional.of(Any.pack(convert(pac))); } else if (subject instanceof final org.dependencytrack.model.Project p) { return Optional.of(Any.pack(convert(p))); } @@ -324,26 +317,6 @@ private static Project convert(final org.dependencytrack.model.Project project) return builder.build(); } - private static ComponentVulnAnalysisCompleteSubject convert(ComponentVulnAnalysisComplete componentVulnAnalysisComplete) { - - Component component = convert(componentVulnAnalysisComplete.getComponent()); - ComponentVulnAnalysisCompleteSubject.Builder builder = ComponentVulnAnalysisCompleteSubject.newBuilder(); - builder.setComponent(component); - List vulnerabilities = componentVulnAnalysisComplete.getVulnerabilityList().stream().map(NotificationModelConverter::convert).toList(); - builder.addAllVulnerabilities(vulnerabilities); - return builder.build(); - } - - private static ProjectVulnAnalysisCompleteSubject convert(ProjectVulnAnalysisComplete notification) { - ProjectVulnAnalysisCompleteSubject.Builder builder = ProjectVulnAnalysisCompleteSubject.newBuilder(); - builder.setToken(notification.getToken().toString()); - builder.setProject(convert(notification.getProject())); - List componentAnalysisCompleteSubjects = notification.getComponentAnalysisCompleteList().stream().map(NotificationModelConverter::convert).toList(); - builder.addAllFindings(componentAnalysisCompleteSubjects); - builder.setStatus(notification.getStatus()); - return builder.build(); - } - private static Vulnerability convert(final org.dependencytrack.model.Vulnerability vulnerability) { final Vulnerability.Builder builder = Vulnerability.newBuilder() .setUuid(vulnerability.getUuid().toString()) diff --git a/src/main/java/org/dependencytrack/parser/github/graphql/GitHubSecurityAdvisoryParser.java b/src/main/java/org/dependencytrack/parser/github/graphql/GitHubSecurityAdvisoryParser.java deleted file mode 100644 index b7462a820..000000000 --- a/src/main/java/org/dependencytrack/parser/github/graphql/GitHubSecurityAdvisoryParser.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * 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.parser.github.graphql; - - -import org.apache.commons.lang3.tuple.Pair; -import org.dependencytrack.parser.github.graphql.model.GitHubSecurityAdvisory; -import org.dependencytrack.parser.github.graphql.model.GitHubVulnerability; -import org.dependencytrack.parser.github.graphql.model.PageableList; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.List; - -import static org.dependencytrack.util.JsonUtil.jsonStringToTimestamp; - -public class GitHubSecurityAdvisoryParser { - - public PageableList parse(final JSONObject object) { - final PageableList pageableList = new PageableList(); - final List advisories = new ArrayList<>(); - final JSONObject data = object.optJSONObject("data"); - if (data != null) { - final JSONObject securityAdvisories = data.getJSONObject("securityAdvisories"); - if (securityAdvisories != null) { - final JSONArray securityAdvisoriesNodes = securityAdvisories.getJSONArray("nodes"); - if (securityAdvisoriesNodes != null) { - for (int i = 0; i < securityAdvisoriesNodes.length(); i++) { - final JSONObject securityAdvisory = securityAdvisoriesNodes.getJSONObject(i); - final GitHubSecurityAdvisory advisory = parseSecurityAdvisory(securityAdvisory); - advisories.add(advisory); - } - } - pageableList.setTotalCount(securityAdvisories.optInt("totalCount")); - final JSONObject pageInfo = securityAdvisories.getJSONObject("pageInfo"); - if (pageInfo != null) { - pageableList.setHasNextPage(pageInfo.optBoolean("hasNextPage")); - pageableList.setHasPreviousPage(pageInfo.optBoolean("hasPreviousPage")); - pageableList.setStartCursor(pageInfo.optString("startCursor")); - pageableList.setEndCursor(pageInfo.optString("endCursor")); - } - } - } - pageableList.setAdvisories(advisories); - return pageableList; - } - - private GitHubSecurityAdvisory parseSecurityAdvisory(final JSONObject object) { - final GitHubSecurityAdvisory advisory = new GitHubSecurityAdvisory(); - advisory.setDatabaseId(object.getInt("databaseId")); - advisory.setDescription(object.optString("description", null)); - advisory.setGhsaId(object.optString("ghsaId", null)); - advisory.setId(object.optString("id", null)); - advisory.setNotificationsPermalink(object.optString("notificationsPermalink", null)); - advisory.setOrigin(object.optString("origin", null)); - advisory.setPermalink(object.optString("permalink", null)); - advisory.setSeverity(object.optString("severity", null)); - advisory.setSummary(object.optString("summary", null)); - advisory.setPublishedAt(jsonStringToTimestamp(object.optString("publishedAt", null))); - advisory.setUpdatedAt(jsonStringToTimestamp(object.optString("updatedAt", null))); - advisory.setWithdrawnAt(jsonStringToTimestamp(object.optString("withdrawnAt", null))); - - final JSONArray identifiers = object.optJSONArray("identifiers"); - if (identifiers != null) { - for (int i=0; i pair = Pair.of(type, value); - advisory.addIdentifier(pair); - } - } - } - - final JSONArray references = object.optJSONArray("references"); - if (references != null) { - for (int i=0; i vulnerabilities = parseVulnerabilities(object); - advisory.setVulnerabilities(vulnerabilities); - return advisory; - } - - private List parseVulnerabilities(final JSONObject object) { - final List vulnerabilities = new ArrayList<>(); - final JSONObject vs = object.optJSONObject("vulnerabilities"); - if (vs != null) { - final JSONArray edges = vs.optJSONArray("edges"); - if (edges != null) { - for (int i=0; i> identifiers; - private String notificationsPermalink; - private String origin; - private String permalink; - private List references; - private String severity; - private String summary; - private ZonedDateTime publishedAt; - private ZonedDateTime updatedAt; - private ZonedDateTime withdrawnAt; - private List vulnerabilities; - private double cvssScore; - private String cvssVector; - private List cwes; - - public int getDatabaseId() { - return databaseId; - } - - public void setDatabaseId(int databaseId) { - this.databaseId = databaseId; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getGhsaId() { - return ghsaId; - } - - public void setGhsaId(String ghsaId) { - this.ghsaId = ghsaId; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public List> getIdentifiers() { - return identifiers; - } - - public void addIdentifier(Pair identifier) { - if (this.identifiers == null) { - this.identifiers = new ArrayList<>(); - } - this.identifiers.add(identifier); - } - - public void setIdentifiers(List> identifiers) { - this.identifiers = identifiers; - } - - public String getNotificationsPermalink() { - return notificationsPermalink; - } - - public void setNotificationsPermalink(String notificationsPermalink) { - this.notificationsPermalink = notificationsPermalink; - } - - public String getOrigin() { - return origin; - } - - public void setOrigin(String origin) { - this.origin = origin; - } - - public String getPermalink() { - return permalink; - } - - public void setPermalink(String permalink) { - this.permalink = permalink; - } - - public List getReferences() { - return references; - } - - public void addReference(String reference) { - if (this.references == null) { - this.references = new ArrayList<>(); - } - this.references.add(reference); - } - - public void setReferences(List references) { - this.references = references; - } - - public String getSeverity() { - return severity; - } - - public void setSeverity(String severity) { - this.severity = severity; - } - - public String getSummary() { - return summary; - } - - public void setSummary(String summary) { - this.summary = summary; - } - - public ZonedDateTime getPublishedAt() { - return publishedAt; - } - - public void setPublishedAt(ZonedDateTime publishedAt) { - this.publishedAt = publishedAt; - } - - public ZonedDateTime getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(ZonedDateTime updatedAt) { - this.updatedAt = updatedAt; - } - - public ZonedDateTime getWithdrawnAt() { - return withdrawnAt; - } - - public void setWithdrawnAt(ZonedDateTime withdrawnAt) { - this.withdrawnAt = withdrawnAt; - } - - public List getVulnerabilities() { - return vulnerabilities; - } - - public void setVulnerabilities(List vulnerabilities) { - this.vulnerabilities = vulnerabilities; - } - - public double getCvssScore() { - return cvssScore; - } - - public void setCvssScore(double cvssScore) { - this.cvssScore = cvssScore; - } - - public String getCvssVector() { - return cvssVector; - } - - public void setCvssVector(String cvssVector) { - this.cvssVector = cvssVector; - } - - public List getCwes() { - return cwes; - } - - public void addCwe(String cwe) { - if (cwes == null) { - cwes = new ArrayList<>(); - } - cwes.add(cwe); - } - - public void setCwes(List cwes) { - this.cwes = cwes; - } -} diff --git a/src/main/java/org/dependencytrack/parser/github/graphql/model/GitHubVulnerability.java b/src/main/java/org/dependencytrack/parser/github/graphql/model/GitHubVulnerability.java deleted file mode 100644 index 4786f49a4..000000000 --- a/src/main/java/org/dependencytrack/parser/github/graphql/model/GitHubVulnerability.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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.parser.github.graphql.model; - -import java.time.ZonedDateTime; - -public class GitHubVulnerability { - - private String severity; - private ZonedDateTime updatedAt; - private String firstPatchedVersionIdentifier; - private String vulnerableVersionRange; - private String packageEcosystem; - private String packageName; - - public String getSeverity() { - return severity; - } - - public void setSeverity(String severity) { - this.severity = severity; - } - - public ZonedDateTime getUpdatedAt() { - return updatedAt; - } - - public void setUpdatedAt(ZonedDateTime updatedAt) { - this.updatedAt = updatedAt; - } - - public String getFirstPatchedVersionIdentifier() { - return firstPatchedVersionIdentifier; - } - - public void setFirstPatchedVersionIdentifier(String firstPatchedVersionIdentifier) { - this.firstPatchedVersionIdentifier = firstPatchedVersionIdentifier; - } - - public String getVulnerableVersionRange() { - return vulnerableVersionRange; - } - - public void setVulnerableVersionRange(String vulnerableVersionRange) { - this.vulnerableVersionRange = vulnerableVersionRange; - } - - public String getPackageEcosystem() { - return packageEcosystem; - } - - public void setPackageEcosystem(String packageEcosystem) { - this.packageEcosystem = packageEcosystem; - } - - public String getPackageName() { - return packageName; - } - - public void setPackageName(String packageName) { - this.packageName = packageName; - } -} diff --git a/src/main/java/org/dependencytrack/parser/github/graphql/model/PageableList.java b/src/main/java/org/dependencytrack/parser/github/graphql/model/PageableList.java deleted file mode 100644 index baf24bc4a..000000000 --- a/src/main/java/org/dependencytrack/parser/github/graphql/model/PageableList.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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.parser.github.graphql.model; - -import java.util.List; - -public class PageableList { - - private List advisories; - private long totalCount; - private boolean hasNextPage; - private boolean hasPreviousPage; - private String startCursor; - private String endCursor; - - public List getAdvisories() { - return advisories; - } - - public void setAdvisories(List advisories) { - this.advisories = advisories; - } - - public long getTotalCount() { - return totalCount; - } - - public void setTotalCount(long totalCount) { - this.totalCount = totalCount; - } - - public boolean isHasNextPage() { - return hasNextPage; - } - - public void setHasNextPage(boolean hasNextPage) { - this.hasNextPage = hasNextPage; - } - - public boolean isHasPreviousPage() { - return hasPreviousPage; - } - - public void setHasPreviousPage(boolean hasPreviousPage) { - this.hasPreviousPage = hasPreviousPage; - } - - public String getStartCursor() { - return startCursor; - } - - public void setStartCursor(String startCursor) { - this.startCursor = startCursor; - } - - public String getEndCursor() { - return endCursor; - } - - public void setEndCursor(String endCursor) { - this.endCursor = endCursor; - } -} diff --git a/src/main/java/org/dependencytrack/upgrade/UpgradeInitializer.java b/src/main/java/org/dependencytrack/upgrade/UpgradeInitializer.java deleted file mode 100644 index c28190ffc..000000000 --- a/src/main/java/org/dependencytrack/upgrade/UpgradeInitializer.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * 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.upgrade; - -import alpine.Config; -import alpine.common.logging.Logger; -import alpine.common.util.VersionComparator; -import alpine.model.InstalledUpgrades; -import alpine.model.SchemaVersion; -import alpine.server.persistence.PersistenceManagerFactory; -import alpine.server.upgrade.UpgradeException; -import alpine.server.upgrade.UpgradeExecutor; -import alpine.server.upgrade.UpgradeMetaProcessor; -import org.datanucleus.PersistenceNucleusContext; -import org.datanucleus.PropertyNames; -import org.datanucleus.api.jdo.JDOPersistenceManagerFactory; -import org.datanucleus.store.schema.SchemaAwareStoreManager; -import org.dependencytrack.persistence.QueryManager; - -import javax.jdo.JDOHelper; -import javax.jdo.PersistenceManager; -import javax.servlet.ServletContextEvent; -import javax.servlet.ServletContextListener; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -public class UpgradeInitializer implements ServletContextListener { - - private static final Logger LOGGER = Logger.getLogger(UpgradeInitializer.class); - - /** - * {@inheritDoc} - */ - @Override - public void contextInitialized(final ServletContextEvent event) { - LOGGER.info("Initializing upgrade framework"); - try { - final UpgradeMetaProcessor ump = new UpgradeMetaProcessor(); - final VersionComparator currentVersion = ump.getSchemaVersion(); - ump.close(); - if (currentVersion != null && currentVersion.isOlderThan(new VersionComparator("4.0.0"))) { - LOGGER.error("Unable to upgrade Dependency-Track versions prior to v4.0.0. Please refer to documentation for migration details. Halting."); - Runtime.getRuntime().halt(-1); - } - } catch (UpgradeException e) { - LOGGER.error("An error occurred determining database schema version. Unable to continue.", e); - Runtime.getRuntime().halt(-1); - } - - try (final JDOPersistenceManagerFactory pmf = createPersistenceManagerFactory()) { - // Ensure that the UpgradeMetaProcessor and SchemaVersion tables are created NOW, not dynamically at runtime. - final PersistenceNucleusContext ctx = pmf.getNucleusContext(); - final Set classNames = new HashSet<>(); - classNames.add(InstalledUpgrades.class.getCanonicalName()); - classNames.add(SchemaVersion.class.getCanonicalName()); - ((SchemaAwareStoreManager) ctx.getStoreManager()).createSchemaForClasses(classNames, new Properties()); - - try (final PersistenceManager pm = pmf.getPersistenceManager(); - final QueryManager qm = new QueryManager(pm)) { - final UpgradeExecutor executor = new UpgradeExecutor(qm); - try { - executor.executeUpgrades(UpgradeItems.getUpgradeItems()); - } catch (UpgradeException e) { - LOGGER.error("An error occurred performing upgrade processing. " + e.getMessage()); - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public void contextDestroyed(final ServletContextEvent event) { - /* Intentionally blank to satisfy interface */ - } - - /** - * Create a new, dedicated {@link javax.jdo.PersistenceManagerFactory} to be used for schema - * generation and execution of schema upgrades. - *

- * Necessary because {@link UpgradeInitializer} is executed before {@link PersistenceManagerFactory} - * on application startup. The PMF created by this method does not use connection pooling, as all - * operations are performed in serial order. - * - * @return A {@link JDOPersistenceManagerFactory} - */ - private JDOPersistenceManagerFactory createPersistenceManagerFactory() { - final var dnProps = new Properties(); - dnProps.put(PropertyNames.PROPERTY_CONNECTION_URL, Config.getInstance().getProperty(Config.AlpineKey.DATABASE_URL)); - dnProps.put(PropertyNames.PROPERTY_CONNECTION_DRIVER_NAME, Config.getInstance().getProperty(Config.AlpineKey.DATABASE_DRIVER)); - dnProps.put(PropertyNames.PROPERTY_CONNECTION_USER_NAME, Config.getInstance().getProperty(Config.AlpineKey.DATABASE_USERNAME)); - dnProps.put(PropertyNames.PROPERTY_CONNECTION_PASSWORD, Config.getInstance().getPropertyOrFile(Config.AlpineKey.DATABASE_PASSWORD)); - dnProps.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_DATABASE, "true"); - dnProps.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_TABLES, "true"); - dnProps.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_COLUMNS, "true"); - dnProps.put(PropertyNames.PROPERTY_SCHEMA_AUTOCREATE_CONSTRAINTS, "true"); - dnProps.put(PropertyNames.PROPERTY_SCHEMA_GENERATE_DATABASE_MODE, "create"); - dnProps.put(PropertyNames.PROPERTY_QUERY_JDOQL_ALLOWALL, "true"); - dnProps.put(PropertyNames.PROPERTY_PERSISTENCE_UNIT_NAME, "Alpine"); - return (JDOPersistenceManagerFactory) JDOHelper.getPersistenceManagerFactory(dnProps); - } - -} diff --git a/src/main/java/org/dependencytrack/upgrade/UpgradeItems.java b/src/main/java/org/dependencytrack/upgrade/UpgradeItems.java deleted file mode 100644 index cfdb798fb..000000000 --- a/src/main/java/org/dependencytrack/upgrade/UpgradeItems.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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.upgrade; - -import alpine.server.upgrade.UpgradeItem; -import org.dependencytrack.upgrade.v510.v510Updater; -import org.dependencytrack.upgrade.v520.v520Updater; - -import java.util.ArrayList; -import java.util.List; - -class UpgradeItems { - - private static final List> UPGRADE_ITEMS = new ArrayList<>(); - - static { - UPGRADE_ITEMS.add(v510Updater.class); - UPGRADE_ITEMS.add(v520Updater.class); - } - - static List> getUpgradeItems() { - return UPGRADE_ITEMS; - } - -} diff --git a/src/main/java/org/dependencytrack/upgrade/v510/v510Updater.java b/src/main/java/org/dependencytrack/upgrade/v510/v510Updater.java deleted file mode 100644 index 3cd554866..000000000 --- a/src/main/java/org/dependencytrack/upgrade/v510/v510Updater.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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.upgrade.v510; - -import alpine.common.logging.Logger; -import alpine.persistence.AlpineQueryManager; -import alpine.server.upgrade.AbstractUpgradeItem; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -public class v510Updater extends AbstractUpgradeItem { - - private static final Logger LOGGER = Logger.getLogger(v510Updater.class); - - @Override - public String getSchemaVersion() { - return "5.1.0"; - } - - @Override - public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception { - changePolicyConditionValueTypeToText(connection); - } - - private static void changePolicyConditionValueTypeToText(final Connection connection) throws Exception { - LOGGER.info("Changing type of \"POLICYCONDITION\".\"VALUE\" from VARCHAR(255) to TEXT"); - try (final PreparedStatement ps = connection.prepareStatement(""" - ALTER TABLE "POLICYCONDITION" ALTER COLUMN "VALUE" TYPE TEXT; - """)) { - ps.execute(); - } - } - -} diff --git a/src/main/java/org/dependencytrack/upgrade/v520/v520Updater.java b/src/main/java/org/dependencytrack/upgrade/v520/v520Updater.java deleted file mode 100644 index 3d2b97f2d..000000000 --- a/src/main/java/org/dependencytrack/upgrade/v520/v520Updater.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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.upgrade.v520; - -import alpine.common.logging.Logger; -import alpine.persistence.AlpineQueryManager; -import alpine.server.upgrade.AbstractUpgradeItem; - -import java.sql.Connection; -import java.sql.PreparedStatement; - -public class v520Updater extends AbstractUpgradeItem { - - private static final Logger LOGGER = Logger.getLogger(v520Updater.class); - - @Override - public String getSchemaVersion() { - return "5.2.0"; - } - - @Override - public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception { - changePurlColumnLengthInIntegrityMetaComponentTable(connection); - dropStatusCheckConstraintOnIntegrityMetaComponentTable(connection); - } - - private static void changePurlColumnLengthInIntegrityMetaComponentTable(final Connection connection) throws Exception { - LOGGER.info("Changing length of \"PURL\" from VARCHAR(255) to VARCHAR(1024)"); - try (final PreparedStatement ps = connection.prepareStatement(""" - ALTER TABLE "INTEGRITY_META_COMPONENT" ALTER "PURL" TYPE VARCHAR(1024); - """)) { - ps.execute(); - } - } - - private static void dropStatusCheckConstraintOnIntegrityMetaComponentTable(final Connection connection) throws Exception { - LOGGER.info("Dropping constraint \"INTEGRITY_META_COMPONENT_STATUS_check\" if it exists on \"INTEGRITY_META_COMPONENT\" table"); - try (final PreparedStatement ps = connection.prepareStatement(""" - ALTER TABLE "INTEGRITY_META_COMPONENT" DROP CONSTRAINT IF EXISTS "INTEGRITY_META_COMPONENT_STATUS_check" RESTRICT; - """)) { - ps.execute(); - } - } -} diff --git a/src/main/java/org/dependencytrack/util/ComponentIdentificationUtil.java b/src/main/java/org/dependencytrack/util/ComponentIdentificationUtil.java deleted file mode 100644 index aec952e12..000000000 --- a/src/main/java/org/dependencytrack/util/ComponentIdentificationUtil.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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.util; - -import com.github.packageurl.MalformedPackageURLException; -import com.github.packageurl.PackageURL; -import org.apache.commons.lang3.StringUtils; -import org.dependencytrack.model.Component; - -/** - * A collection of utilities that compare the identity of a component. - * - * @since 4.0.0 - */ -public class ComponentIdentificationUtil { - - private ComponentIdentificationUtil() { - } - - @SuppressWarnings("deprecation") - public static boolean doesIdentityMatch(final Component a, final org.cyclonedx.model.Component b) { - if (a == null || b == null) { - return false; - } - if (isMatch(a.getPurl(), b.getPurl())) { - return true; - } - if (isMatch(a.getPurlCoordinates(), b.getPurl())) { - return true; - } - if (b.getSwid() != null && isMatch(a.getSwidTagId(), b.getSwid().getTagId())) { - return true; - } - if (isMatch(a.getCpe(), b.getCpe())) { - return true; - } - if (StringUtils.trimToEmpty(a.getGroup()).equals(StringUtils.trimToEmpty(b.getGroup())) - && StringUtils.trimToEmpty(a.getName()).equals(StringUtils.trimToEmpty(b.getName())) - && StringUtils.trimToEmpty(a.getVersion()).equals(StringUtils.trimToEmpty(b.getVersion()))) { - return true; - } - return false; - } - - public static boolean doesIdentityMatch(final Component a, final Component b) { - if (a == null || b == null) { - return false; - } - if (isMatch(a.getPurl(), b.getPurl())) { - return true; - } - if (isMatch(a.getPurlCoordinates(), b.getPurlCoordinates())) { - return true; - } - if (isMatch(a.getSwidTagId(), b.getSwidTagId())) { - return true; - } - if (isMatch(a.getCpe(), b.getCpe())) { - return true; - } - if (StringUtils.trimToEmpty(a.getGroup()).equals(StringUtils.trimToEmpty(b.getGroup())) - && StringUtils.trimToEmpty(a.getName()).equals(StringUtils.trimToEmpty(b.getName())) - && StringUtils.trimToEmpty(a.getVersion()).equals(StringUtils.trimToEmpty(b.getVersion()))) { - return true; - } - return false; - } - - private static boolean isMatch(final PackageURL a, final PackageURL b) { - if (a != null && b != null) { - return a.canonicalize().equals(b.canonicalize()); - } - return false; - } - - private static boolean isMatch(final PackageURL a, final String b) { - if (a != null && b != null) { - try { - return a.canonicalize().equals(new PackageURL(b).canonicalize()); - } catch (MalformedPackageURLException e) { - return false; - } - } - return false; - } - - private static boolean isMatch(final String a, final String b) { - if (StringUtils.trimToNull(a) != null && StringUtils.trimToNull(b) != null) { - return StringUtils.trimToNull(a).equals(StringUtils.trimToNull(b)); - } - return false; - } -} diff --git a/src/main/java/org/dependencytrack/util/ComponentVersion.java b/src/main/java/org/dependencytrack/util/ComponentVersion.java deleted file mode 100644 index 725e51200..000000000 --- a/src/main/java/org/dependencytrack/util/ComponentVersion.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * 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.util; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import javax.annotation.concurrent.NotThreadSafe; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - *

- * Simple object to track the parts of a version number. The parts are contained - * in a List such that version 1.2.3 will be stored as: versionParts[0] = 1; - * versionParts[1] = 2; - * versionParts[2] = 3; - *

- *

- * Note, the parser contained in this class expects the version numbers to be - * separated by periods. If a different separator is used the parser will likely - * fail.

- * - * @author Jeremy Long - * - * Ported from DependencyVersion in Dependency-Check v5.2.1 - */ -@NotThreadSafe -public class ComponentVersion implements Iterable, Comparable { - - /** - * A list of the version parts. - */ - private List versionParts; - - /** - * Constructor for a empty DependencyVersion. - */ - public ComponentVersion() { - } - - /** - * Constructor for a DependencyVersion that will parse a version string. - * Note, this should only be used when the version passed in is - * already known to be a well formatted version number. Otherwise, - * DependencyVersionUtil.parseVersion() should be used instead. - * - * @param version the well formatted version number to parse - */ - public ComponentVersion(String version) { - parseVersion(version); - } - - /** - * Parses a version string into its sub parts: major, minor, revision, - * build, etc. Note, this should only be used to parse something that - * is already known to be a version number. - * - * @param version the version string to parse - */ - public final void parseVersion(String version) { - versionParts = new ArrayList<>(); - if (version != null) { - // https://github.com/DependencyTrack/dependency-track/issues/1374 - // handle deb versions - String lcVersion = version.toLowerCase(); - final Pattern debrx = Pattern.compile("^([0-9]+:)?(.*)(-[^-]+ubuntu[^-]+)$"); - final Matcher debmatcher = debrx.matcher(lcVersion); - if (debmatcher.matches()) { - lcVersion = debmatcher.group(2); - } - - final Pattern rx = Pattern.compile("(\\d+[a-z]{1,3}$|[a-z]{1,3}[_-]?\\d+|\\d+|(rc|release|snapshot|beta|alpha)$)", - Pattern.CASE_INSENSITIVE); - final Matcher matcher = rx.matcher(lcVersion); - while (matcher.find()) { - versionParts.add(matcher.group()); - } - if (versionParts.isEmpty()) { - versionParts.add(version); - } - } - } - - /** - * Get the value of versionParts. - * - * @return the value of versionParts - */ - public List getVersionParts() { - return versionParts; - } - - /** - * Set the value of versionParts. - * - * @param versionParts new value of versionParts - */ - public void setVersionParts(List versionParts) { - this.versionParts = versionParts; - } - - /** - * Retrieves an iterator for the version parts. - * - * @return an iterator for the version parts - */ - @Override - public Iterator iterator() { - return versionParts.iterator(); - } - - /** - * Reconstructs the version string from the split version parts. - * - * @return a string representing the version. - */ - @Override - public String toString() { - return StringUtils.join(versionParts, '.'); - } - - /** - * Compares the equality of this object to the one passed in as a parameter. - * - * @param obj the object to compare equality - * @return returns true only if the two objects are equal, otherwise false - */ - @Override - public boolean equals(Object obj) { - if (obj == null || !(obj instanceof ComponentVersion)) { - return false; - } - if (this == obj) { - return true; - } - final ComponentVersion other = (ComponentVersion) obj; - final int minVersionMatchLength = (this.versionParts.size() < other.versionParts.size()) - ? this.versionParts.size() : other.versionParts.size(); - final int maxVersionMatchLength = (this.versionParts.size() > other.versionParts.size()) - ? this.versionParts.size() : other.versionParts.size(); - - if (minVersionMatchLength == 1 && maxVersionMatchLength >= 3) { - return false; - } - - //TODO steal better version of code from compareTo - for (int i = 0; i < minVersionMatchLength; i++) { - final String thisPart = this.versionParts.get(i); - final String otherPart = other.versionParts.get(i); - if (!thisPart.equals(otherPart)) { - return false; - } - } - if (this.versionParts.size() > minVersionMatchLength) { - for (int i = minVersionMatchLength; i < this.versionParts.size(); i++) { - if (!"0".equals(this.versionParts.get(i))) { - return false; - } - } - } - - if (other.versionParts.size() > minVersionMatchLength) { - for (int i = minVersionMatchLength; i < other.versionParts.size(); i++) { - if (!"0".equals(other.versionParts.get(i))) { - return false; - } - } - } - - /* - * if (this.versionParts != other.versionParts && (this.versionParts == null || !this.versionParts.equals(other.versionParts))) { - * return false; - * } - */ - return true; - } - - /** - * Calculates the hashCode for this object. - * - * @return the hashCode - */ - @Override - public int hashCode() { - return new HashCodeBuilder(5, 71) - .append(versionParts) - .toHashCode(); - } - - /** - * Determines if the three most major major version parts are identical. For - * instances, if version 1.2.3.4 was compared to 1.2.3 this function would - * return true. - * - * @param version the version number to compare - * @return true if the first three major parts of the version are identical - */ - public boolean matchesAtLeastThreeLevels(ComponentVersion version) { - if (version == null) { - return false; - } - if (Math.abs(this.versionParts.size() - version.versionParts.size()) >= 3) { - return false; - } - - final int max = (this.versionParts.size() < version.versionParts.size()) - ? this.versionParts.size() : version.versionParts.size(); - - boolean ret = true; - for (int i = 0; i < max; i++) { - final String thisVersion = this.versionParts.get(i); - final String otherVersion = version.getVersionParts().get(i); - if (i >= 3) { - if (thisVersion.compareToIgnoreCase(otherVersion) >= 0) { - ret = false; - break; - } - } else if (!thisVersion.equals(otherVersion)) { - ret = false; - break; - } - } - - return ret; - } - - @Override - public int compareTo(ComponentVersion version) { - if (version == null) { - return 1; - } - final List left = this.getVersionParts(); - final List right = version.getVersionParts(); - final int max = left.size() < right.size() ? left.size() : right.size(); - - for (int i = 0; i < max; i++) { - final String lStr = left.get(i); - final String rStr = right.get(i); - if (lStr.equals(rStr)) { - continue; - } - try { - final int l = Integer.parseInt(lStr); - final int r = Integer.parseInt(rStr); - if (l < r) { - return -1; - } else if (l > r) { - return 1; - } - } catch (NumberFormatException ex) { - final int comp = left.get(i).compareTo(right.get(i)); - if (comp < 0) { - return -1; - } else if (comp > 0) { - return 1; - } - } - } - // Modified from original by Steve Springett - // Account for comparisons where one version may be 1.0.0 and another may be 1.0.0.0. - if (left.size() == max && right.size() == left.size()+1 && right.get(right.size()-1).equals("0")) { - return 0; - } else if (right.size() == max && left.size() == right.size()+1 && left.get(left.size()-1).equals("0")) { - return 0; - } else { - return Integer.compare(left.size(), right.size()); - } - } -} diff --git a/src/main/java/org/dependencytrack/util/JsonUtil.java b/src/main/java/org/dependencytrack/util/JsonUtil.java deleted file mode 100644 index 2fbbd0649..000000000 --- a/src/main/java/org/dependencytrack/util/JsonUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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.util; - -import javax.json.JsonObjectBuilder; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.time.ZonedDateTime; -import java.time.format.DateTimeParseException; - -public final class JsonUtil { - - /** - * Private constructor. - */ - private JsonUtil() { } - - public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final String value) { - if (value != null) { - builder.add(key, value); - } - return builder; - } - - public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final BigInteger value) { - if (value != null) { - builder.add(key, value); - } - return builder; - } - - public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final BigDecimal value) { - if (value != null) { - builder.add(key, value); - } - return builder; - } - - public static JsonObjectBuilder add(final JsonObjectBuilder builder, final String key, final Enum value) { - if (value != null) { - builder.add(key, value.name()); - } - return builder; - } - - public static ZonedDateTime jsonStringToTimestamp(final String s) { - if (s == null) { - return null; - } - try { - return ZonedDateTime.parse(s); - } catch (DateTimeParseException e) { - return null; - } - } - -} diff --git a/src/main/java/org/dependencytrack/util/NotificationUtil.java b/src/main/java/org/dependencytrack/util/NotificationUtil.java index 1fd511d6b..629825157 100644 --- a/src/main/java/org/dependencytrack/util/NotificationUtil.java +++ b/src/main/java/org/dependencytrack/util/NotificationUtil.java @@ -28,7 +28,6 @@ import org.dependencytrack.model.AnalysisState; import org.dependencytrack.model.Component; import org.dependencytrack.model.ConfigPropertyConstants; -import org.dependencytrack.model.Finding; import org.dependencytrack.model.NotificationPublisher; import org.dependencytrack.model.Policy; import org.dependencytrack.model.PolicyCondition; @@ -37,20 +36,14 @@ import org.dependencytrack.model.Tag; import org.dependencytrack.model.ViolationAnalysis; import org.dependencytrack.model.ViolationAnalysisState; -import org.dependencytrack.model.Vulnerability; -import org.dependencytrack.model.VulnerabilityAlias; -import org.dependencytrack.model.VulnerabilityScan; import org.dependencytrack.notification.NotificationConstants; import org.dependencytrack.notification.NotificationGroup; import org.dependencytrack.notification.NotificationScope; import org.dependencytrack.notification.publisher.DefaultNotificationPublishers; import org.dependencytrack.notification.vo.AnalysisDecisionChange; -import org.dependencytrack.notification.vo.ComponentVulnAnalysisComplete; import org.dependencytrack.notification.vo.PolicyViolationIdentified; -import org.dependencytrack.notification.vo.ProjectVulnAnalysisComplete; import org.dependencytrack.notification.vo.ViolationAnalysisDecisionChange; import org.dependencytrack.persistence.QueryManager; -import org.dependencytrack.proto.notification.v1.ProjectVulnAnalysisStatus; import javax.jdo.FetchPlan; import javax.jdo.Query; @@ -58,17 +51,12 @@ import java.io.IOException; import java.net.URLDecoder; import java.nio.file.Path; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; import static java.nio.charset.StandardCharsets.UTF_8; @@ -419,93 +407,6 @@ public static String generateNotificationTitle(final String messageType, final o return messageType + " on Project: [" + projectStr + "]"; } - public static Notification createProjectVulnerabilityAnalysisCompleteNotification(VulnerabilityScan vulnScan, UUID token, ProjectVulnAnalysisStatus status) { - // TODO: Convert data loading to raw SQL to avoid loading unneeded data and excessive queries. - // See #analyzeNotificationCriteria(QueryManager, PolicyViolation) for an example. - try (QueryManager qm = new QueryManager()) { - Project project = qm.getObjectByUuid(Project.class, vulnScan.getTargetIdentifier()); - if (project == null) { - // This can happen when the project was deleted before completion of the vuln scan is detected. - throw new NoSuchElementException("Project with UUID %s does not exist".formatted(vulnScan.getTargetIdentifier())); - } - - List findings = qm.getFindings(project); - List componentList = new ArrayList<>(); - ConcurrentHashMap> map = new ConcurrentHashMap<>(); - for (Finding finding : findings) { - final var componentUuid = (String) finding.getComponent().get("uuid"); - Component component = qm.getObjectByUuid(Component.class, componentUuid); - if (component == null) { - // This can happen when the project was deleted while this method is executing. - throw new NoSuchElementException("Component with UUID %s does not exist in project %s" - .formatted(componentUuid, project.getUuid())); - } - final var vulnerabilityUuid = (String) finding.getVulnerability().get("uuid"); - Vulnerability vulnerability = qm.getObjectByUuid(Vulnerability.class, vulnerabilityUuid); - if (vulnerability == null) { - // Unlikely to happen, but when in doubt it's still better to raise this exception - // instead of running into a generic NPE. - throw new NoSuchElementException("Vulnerability with UUID %s does not exist".formatted(vulnerabilityUuid)); - } - final List aliases = qm.detach(qm.getVulnerabilityAliases(vulnerability)); - vulnerability.setAliases(aliases); - if (map.containsKey(component.getUuid().toString())) { - List temp1 = new ArrayList<>(); - temp1.add(vulnerability); - temp1.addAll(map.get(component.getUuid().toString())); - map.remove(component.getUuid().toString()); - map.put(component.getUuid().toString(), temp1); - } else { - //component should be added to list only if not present in map - componentList.add(component); - map.put(component.getUuid().toString(), List.of(vulnerability)); - } - } - - - List componentAnalysisCompleteList = createList(componentList, map); - return new Notification() - .scope(NotificationScope.PORTFOLIO) - .group(NotificationGroup.PROJECT_VULN_ANALYSIS_COMPLETE) - .level(NotificationLevel.INFORMATIONAL) - .title(NotificationConstants.Title.PROJECT_VULN_ANALYSIS_COMPLETE) - .content("project analysis complete for project " + project.getName() + " with id: " + project.getUuid() + " and with version: " + project.getVersion() + ". Vulnerability details added to subject ") - .subject(new ProjectVulnAnalysisComplete(token, project, componentAnalysisCompleteList, status)); - } - } - - public static List createList(List componentList, Map> map) { - List componentAnalysisCompleteList = new ArrayList<>(); - for (Component component : componentList) { - List vulnerabilities = map.get(component.getUuid().toString()); - List result = new ArrayList<>(); - for (Vulnerability vulnerability : vulnerabilities) { - Vulnerability vulnerability1 = new Vulnerability(); - vulnerability1.setId(vulnerability.getId()); - vulnerability1.setVulnId(vulnerability.getVulnId()); - vulnerability1.setSource(vulnerability.getSource()); - vulnerability1.setTitle(vulnerability.getTitle()); - vulnerability1.setSubTitle(vulnerability.getSubTitle()); - vulnerability1.setRecommendation(vulnerability.getRecommendation()); - vulnerability1.setSeverity(vulnerability.getSeverity()); - vulnerability1.setCvssV2BaseScore(vulnerability.getCvssV2BaseScore()); - vulnerability1.setCvssV3BaseScore(vulnerability.getCvssV3BaseScore()); - vulnerability1.setOwaspRRLikelihoodScore(vulnerability.getOwaspRRLikelihoodScore()); - vulnerability1.setOwaspRRTechnicalImpactScore(vulnerability.getOwaspRRTechnicalImpactScore()); - vulnerability1.setOwaspRRBusinessImpactScore(vulnerability.getOwaspRRBusinessImpactScore()); - vulnerability1.setCwes(vulnerability.getCwes()); - vulnerability1.setUuid(vulnerability.getUuid()); - vulnerability1.setVulnerableSoftware(vulnerability.getVulnerableSoftware()); - if (vulnerability.getAliases() != null && !vulnerability.getAliases().isEmpty()) { - vulnerability1.setAliases(vulnerability.getAliases()); - } - result.add(vulnerability1); - } - componentAnalysisCompleteList.add(new ComponentVulnAnalysisComplete(result, component)); - } - return componentAnalysisCompleteList; - } - public static class PolicyViolationNotificationProjection { public String projectUuid; public String projectName; diff --git a/src/test/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverterTest.java b/src/test/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverterTest.java index 042bb500e..81dad9341 100644 --- a/src/test/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverterTest.java +++ b/src/test/java/org/dependencytrack/parser/dependencytrack/NotificationModelConverterTest.java @@ -33,11 +33,9 @@ import org.dependencytrack.notification.vo.AnalysisDecisionChange; import org.dependencytrack.notification.vo.BomConsumedOrProcessed; import org.dependencytrack.notification.vo.BomProcessingFailed; -import org.dependencytrack.notification.vo.ComponentVulnAnalysisComplete; import org.dependencytrack.notification.vo.NewVulnerabilityIdentified; import org.dependencytrack.notification.vo.NewVulnerableDependency; import org.dependencytrack.notification.vo.PolicyViolationIdentified; -import org.dependencytrack.notification.vo.ProjectVulnAnalysisComplete; import org.dependencytrack.notification.vo.VexConsumedOrProcessed; import org.dependencytrack.notification.vo.ViolationAnalysisDecisionChange; import org.dependencytrack.persistence.CweImporter; @@ -54,8 +52,6 @@ import org.dependencytrack.proto.notification.v1.PolicyViolationAnalysisDecisionChangeSubject; import org.dependencytrack.proto.notification.v1.PolicyViolationSubject; import org.dependencytrack.proto.notification.v1.Project; -import org.dependencytrack.proto.notification.v1.ProjectVulnAnalysisCompleteSubject; -import org.dependencytrack.proto.notification.v1.ProjectVulnAnalysisStatus; import org.dependencytrack.proto.notification.v1.VexConsumedOrProcessedSubject; import org.dependencytrack.proto.notification.v1.Vulnerability; import org.dependencytrack.proto.notification.v1.VulnerabilityAnalysis; @@ -83,7 +79,6 @@ import static org.dependencytrack.proto.notification.v1.Group.GROUP_POLICY_VIOLATION; import static org.dependencytrack.proto.notification.v1.Group.GROUP_PROJECT_AUDIT_CHANGE; import static org.dependencytrack.proto.notification.v1.Group.GROUP_PROJECT_CREATED; -import static org.dependencytrack.proto.notification.v1.Group.GROUP_PROJECT_VULN_ANALYSIS_COMPLETE; import static org.dependencytrack.proto.notification.v1.Group.GROUP_REPOSITORY; import static org.dependencytrack.proto.notification.v1.Group.GROUP_VEX_CONSUMED; import static org.dependencytrack.proto.notification.v1.Group.GROUP_VEX_PROCESSED; @@ -738,36 +733,4 @@ private void assertPolicyViolation(final PolicyViolation policyViolation) { assertThat(policyViolation.getTimestamp().getSeconds()).isEqualTo(1679326314); } - @Test - public void testConvertComponentVulnAnalysisCompleteSubject() throws Exception { - final var token = UUID.randomUUID(); - final org.dependencytrack.model.Project project = createProject(); - final org.dependencytrack.model.Component component = createComponent(project); - final org.dependencytrack.model.Vulnerability vulnerability = createVulnerability(); - ComponentVulnAnalysisComplete componentVulnAnalysisComplete = new ComponentVulnAnalysisComplete(List.of(vulnerability), component); - final var alpineNotification = new alpine.notification.Notification(); - alpineNotification.setScope(NotificationScope.PORTFOLIO.name()); - alpineNotification.setLevel(NotificationLevel.INFORMATIONAL); - alpineNotification.setGroup(NotificationGroup.PROJECT_VULN_ANALYSIS_COMPLETE.name()); - alpineNotification.setTitle("Foo"); - alpineNotification.setContent("Bar"); - alpineNotification.setSubject(new ProjectVulnAnalysisComplete(token, project, List.of(componentVulnAnalysisComplete), ProjectVulnAnalysisStatus.PROJECT_VULN_ANALYSIS_STATUS_COMPLETED)); - - final Notification notification = NotificationModelConverter.convert(alpineNotification); - assertThat(notification.getScope()).isEqualTo(SCOPE_PORTFOLIO); - assertThat(notification.getLevel()).isEqualTo(LEVEL_INFORMATIONAL); - assertThat(notification.getGroup()).isEqualTo(GROUP_PROJECT_VULN_ANALYSIS_COMPLETE); - assertThat(notification.getTitle()).isEqualTo("Foo"); - assertThat(notification.getContent()).isEqualTo("Bar"); - assertThat(notification.getTimestamp().getSeconds()).isNotZero(); - assertThat(notification.hasSubject()).isTrue(); - assertThat(notification.getSubject().is(ProjectVulnAnalysisCompleteSubject.class)).isTrue(); - - final var subject = notification.getSubject().unpack(ProjectVulnAnalysisCompleteSubject.class); - assertProject(subject.getProject()); - assertThat(subject.getToken()).isEqualTo(token.toString()); - assertComponent(subject.getFindingsList().get(0).getComponent()); - assertVulnerability(subject.getFindingsList().get(0).getVulnerabilities(0)); - assertThat(subject.getStatus()).isEqualTo(ProjectVulnAnalysisStatus.PROJECT_VULN_ANALYSIS_STATUS_COMPLETED); - } } \ No newline at end of file