proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
|---|---|---|---|---|---|---|---|---|---|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/CoordinatesPolicyEvaluator.java
|
CoordinatesPolicyEvaluator
|
parseCoordinatesDefinition
|
class CoordinatesPolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(CoordinatesPolicyEvaluator.class);
private static final Pattern VERSION_OPERATOR_PATTERN = Pattern.compile("^(?<operator>[<>]=?|[!=]=)\\s*");
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.COORDINATES;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {
final List<PolicyConditionViolation> violations = new ArrayList<>();
for (final PolicyCondition condition : super.extractSupportedConditions(policy)) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
final Coordinates coordinates = parseCoordinatesDefinition(condition);
if (matches(condition.getOperator(), coordinates.getGroup(), component.getGroup())
&& matches(condition.getOperator(), coordinates.getName(), component.getName())
&& versionMatches(condition.getOperator(), coordinates.getVersion(), component.getVersion())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
return violations;
}
private boolean matches(final PolicyCondition.Operator operator, final String conditionValue, final String part) {
if (conditionValue == null && part == null) {
return true;
}
final String p = StringUtils.trimToNull(part);
if (p != null) {
if (PolicyCondition.Operator.MATCHES == operator) {
return org.dependencytrack.policy.Matcher.matches(p, conditionValue);
} else if (PolicyCondition.Operator.NO_MATCH == operator) {
return !org.dependencytrack.policy.Matcher.matches(p, conditionValue);
}
}
return false;
}
private boolean versionMatches(final PolicyCondition.Operator conditionOperator, final String conditionValue, final String part) {
if (conditionValue == null && part == null) {
return true;
} else if (conditionValue == null ^ part == null) {
return false;
}
final Matcher versionOperatorMatcher = VERSION_OPERATOR_PATTERN.matcher(conditionValue);
if (!versionOperatorMatcher.find()) {
// No operator provided, use default matching algorithm
return matches(conditionOperator, conditionValue, part);
}
final PolicyCondition.Operator versionOperator;
switch (versionOperatorMatcher.group(1)) {
case "==":
versionOperator = PolicyCondition.Operator.NUMERIC_EQUAL;
break;
case "!=":
versionOperator = PolicyCondition.Operator.NUMERIC_NOT_EQUAL;
break;
case "<":
versionOperator = PolicyCondition.Operator.NUMERIC_LESS_THAN;
break;
case "<=":
versionOperator = PolicyCondition.Operator.NUMERIC_LESSER_THAN_OR_EQUAL;
break;
case ">":
versionOperator = PolicyCondition.Operator.NUMERIC_GREATER_THAN;
break;
case ">=":
versionOperator = PolicyCondition.Operator.NUMERIC_GREATER_THAN_OR_EQUAL;
break;
default:
versionOperator = null;
break;
}
if (versionOperator == null) {
// Shouldn't ever happen because the regex won't match anything else
LOGGER.error("Failed to infer version operator from " + versionOperatorMatcher.group(1));
return false;
}
final var componentVersion = new ComponentVersion(part);
final var conditionVersion = new ComponentVersion(VERSION_OPERATOR_PATTERN.split(conditionValue)[1]);
final boolean versionMatches = VersionPolicyEvaluator.matches(componentVersion, conditionVersion, versionOperator);
if (PolicyCondition.Operator.NO_MATCH == conditionOperator) {
return !versionMatches;
}
return versionMatches;
}
/**
* Expects the format of condition.getValue() to be:
* <pre>
* {
* 'group': 'acme',
* 'name': 'test component',
* 'version': '1.0.0'
* }
* </pre>
*
* @param condition teh condition to evaluate
* @return the Coordinates
*/
private Coordinates parseCoordinatesDefinition(final PolicyCondition condition) {<FILL_FUNCTION_BODY>}
}
|
if (condition.getValue() == null) {
return new Coordinates(null, null, null);
}
final JSONObject def = new JSONObject(condition.getValue());
return new Coordinates(
def.optString("group", null),
def.optString("name", null),
def.optString("version", null)
);
| 1,197
| 89
| 1,286
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/CpePolicyEvaluator.java
|
CpePolicyEvaluator
|
evaluate
|
class CpePolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(CpePolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.CPE;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
for (final PolicyCondition condition: super.extractSupportedConditions(policy)) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
if (PolicyCondition.Operator.MATCHES == condition.getOperator()) {
if (Matcher.matches(component.getCpe(), condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
} else if (PolicyCondition.Operator.NO_MATCH == condition.getOperator()) {
if (!Matcher.matches(component.getCpe(), condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
}
return violations;
| 139
| 214
| 353
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/CwePolicyEvaluator.java
|
CwePolicyEvaluator
|
evaluate
|
class CwePolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(CwePolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.CWE;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
public boolean matches(final PolicyCondition.Operator operator, final List<Integer> vulnerabilityCwes, final String conditionValue) {
if (conditionValue == null || vulnerabilityCwes == null) {
return false;
}
if("*".equals(conditionValue.trim())){
return true;
}
List<Integer> cweIdsToMatch = new ArrayList<>();
List<String> conditionCwes = Arrays.asList(conditionValue.split(","));
conditionCwes.replaceAll(String::trim);
conditionCwes.stream().forEach(cwe -> {
Integer id = CweResolver.getInstance().parseCweString(cwe);
if(id != null)
cweIdsToMatch.add(id);
});
if (!cweIdsToMatch.isEmpty()) {
if (PolicyCondition.Operator.CONTAINS_ANY == operator) {
return CollectionUtils.containsAny(vulnerabilityCwes, cweIdsToMatch);
} else if (PolicyCondition.Operator.CONTAINS_ALL == operator) {
return CollectionUtils.containsAll(vulnerabilityCwes, cweIdsToMatch);
}
}
return false;
}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
final List<PolicyCondition> policyConditions = super.extractSupportedConditions(policy);
if (policyConditions.isEmpty()) {
return violations;
}
for (final Vulnerability vulnerability : qm.getAllVulnerabilities(component, false)) {
for (final PolicyCondition condition: policyConditions) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
if (matches(condition.getOperator(), vulnerability.getCwes(), condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
}
return violations;
| 444
| 200
| 644
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/LicenseGroupPolicyEvaluator.java
|
TemporaryLicenseGroup
|
evaluate
|
class TemporaryLicenseGroup extends LicenseGroup {
private static final long serialVersionUID = -1268650463377651000L;
}
/**
* Whether a condition provides a positive list or negative list of licenses.
*
* <p>
* Configuring a LicenseGroupPolicy allows the user to specify conditions as either "IS
* MyLicenseGroup" or "IS_NOT MyLicenseGroup", and a policy violation is reported when the
* condition is met. The IS and IS_NOT is not very intuitive when actually evaluating a
* condition; what it actually means is that either "IS_NOT" is selected, and the user provides
* a list of licenses that are allowed to be used (violation if license is not in license
* group), or "IS" is selected and the user provides a list of licenses that cannot be used
* (violation if license is in license group).
*
* <p>
* In order to simplify thinking about license violations, this license group type is used.
*
*/
private static enum LicenseGroupType {
/**
* License group represents a list of licenses that are explicitly allowed to be used
*/
AllowedLicenseList,
/**
* License group represents a list of licenses that are not allowed to be used
*/
ForbiddenLicenseList;
}
private static final Logger LOGGER = Logger.getLogger(LicenseGroupPolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.LICENSE_GROUP;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
final List<PolicyCondition> policyConditions = super.extractSupportedConditions(policy);
if (policyConditions.isEmpty()) {
return violations;
}
final SpdxExpression expression = getSpdxExpressionFromComponent(component);
for (final PolicyCondition condition : policyConditions) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition ("
+ condition.getUuid() + ")");
final LicenseGroup lg = qm.getObjectByUuid(LicenseGroup.class, condition.getValue());
if (lg == null) {
LOGGER.warn("The license group %s does not exist; Skipping evaluation of condition %s of policy %s"
.formatted(condition.getValue(), condition.getUuid(), policy.getName()));
continue;
}
evaluateCondition(qm, condition, expression, lg, component, violations);
}
return violations;
| 457
| 254
| 711
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/LicensePolicyEvaluator.java
|
LicensePolicyEvaluator
|
evaluate
|
class LicensePolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(LicensePolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.LICENSE;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
final List<PolicyCondition> policyConditions = super.extractSupportedConditions(policy);
if (policyConditions.isEmpty()) {
return violations;
}
// use spdx expression checking logic from the license group policy evaluator
final SpdxExpression expression = LicenseGroupPolicyEvaluator.getSpdxExpressionFromComponent(component);
boolean allPoliciesViolated = true;
for (final PolicyCondition condition: super.extractSupportedConditions(policy)) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
LicenseGroup licenseGroup = null;
// lg will stay null if we are checking for "unresolved"
if (!condition.getValue().equals("unresolved")) {
License conditionLicense = qm.getObjectByUuid(License.class, condition.getValue());
licenseGroup = LicenseGroupPolicyEvaluator.getTemporaryLicenseGroupForLicense(conditionLicense);
}
boolean addedViolation = LicenseGroupPolicyEvaluator.evaluateCondition(qm, condition, expression,
licenseGroup, component, violations);
if (addedViolation == false) {
allPoliciesViolated = false;
}
}
return violations;
| 137
| 340
| 477
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/Matcher.java
|
Matcher
|
matches
|
class Matcher {
private Matcher() {
// Utility-class should not be instantiated
}
/**
* Check if the given value matches with the conditionString. If the
* conditionString is not a regular expression, turn it into one.
*
* @param value The value to match against
* @param conditionString The condition that should match -- may or may not be a
* regular expression
* @return <code>true</code> if the value matches the conditionString
*/
static boolean matches(String value, String conditionString) {<FILL_FUNCTION_BODY>}
}
|
if (value == null && conditionString == null) {
return true;
}
if (value == null ^ conditionString == null) {
return false;
}
conditionString = conditionString.replace("*", ".*").replace("..*", ".*");
if (!conditionString.startsWith("^") && !conditionString.startsWith(".*")) {
conditionString = ".*" + conditionString;
}
if (!conditionString.endsWith("$") && !conditionString.endsWith(".*")) {
conditionString += ".*";
}
return value.matches(conditionString);
| 155
| 155
| 310
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/PackageURLPolicyEvaluator.java
|
PackageURLPolicyEvaluator
|
evaluate
|
class PackageURLPolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(PackageURLPolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.PACKAGE_URL;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
for (final PolicyCondition condition: super.extractSupportedConditions(policy)) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
final var canonicalPurl = component.getPurl() == null ? null : component.getPurl().canonicalize();
if (PolicyCondition.Operator.MATCHES == condition.getOperator()) {
if (Matcher.matches(canonicalPurl, condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
} else if (PolicyCondition.Operator.NO_MATCH == condition.getOperator()) {
if (!Matcher.matches(canonicalPurl, condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
}
return violations;
| 142
| 241
| 383
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/PolicyEngine.java
|
PolicyEngine
|
createPolicyViolations
|
class PolicyEngine {
private static final Logger LOGGER = Logger.getLogger(PolicyEngine.class);
private final List<PolicyEvaluator> evaluators = new ArrayList<>();
public PolicyEngine() {
evaluators.add(new SeverityPolicyEvaluator());
evaluators.add(new CoordinatesPolicyEvaluator());
evaluators.add(new LicenseGroupPolicyEvaluator());
evaluators.add(new LicensePolicyEvaluator());
evaluators.add(new PackageURLPolicyEvaluator());
evaluators.add(new CpePolicyEvaluator());
evaluators.add(new SwidTagIdPolicyEvaluator());
evaluators.add(new VersionPolicyEvaluator());
evaluators.add(new ComponentAgePolicyEvaluator());
evaluators.add(new ComponentHashPolicyEvaluator());
evaluators.add(new CwePolicyEvaluator());
evaluators.add(new VulnerabilityIdPolicyEvaluator());
evaluators.add(new VersionDistancePolicyEvaluator());
}
public List<PolicyViolation> evaluate(final List<Component> components) {
LOGGER.info("Evaluating " + components.size() + " component(s) against applicable policies");
List<PolicyViolation> violations = new ArrayList<>();
try (final QueryManager qm = new QueryManager()) {
final List<Policy> policies = qm.getAllPolicies();
for (final Component component : components) {
final Component componentFromDb = qm.getObjectById(Component.class, component.getId());
violations.addAll(this.evaluate(qm, policies, componentFromDb));
}
}
LOGGER.info("Policy analysis complete");
return violations;
}
private List<PolicyViolation> evaluate(final QueryManager qm, final List<Policy> policies, final Component component) {
final List<PolicyViolation> policyViolations = new ArrayList<>();
final List<PolicyViolation> existingPolicyViolations = qm.detach(qm.getAllPolicyViolations(component));
for (final Policy policy : policies) {
if (policy.isGlobal() || isPolicyAssignedToProject(policy, component.getProject())
|| isPolicyAssignedToProjectTag(policy, component.getProject())) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy (" + policy.getUuid() + ")");
final List<PolicyConditionViolation> policyConditionViolations = new ArrayList<>();
int policyConditionsViolated = 0;
for (final PolicyEvaluator evaluator : evaluators) {
evaluator.setQueryManager(qm);
final List<PolicyConditionViolation> policyConditionViolationsFromEvaluator = evaluator.evaluate(policy, component);
if (!policyConditionViolationsFromEvaluator.isEmpty()) {
policyConditionViolations.addAll(policyConditionViolationsFromEvaluator);
policyConditionsViolated += (int) policyConditionViolationsFromEvaluator.stream()
.map(pcv -> pcv.getPolicyCondition().getId())
.sorted()
.distinct()
.count();
}
}
if (Policy.Operator.ANY == policy.getOperator()) {
if (policyConditionsViolated > 0) {
policyViolations.addAll(createPolicyViolations(qm, policyConditionViolations));
}
} else if (Policy.Operator.ALL == policy.getOperator() && policyConditionsViolated == policy.getPolicyConditions().size()) {
policyViolations.addAll(createPolicyViolations(qm, policyConditionViolations));
}
}
}
qm.reconcilePolicyViolations(component, policyViolations);
for (final PolicyViolation pv : qm.getAllPolicyViolations(component)) {
if (existingPolicyViolations.stream().noneMatch(existingViolation -> existingViolation.getId() == pv.getId())) {
NotificationUtil.analyzeNotificationCriteria(qm, pv);
}
}
return policyViolations;
}
private boolean isPolicyAssignedToProject(Policy policy, Project project) {
if (policy.getProjects() == null || policy.getProjects().isEmpty()) {
return false;
}
return (policy.getProjects().stream().anyMatch(p -> p.getId() == project.getId()) || (Boolean.TRUE.equals(policy.isIncludeChildren()) && isPolicyAssignedToParentProject(policy, project)));
}
private List<PolicyViolation> createPolicyViolations(final QueryManager qm, final List<PolicyConditionViolation> pcvList) {<FILL_FUNCTION_BODY>}
public PolicyViolation.Type determineViolationType(final PolicyCondition.Subject subject) {
if (subject == null) {
return null;
}
return switch (subject) {
case CWE, SEVERITY, VULNERABILITY_ID -> PolicyViolation.Type.SECURITY;
case AGE, COORDINATES, PACKAGE_URL, CPE, SWID_TAGID, COMPONENT_HASH, VERSION, VERSION_DISTANCE ->
PolicyViolation.Type.OPERATIONAL;
case LICENSE, LICENSE_GROUP -> PolicyViolation.Type.LICENSE;
};
}
private boolean isPolicyAssignedToProjectTag(Policy policy, Project project) {
if (policy.getTags() == null || policy.getTags().isEmpty()) {
return false;
}
boolean flag = false;
for (Tag projectTag : project.getTags()) {
flag = policy.getTags().stream().anyMatch(policyTag -> policyTag.getId() == projectTag.getId());
if (flag) {
break;
}
}
return flag;
}
private boolean isPolicyAssignedToParentProject(Policy policy, Project child) {
if (child.getParent() == null) {
return false;
}
if (policy.getProjects().stream().anyMatch(p -> p.getId() == child.getParent().getId())) {
return true;
}
return isPolicyAssignedToParentProject(policy, child.getParent());
}
}
|
final List<PolicyViolation> policyViolations = new ArrayList<>();
for (PolicyConditionViolation pcv : pcvList) {
final PolicyViolation pv = new PolicyViolation();
pv.setComponent(pcv.getComponent());
pv.setPolicyCondition(pcv.getPolicyCondition());
pv.setType(determineViolationType(pcv.getPolicyCondition().getSubject()));
pv.setTimestamp(new Date());
policyViolations.add(qm.addPolicyViolationIfNotExist(pv));
}
return policyViolations;
| 1,602
| 157
| 1,759
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/SeverityPolicyEvaluator.java
|
SeverityPolicyEvaluator
|
evaluate
|
class SeverityPolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(SeverityPolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.SEVERITY;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
final List<PolicyCondition> policyConditions = super.extractSupportedConditions(policy);
if (policyConditions.isEmpty()) {
return violations;
}
//final Component component = qm.getObjectById(Component.class, c.getId());
for (final Vulnerability vulnerability : qm.getAllVulnerabilities(component, false)) {
for (final PolicyCondition condition: policyConditions) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
if (PolicyCondition.Operator.IS == condition.getOperator()) {
if (vulnerability.getSeverity().name().equals(condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
} else if (PolicyCondition.Operator.IS_NOT == condition.getOperator()) {
if (! vulnerability.getSeverity().name().equals(condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
}
}
return violations;
| 142
| 301
| 443
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/SwidTagIdPolicyEvaluator.java
|
SwidTagIdPolicyEvaluator
|
evaluate
|
class SwidTagIdPolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(SwidTagIdPolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.SWID_TAGID;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
for (final PolicyCondition condition: super.extractSupportedConditions(policy)) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
if (PolicyCondition.Operator.MATCHES == condition.getOperator()) {
if (Matcher.matches(component.getSwidTagId(), condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
} else if (PolicyCondition.Operator.NO_MATCH == condition.getOperator()) {
if (!Matcher.matches(component.getSwidTagId(), condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
}
return violations;
| 146
| 218
| 364
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/VersionDistancePolicyEvaluator.java
|
VersionDistancePolicyEvaluator
|
evaluate
|
class VersionDistancePolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(VersionDistancePolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.VERSION_DISTANCE;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
/**
* Evaluate VersionDistance conditions for a given versionDistance. A condition
*
* @param condition operator and value containing combined {@link VersionDistance} values
* @param versionDistance the {@link VersionDistance} to evalue
* @return true if the condition is true for the components versionDistance, false otherwise
*/
private boolean evaluate(final PolicyCondition condition, final VersionDistance versionDistance) {
final var operator = condition.getOperator();
final var value = condition.getValue();
if (!StringUtils.isEmpty(value)) {
final var json = new JSONObject(value);
final var epoch = json.optString("epoch", "0");
final var major = json.optString("major", "?");
final var minor = json.optString("minor", "?");
final var patch = json.optString("patch", "?");
final List<VersionDistance> versionDistanceList;
try {
versionDistanceList = VersionDistance.parse(epoch+":"+major+"."+minor+"."+patch);
} catch (IllegalArgumentException e) {
LOGGER.error("Invalid version distance format", e);
return false;
}
if (versionDistanceList.isEmpty()) {
versionDistanceList.add(new VersionDistance(0,0,0));
}
return versionDistanceList.stream().reduce(
false,
(latest, current) -> latest || matches(operator, current, versionDistance),
Boolean::logicalOr
);
}
return false;
}
private boolean matches(final Operator operator, final VersionDistance policyDistance, final VersionDistance versionDistance) {
return switch (operator) {
case NUMERIC_GREATER_THAN -> versionDistance.compareTo(policyDistance) > 0;
case NUMERIC_GREATER_THAN_OR_EQUAL -> versionDistance.compareTo(policyDistance) >= 0;
case NUMERIC_EQUAL -> versionDistance.compareTo(policyDistance) == 0;
case NUMERIC_NOT_EQUAL -> versionDistance.compareTo(policyDistance) != 0;
case NUMERIC_LESSER_THAN_OR_EQUAL -> versionDistance.compareTo(policyDistance) <= 0;
case NUMERIC_LESS_THAN -> versionDistance.compareTo(policyDistance) < 0;
default -> {
LOGGER.warn("Operator %s is not supported for component age conditions".formatted(operator));
yield false;
}
};
}
/**
* Test if the components project direct dependencies contain a given component
* If so, the component is a direct dependency of the project
*
* @param component component to test
* @return If the components project direct dependencies contain the component
*/
private boolean isDirectDependency(Component component) {
if (component.getProject().getDirectDependencies() == null) {
return false;
}
return component.getProject().getDirectDependencies().contains("\"uuid\":\"" + component.getUuid().toString() + "\"");
}
}
|
final var violations = new ArrayList<PolicyConditionViolation>();
if (component.getPurl() == null || component.getVersion() == null) {
return violations;
}
final List<PolicyCondition> conditions = super.extractSupportedConditions(policy);
if (conditions.isEmpty()) {
return violations;
}
final RepositoryType repoType = RepositoryType.resolve(component.getPurl());
if (RepositoryType.UNSUPPORTED == repoType) {
return violations;
}
final RepositoryMetaComponent metaComponent;
try (final var qm = new QueryManager()) {
metaComponent = qm.getRepositoryMetaComponent(repoType,
component.getPurl().getNamespace(), component.getPurl().getName());
qm.getPersistenceManager().detachCopy(metaComponent);
}
if (metaComponent == null || metaComponent.getLatestVersion() == null) {
return violations;
}
final VersionDistance versionDistance;
try {
versionDistance = VersionDistance.getVersionDistance(component.getVersion(), metaComponent.getLatestVersion());
} catch (RuntimeException e) {
LOGGER.warn("""
Failed to compute version distance for component %s (UUID: %s), \
between component version %s and latest version %s; Skipping\
""".formatted(component, component.getUuid(), component.getVersion(), metaComponent.getLatestVersion()), e);
return violations;
}
for (final PolicyCondition condition : conditions) {
if (isDirectDependency(component) && evaluate(condition, versionDistance)) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
return violations;
| 915
| 441
| 1,356
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/VersionPolicyEvaluator.java
|
VersionPolicyEvaluator
|
evaluate
|
class VersionPolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(VersionPolicyEvaluator.class);
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.VERSION;
}
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
static boolean matches(final ComponentVersion componentVersion,
final ComponentVersion conditionVersion,
final PolicyCondition.Operator operator) {
final int comparisonResult = componentVersion.compareTo(conditionVersion);
switch (operator) {
case NUMERIC_EQUAL:
return comparisonResult == 0;
case NUMERIC_NOT_EQUAL:
return comparisonResult != 0;
case NUMERIC_LESS_THAN:
return comparisonResult < 0;
case NUMERIC_LESSER_THAN_OR_EQUAL:
return comparisonResult <= 0;
case NUMERIC_GREATER_THAN:
return comparisonResult > 0;
case NUMERIC_GREATER_THAN_OR_EQUAL:
return comparisonResult >= 0;
default:
LOGGER.warn("Unsupported operation " + operator);
break;
}
return false;
}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
final List<PolicyCondition> policyConditions = super.extractSupportedConditions(policy);
if (policyConditions.isEmpty()) {
return violations;
}
final var componentVersion = new ComponentVersion(component.getVersion());
for (final PolicyCondition condition : super.extractSupportedConditions(policy)) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
final var conditionVersion = new ComponentVersion(condition.getValue());
if (conditionVersion.getVersionParts().isEmpty()) {
LOGGER.warn("Unable to parse version (" + condition.getValue() + " provided by condition");
continue;
}
if (matches(componentVersion, conditionVersion, condition.getOperator())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
return violations;
| 345
| 252
| 597
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/policy/VulnerabilityIdPolicyEvaluator.java
|
VulnerabilityIdPolicyEvaluator
|
evaluate
|
class VulnerabilityIdPolicyEvaluator extends AbstractPolicyEvaluator {
private static final Logger LOGGER = Logger.getLogger(VulnerabilityIdPolicyEvaluator.class);
/**
* {@inheritDoc}
*/
@Override
public PolicyCondition.Subject supportedSubject() {
return PolicyCondition.Subject.VULNERABILITY_ID;
}
/**
* {@inheritDoc}
*/
@Override
public List<PolicyConditionViolation> evaluate(final Policy policy, final Component component) {<FILL_FUNCTION_BODY>}
}
|
final List<PolicyConditionViolation> violations = new ArrayList<>();
final List<PolicyCondition> policyConditions = super.extractSupportedConditions(policy);
if (policyConditions.isEmpty()) {
return violations;
}
for (final Vulnerability vulnerability : qm.getAllVulnerabilities(component, false)) {
for (final PolicyCondition condition: policyConditions) {
LOGGER.debug("Evaluating component (" + component.getUuid() + ") against policy condition (" + condition.getUuid() + ")");
if (PolicyCondition.Operator.IS == condition.getOperator()) {
if (vulnerability.getVulnId().equals(condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
} else if (PolicyCondition.Operator.IS_NOT == condition.getOperator()) {
if (! vulnerability.getVulnId().equals(condition.getValue())) {
violations.add(new PolicyConditionViolation(condition, component));
}
}
}
}
return violations;
| 149
| 277
| 426
|
<methods>public non-sealed void <init>() ,public void setQueryManager(org.dependencytrack.persistence.QueryManager) <variables>protected org.dependencytrack.persistence.QueryManager qm
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/AbstractConfigPropertyResource.java
|
AbstractConfigPropertyResource
|
updatePropertyValueInternal
|
class AbstractConfigPropertyResource extends AlpineResource {
private final Logger LOGGER = Logger.getLogger(this.getClass()); // Use the classes that extend this, not this class itself
static final String ENCRYPTED_PLACEHOLDER = "HiddenDecryptedPropertyPlaceholder";
Response updatePropertyValue(QueryManager qm, IConfigProperty json, IConfigProperty property) {
if (property != null) {
final Response check = updatePropertyValueInternal(json, property);
if (check != null) {
return check;
}
property = qm.persist(property);
IConfigProperty detached = qm.detach(property.getClass(), property.getId());
if (IConfigProperty.PropertyType.ENCRYPTEDSTRING == detached.getPropertyType()) {
detached.setPropertyValue(ENCRYPTED_PLACEHOLDER);
}
return Response.ok(detached).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The config property could not be found.").build();
}
}
private Response updatePropertyValueInternal(IConfigProperty json, IConfigProperty property) {<FILL_FUNCTION_BODY>}
}
|
if (property.getPropertyType() == IConfigProperty.PropertyType.BOOLEAN) {
property.setPropertyValue(String.valueOf(BooleanUtil.valueOf(json.getPropertyValue())));
} else if (property.getPropertyType() == IConfigProperty.PropertyType.INTEGER) {
try {
int propertyValue = Integer.parseInt(json.getPropertyValue());
if(ConfigPropertyConstants.TASK_SCHEDULER_LDAP_SYNC_CADENCE.getGroupName().equals(json.getGroupName()) && propertyValue <= 0) {
return Response.status(Response.Status.BAD_REQUEST).entity("A Task scheduler cadence ("+json.getPropertyName()+") cannot be inferior to one hour.A value of "+propertyValue+" was provided.").build();
}
if(ConfigPropertyConstants.SEARCH_INDEXES_CONSISTENCY_CHECK_DELTA_THRESHOLD.getPropertyName().equals(json.getPropertyName()) && (propertyValue < 1 || propertyValue > 100)) {
return Response.status(Response.Status.BAD_REQUEST).entity("Lucene index delta threshold ("+json.getPropertyName()+") cannot be inferior to 1 or superior to 100.A value of "+propertyValue+" was provided.").build();
}
property.setPropertyValue(String.valueOf(propertyValue));
} catch (NumberFormatException e) {
return Response.status(Response.Status.BAD_REQUEST).entity("The property expected an integer and an integer was not sent.").build();
}
} else if (property.getPropertyType() == IConfigProperty.PropertyType.NUMBER) {
try {
new BigDecimal(json.getPropertyValue()); // don't actually use it, just see if it's parses without exception
property.setPropertyValue(json.getPropertyValue());
} catch (NumberFormatException e) {
return Response.status(Response.Status.BAD_REQUEST).entity("The property expected a number and a number was not sent.").build();
}
} else if (property.getPropertyType() == IConfigProperty.PropertyType.URL) {
if (json.getPropertyValue() == null) {
property.setPropertyValue(null);
} else {
try {
final URL url = new URL(json.getPropertyValue());
property.setPropertyValue(url.toExternalForm());
} catch (MalformedURLException e) {
return Response.status(Response.Status.BAD_REQUEST).entity("The property expected a URL but the URL was malformed.").build();
}
}
} else if (property.getPropertyType() == IConfigProperty.PropertyType.UUID) {
if (UuidUtil.isValidUUID(json.getPropertyValue())) {
property.setPropertyValue(json.getPropertyValue());
} else {
return Response.status(Response.Status.BAD_REQUEST).entity("The property expected a UUID but a valid UUID was not sent.").build();
}
} else if (property.getPropertyType() == IConfigProperty.PropertyType.ENCRYPTEDSTRING) {
if (json.getPropertyValue() == null) {
property.setPropertyValue(null);
} else {
try {
// Determine if the value of the encrypted property value is that of the placeholder. If so, the value has not been modified and should not be saved.
if (ENCRYPTED_PLACEHOLDER.equals(json.getPropertyValue())) {
return Response.notModified().build();
}
property.setPropertyValue(DataEncryption.encryptAsString(json.getPropertyValue()));
} catch (Exception e) {
LOGGER.error("An error occurred while encrypting config property value", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("An error occurred while encrypting property value. Check log for details.").build();
}
}
} else if(ConfigPropertyConstants.VULNERABILITY_SOURCE_GOOGLE_OSV_ENABLED.getPropertyName().equals(json.getPropertyName())) {
String propertyValue = json.getPropertyValue();
if (propertyValue != null && !propertyValue.isBlank()) {
Set<String> ecosystems = Arrays.stream(propertyValue.split(";")).map(String::trim).collect(Collectors.toSet());
property.setPropertyValue(String.join(";", ecosystems));
} else {
property.setPropertyValue(propertyValue);
}
} else {
property.setPropertyValue(json.getPropertyValue());
}
return null;
| 310
| 1,147
| 1,457
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/AccessControlResource.java
|
AccessControlResource
|
addMapping
|
class AccessControlResource extends AlpineResource {
private static final Logger LOGGER = Logger.getLogger(AccessControlResource.class);
@GET
@Path("/team/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns the projects assigned to the specified team",
response = String.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of projects"),
notes = "<p>Requires permission <strong>ACCESS_MANAGEMENT</strong></p>"
)
@PaginatedApi
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the team could not be found"),
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response retrieveProjects (@ApiParam(value = "The UUID of the team to retrieve mappings for", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid,
@ApiParam(value = "Optionally excludes inactive projects from being returned", required = false)
@QueryParam("excludeInactive") boolean excludeInactive,
@ApiParam(value = "Optionally excludes children projects from being returned", required = false)
@QueryParam("onlyRoot") boolean onlyRoot) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Team team = qm.getObjectByUuid(Team.class, uuid);
if (team != null) {
final PaginatedResult result = qm.getProjects(team, excludeInactive, true, onlyRoot);
return Response.ok(result.getObjects()).header(TOTAL_COUNT_HEADER, result.getTotal()).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the team could not be found.").build();
}
}
}
@PUT
@Path("/mapping")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Adds an ACL mapping",
response = AclMappingRequest.class,
notes = "<p>Requires permission <strong>ACCESS_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the team or project could not be found"),
@ApiResponse(code = 409, message = "A mapping with the same team and project already exists")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response addMapping(AclMappingRequest request) {<FILL_FUNCTION_BODY>}
@DELETE
@Path("/mapping/team/{teamUuid}/project/{projectUuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Removes an ACL mapping",
notes = "<p>Requires permission <strong>ACCESS_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the team or project could not be found"),
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteMapping(
@ApiParam(value = "The UUID of the team to delete the mapping for", format = "uuid", required = true)
@PathParam("teamUuid") @ValidUuid String teamUuid,
@ApiParam(value = "The UUID of the project to delete the mapping for", format = "uuid", required = true)
@PathParam("projectUuid") @ValidUuid String projectUuid) {
try (QueryManager qm = new QueryManager()) {
final Team team = qm.getObjectByUuid(Team.class, teamUuid);
final Project project = qm.getObjectByUuid(Project.class, projectUuid);
if (team != null && project != null) {
final List<Team> teams = new ArrayList<>();
for (final Team t: project.getAccessTeams()) {
if (t.getUuid() != team.getUuid()) {
teams.add(t);
}
}
project.setAccessTeams(teams);
qm.persist(project);
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the team or project could not be found.").build();
}
}
}
}
|
final Validator validator = super.getValidator();
failOnValidationError(
validator.validateProperty(request, "team"),
validator.validateProperty(request, "project")
);
try (QueryManager qm = new QueryManager()) {
final Team team = qm.getObjectByUuid(Team.class, request.getTeam());
final Project project = qm.getObjectByUuid(Project.class, request.getProject());
if (team != null && project != null) {
for (final Team t: project.getAccessTeams()) {
if (t.getUuid() == team.getUuid()) {
return Response.status(Response.Status.CONFLICT).entity("A mapping with the same team and project already exists.").build();
}
}
project.addAccessTeam(team);
qm.persist(project);
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the team could not be found.").build();
}
}
| 1,242
| 272
| 1,514
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/AnalysisResource.java
|
AnalysisResource
|
retrieveAnalysis
|
class AnalysisResource extends AlpineResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Retrieves an analysis trail",
response = Analysis.class,
notes = "<p>Requires permission <strong>VIEW_VULNERABILITY</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The project, component, or vulnerability could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_VULNERABILITY)
public Response retrieveAnalysis(@ApiParam(value = "The UUID of the project", format = "uuid")
@QueryParam("project") String projectUuid,
@ApiParam(value = "The UUID of the component", format = "uuid", required = true)
@QueryParam("component") String componentUuid,
@ApiParam(value = "The UUID of the vulnerability", format = "uuid", required = true)
@QueryParam("vulnerability") String vulnerabilityUuid) {<FILL_FUNCTION_BODY>}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Records an analysis decision",
response = Analysis.class,
notes = "<p>Requires permission <strong>VULNERABILITY_ANALYSIS</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The project, component, or vulnerability could not be found")
})
@PermissionRequired(Permissions.Constants.VULNERABILITY_ANALYSIS)
public Response updateAnalysis(AnalysisRequest request) {
final Validator validator = getValidator();
failOnValidationError(
validator.validateProperty(request, "project"),
validator.validateProperty(request, "component"),
validator.validateProperty(request, "vulnerability"),
validator.validateProperty(request, "analysisState"),
validator.validateProperty(request, "analysisJustification"),
validator.validateProperty(request, "analysisResponse"),
validator.validateProperty(request, "analysisDetails"),
validator.validateProperty(request, "comment")
);
try (QueryManager qm = new QueryManager()) {
final Project project = qm.getObjectByUuid(Project.class, request.getProject());
if (project == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
final Component component = qm.getObjectByUuid(Component.class, request.getComponent());
if (component == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
final Vulnerability vulnerability = qm.getObjectByUuid(Vulnerability.class, request.getVulnerability());
if (vulnerability == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The vulnerability could not be found.").build();
}
String commenter = null;
if (getPrincipal() instanceof LdapUser || getPrincipal() instanceof ManagedUser || getPrincipal() instanceof OidcUser) {
commenter = ((UserPrincipal) getPrincipal()).getUsername();
}
boolean analysisStateChange = false;
boolean suppressionChange = false;
Analysis analysis = qm.getAnalysis(component, vulnerability);
if (analysis != null) {
analysisStateChange = AnalysisCommentUtil.makeStateComment(qm, analysis, request.getAnalysisState(), commenter);
AnalysisCommentUtil.makeJustificationComment(qm, analysis, request.getAnalysisJustification(), commenter);
AnalysisCommentUtil.makeAnalysisResponseComment(qm, analysis, request.getAnalysisResponse(), commenter);
AnalysisCommentUtil.makeAnalysisDetailsComment(qm, analysis, request.getAnalysisDetails(), commenter);
suppressionChange = AnalysisCommentUtil.makeAnalysisSuppressionComment(qm, analysis, request.isSuppressed(), commenter);
analysis = qm.makeAnalysis(component, vulnerability, request.getAnalysisState(), request.getAnalysisJustification(), request.getAnalysisResponse(), request.getAnalysisDetails(), request.isSuppressed());
} else {
analysis = qm.makeAnalysis(component, vulnerability, request.getAnalysisState(), request.getAnalysisJustification(), request.getAnalysisResponse(), request.getAnalysisDetails(), request.isSuppressed());
analysisStateChange = true; // this is a new analysis - so set to true because it was previously null
if (AnalysisState.NOT_SET != request.getAnalysisState()) {
qm.makeAnalysisComment(analysis, String.format("Analysis: %s → %s", AnalysisState.NOT_SET, request.getAnalysisState()), commenter);
}
}
final String comment = StringUtils.trimToNull(request.getComment());
qm.makeAnalysisComment(analysis, comment, commenter);
analysis = qm.getAnalysis(component, vulnerability);
NotificationUtil.analyzeNotificationCriteria(qm, analysis, analysisStateChange, suppressionChange);
return Response.ok(analysis).build();
}
}
}
|
failOnValidationError(
new ValidationTask(RegexSequence.Pattern.UUID, projectUuid, "Project is not a valid UUID", false), // this is optional
new ValidationTask(RegexSequence.Pattern.UUID, componentUuid, "Component is not a valid UUID"),
new ValidationTask(RegexSequence.Pattern.UUID, vulnerabilityUuid, "Vulnerability is not a valid UUID")
);
try (QueryManager qm = new QueryManager()) {
final Project project;
if (StringUtils.trimToNull(projectUuid) != null) {
project = qm.getObjectByUuid(Project.class, projectUuid);
if (project == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
final Component component = qm.getObjectByUuid(Component.class, componentUuid);
if (component == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
final Vulnerability vulnerability = qm.getObjectByUuid(Vulnerability.class, vulnerabilityUuid);
if (vulnerability == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The vulnerability could not be found.").build();
}
final Analysis analysis = qm.getAnalysis(component, vulnerability);
if (analysis == null) {
return Response.status(Response.Status.NOT_FOUND).entity("No analysis exists.").build();
}
return Response.ok(analysis).build();
}
| 1,366
| 414
| 1,780
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/BadgeResource.java
|
BadgeResource
|
getProjectPolicyViolationsBadge
|
class BadgeResource extends AlpineResource {
private static final String SVG_MEDIA_TYPE = "image/svg+xml";
private boolean isBadgeSupportEnabled(final QueryManager qm) {
ConfigProperty property = qm.getConfigProperty(
GENERAL_BADGE_ENABLED.getGroupName(), GENERAL_BADGE_ENABLED.getPropertyName());
return BooleanUtil.valueOf(property.getPropertyValue());
}
@GET
@Path("/vulns/project/{uuid}")
@Produces(SVG_MEDIA_TYPE)
@ApiOperation(
value = "Returns current metrics for a specific project",
response = ProjectMetrics.class
)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Badge support is disabled. No content will be returned."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The project could not be found")
})
@AuthenticationNotRequired
public Response getProjectVulnerabilitiesBadge(
@ApiParam(value = "The UUID of the project to retrieve metrics for", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateVulnerabilities(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
} else {
return Response.status(Response.Status.NO_CONTENT).build();
}
}
}
@GET
@Path("/vulns/project/{name}/{version}")
@Produces(SVG_MEDIA_TYPE)
@ApiOperation(
value = "Returns current metrics for a specific project",
response = ProjectMetrics.class
)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Badge support is disabled. No content will be returned."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The project could not be found")
})
@AuthenticationNotRequired
public Response getProjectVulnerabilitiesBadge(
@ApiParam(value = "The name of the project to query on", required = true)
@PathParam("name") String name,
@ApiParam(value = "The version of the project to query on", required = true)
@PathParam("version") String version) {
try (QueryManager qm = new QueryManager()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getProject(name, version);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateVulnerabilities(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
} else {
return Response.status(Response.Status.NO_CONTENT).build();
}
}
}
@GET
@Path("/violations/project/{uuid}")
@Produces(SVG_MEDIA_TYPE)
@ApiOperation(
value = "Returns a policy violations badge for a specific project",
response = String.class
)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Badge support is disabled. No content will be returned."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The project could not be found")
})
@AuthenticationNotRequired
public Response getProjectPolicyViolationsBadge(
@ApiParam(value = "The UUID of the project to retrieve a badge for", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateViolations(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
} else {
return Response.status(Response.Status.NO_CONTENT).build();
}
}
}
@GET
@Path("/violations/project/{name}/{version}")
@Produces(SVG_MEDIA_TYPE)
@ApiOperation(
value = "Returns a policy violations badge for a specific project",
response = String.class
)
@ApiResponses(value = {
@ApiResponse(code = 204, message = "Badge support is disabled. No content will be returned."),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The project could not be found")
})
@AuthenticationNotRequired
public Response getProjectPolicyViolationsBadge(
@ApiParam(value = "The name of the project to query on", required = true)
@PathParam("name") String name,
@ApiParam(value = "The version of the project to query on", required = true)
@PathParam("version") String version) {<FILL_FUNCTION_BODY>}
}
|
try (QueryManager qm = new QueryManager()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getProject(name, version);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateViolations(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
} else {
return Response.status(Response.Status.NO_CONTENT).build();
}
}
| 1,560
| 172
| 1,732
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/CalculatorResource.java
|
CalculatorResource
|
getOwaspRRScores
|
class CalculatorResource extends AlpineResource {
@GET
@Path("/cvss")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns the CVSS base score, impact sub-score and exploitability sub-score",
response = Score.class
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
public Response getCvssScores(
@ApiParam(value = "A valid CVSSv2 or CVSSv3 vector", required = true)
@QueryParam("vector") String vector) {
try {
final Cvss cvss = Cvss.fromVector(vector);
final Score score = cvss.calculateScore();
return Response.ok(score).build();
} catch (NullPointerException e) {
final String invalidVector = "An invalid CVSSv2 or CVSSv3 vector submitted.";
return Response.status(Response.Status.BAD_REQUEST).entity(invalidVector).build();
}
}
@GET
@Path("/owasp")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns the OWASP Risk Rating likelihood score, technical impact score and business impact score",
response = us.springett.owasp.riskrating.Score.class
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
public Response getOwaspRRScores(
@ApiParam(value = "A valid OWASP Risk Rating vector", required = true)
@QueryParam("vector") String vector) {<FILL_FUNCTION_BODY>}
}
|
try {
final OwaspRiskRating owaspRiskRating = OwaspRiskRating.fromVector(vector);
final us.springett.owasp.riskrating.Score score = owaspRiskRating.calculateScore();
return Response.ok(score).build();
} catch (IllegalArgumentException | MissingFactorException e) {
return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).build();
}
| 454
| 123
| 577
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/ComponentPropertyResource.java
|
ComponentPropertyResource
|
getProperties
|
class ComponentPropertyResource extends AbstractConfigPropertyResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all ComponentProperties for the specified component",
response = ComponentProperty.class,
responseContainer = "List",
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Access to the specified project is forbidden"),
@ApiResponse(code = 404, message = "The project could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getProperties(
@ApiParam(value = "The UUID of the component to retrieve properties for", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid) {<FILL_FUNCTION_BODY>}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Creates a new component property",
response = ComponentProperty.class,
code = 201,
notes = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Access to the specified component is forbidden"),
@ApiResponse(code = 404, message = "The component could not be found"),
@ApiResponse(code = 409, message = "A property with the specified component/group/name combination already exists")
})
@PermissionRequired(Permissions.Constants.PORTFOLIO_MANAGEMENT)
public Response createProperty(
@ApiParam(value = "The UUID of the component to create a property for", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid,
ComponentProperty json) {
final Validator validator = super.getValidator();
failOnValidationError(
validator.validateProperty(json, "groupName"),
validator.validateProperty(json, "propertyName"),
validator.validateProperty(json, "propertyValue"),
validator.validateProperty(json, "propertyType")
);
try (QueryManager qm = new QueryManager()) {
final Component component = qm.getObjectByUuid(Component.class, uuid);
if (component != null) {
if (qm.hasAccess(super.getPrincipal(), component.getProject())) {
final List<ComponentProperty> existingProperties = qm.getComponentProperties(component,
StringUtils.trimToNull(json.getGroupName()), StringUtils.trimToNull(json.getPropertyName()));
final var jsonPropertyIdentity = new ComponentProperty.Identity(json);
final boolean isDuplicate = existingProperties.stream()
.map(ComponentProperty.Identity::new)
.anyMatch(jsonPropertyIdentity::equals);
if (existingProperties.isEmpty() || !isDuplicate) {
final ComponentProperty property = qm.createComponentProperty(component,
StringUtils.trimToNull(json.getGroupName()),
StringUtils.trimToNull(json.getPropertyName()),
null, // Set value to null - this will be taken care of by updatePropertyValue below
json.getPropertyType(),
StringUtils.trimToNull(json.getDescription()));
updatePropertyValue(qm, json, property);
return Response.status(Response.Status.CREATED).entity(property).build();
} else {
return Response.status(Response.Status.CONFLICT).entity("A property with the specified component/group/name/value combination already exists.").build();
}
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified component is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
}
}
@DELETE
@Path("/{propertyUuid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Deletes a config property",
response = ComponentProperty.class,
notes = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Access to the specified component is forbidden"),
@ApiResponse(code = 404, message = "The component or component property could not be found"),
})
@PermissionRequired(Permissions.Constants.PORTFOLIO_MANAGEMENT)
public Response deleteProperty(
@ApiParam(value = "The UUID of the component to delete a property from", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid final String componentUuid,
@ApiParam(value = "The UUID of the component property to delete", format = "uuid", required = true)
@PathParam("propertyUuid") @ValidUuid final String propertyUuid) {
try (QueryManager qm = new QueryManager()) {
final Component component = qm.getObjectByUuid(Component.class, componentUuid);
if (component != null) {
if (qm.hasAccess(super.getPrincipal(), component.getProject())) {
final long propertiesDeleted = qm.deleteComponentPropertyByUuid(component, UUID.fromString(propertyUuid));
if (propertiesDeleted > 0) {
return Response.status(Response.Status.NO_CONTENT).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component property could not be found.").build();
}
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified component is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
}
}
}
|
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Component component = qm.getObjectByUuid(Component.class, uuid);
if (component != null) {
if (qm.hasAccess(super.getPrincipal(), component.getProject())) {
final List<ComponentProperty> properties = qm.getComponentProperties(component);
// Detaches the objects and closes the persistence manager so that if/when encrypted string
// values are replaced by the placeholder, they are not erroneously persisted to the database.
qm.getPersistenceManager().detachCopyAll(properties);
qm.close();
for (final ComponentProperty property : properties) {
// Replace the value of encrypted strings with the pre-defined placeholder
if (ComponentProperty.PropertyType.ENCRYPTEDSTRING == property.getPropertyType()) {
property.setPropertyValue(ENCRYPTED_PLACEHOLDER);
}
}
return Response.ok(properties).build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
}
| 1,625
| 329
| 1,954
|
<methods><variables>static final java.lang.String ENCRYPTED_PLACEHOLDER,private final Logger LOGGER
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/ConfigPropertyResource.java
|
ConfigPropertyResource
|
updateConfigProperty
|
class ConfigPropertyResource extends AbstractConfigPropertyResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all ConfigProperties for the specified groupName",
response = ConfigProperty.class,
responseContainer = "List",
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response getConfigProperties() {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final List<ConfigProperty> configProperties = qm.getConfigProperties();
// Detaches the objects and closes the persistence manager so that if/when encrypted string
// values are replaced by the placeholder, they are not erroneously persisted to the database.
qm.getPersistenceManager().detachCopyAll(configProperties);
qm.close();
for (final ConfigProperty configProperty: configProperties) {
// Replace the value of encrypted strings with the pre-defined placeholder
if (ConfigProperty.PropertyType.ENCRYPTEDSTRING == configProperty.getPropertyType()) {
configProperty.setPropertyValue(ENCRYPTED_PLACEHOLDER);
}
}
return Response.ok(configProperties).build();
}
}
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Updates a config property",
response = ConfigProperty.class,
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The config property could not be found"),
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response updateConfigProperty(ConfigProperty json) {
final Validator validator = super.getValidator();
failOnValidationError(
validator.validateProperty(json, "groupName"),
validator.validateProperty(json, "propertyName"),
validator.validateProperty(json, "propertyValue")
);
try (QueryManager qm = new QueryManager()) {
final ConfigProperty property = qm.getConfigProperty(json.getGroupName(), json.getPropertyName());
return updatePropertyValue(qm, json, property);
}
}
@POST
@Path("aggregate")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Updates an array of config properties",
response = ConfigProperty.class,
responseContainer = "List",
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "One or more config properties could not be found"),
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response updateConfigProperty(List<ConfigProperty> list) {<FILL_FUNCTION_BODY>}
}
|
final Validator validator = super.getValidator();
for (ConfigProperty item: list) {
failOnValidationError(
validator.validateProperty(item, "groupName"),
validator.validateProperty(item, "propertyName"),
validator.validateProperty(item, "propertyValue")
);
}
List<Object> returnList = new ArrayList<>();
try (QueryManager qm = new QueryManager()) {
for (ConfigProperty item : list) {
final ConfigProperty property = qm.getConfigProperty(item.getGroupName(), item.getPropertyName());
returnList.add(updatePropertyValue(qm, item, property).getEntity());
}
}
return Response.ok(returnList).build();
| 891
| 184
| 1,075
|
<methods><variables>static final java.lang.String ENCRYPTED_PLACEHOLDER,private final Logger LOGGER
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/CweResource.java
|
CweResource
|
getCwe
|
class CweResource extends AlpineResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all CWEs",
response = Cwe.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of CWEs")
)
@PaginatedApi
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
public Response getCwes() {
final PaginatedResult cwes = CweResolver.getInstance().all(getAlpineRequest().getPagination());
return Response.ok(cwes.getObjects()).header(TOTAL_COUNT_HEADER, cwes.getTotal()).build();
}
@GET
@Path("/{cweId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a specific CWE",
response = Cwe.class
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The CWE could not be found")
})
public Response getCwe(
@ApiParam(value = "The CWE ID of the CWE to retrieve", required = true)
@PathParam("cweId") int cweId) {<FILL_FUNCTION_BODY>}
}
|
final Cwe cwe = CweResolver.getInstance().lookup(cweId);
if (cwe != null) {
return Response.ok(cwe).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The CWE could not be found.").build();
}
| 403
| 84
| 487
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/EventResource.java
|
EventResource
|
isTokenBeingProcessed
|
class EventResource extends AlpineResource {
@GET
@Path("/token/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Determines if there are any tasks associated with the token that are being processed, or in the queue to be processed.",
response = IsTokenBeingProcessedResponse.class,
notes = """
<p>
This endpoint is intended to be used in conjunction with other API calls which return a token for asynchronous tasks.
The token can then be queried using this endpoint to determine if the task is complete:
<ul>
<li>A value of <code>true</code> indicates processing is occurring.</li>
<li>A value of <code>false</code> indicates that no processing is occurring for the specified token.</li>
</ul>
However, a value of <code>false</code> also does not confirm the token is valid,
only that no processing is associated with the specified token.
</p>"""
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
public Response isTokenBeingProcessed (
@ApiParam(value = "The UUID of the token to query", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid) {<FILL_FUNCTION_BODY>}
}
|
final boolean value = Event.isEventBeingProcessed(UUID.fromString(uuid));
IsTokenBeingProcessedResponse response = new IsTokenBeingProcessedResponse();
response.setProcessing(value);
return Response.ok(response).build();
| 352
| 63
| 415
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/IntegrationResource.java
|
IntegrationResource
|
getAllEcosystems
|
class IntegrationResource extends AlpineResource {
@GET
@Path("/osv/ecosystem")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all ecosystems in OSV",
response = String.class,
responseContainer = "List",
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response getAllEcosystems() {<FILL_FUNCTION_BODY>}
@GET
@Path("/osv/ecosystem/inactive")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of available inactive ecosystems in OSV to be selected by user",
response = String.class,
responseContainer = "List",
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response getInactiveEcosystems() {
OsvDownloadTask osvDownloadTask = new OsvDownloadTask();
var selectedEcosystems = osvDownloadTask.getEnabledEcosystems();
final List<String> ecosystems = osvDownloadTask.getEcosystems().stream()
.filter(element -> !selectedEcosystems.contains(element))
.collect(Collectors.toList());
return Response.ok(ecosystems).build();
}
}
|
OsvDownloadTask osvDownloadTask = new OsvDownloadTask();
final List<String> ecosystems = osvDownloadTask.getEcosystems();
return Response.ok(ecosystems).build();
| 466
| 54
| 520
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/LdapResource.java
|
LdapResource
|
retrieveLdapGroups
|
class LdapResource extends AlpineResource {
private static final Logger LOGGER = Logger.getLogger(LdapResource.class);
@GET
@Path("/groups")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns the DNs of all accessible groups within the directory",
response = String.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of ldap groups that match the specified search criteria"),
notes = """
<p>
This API performs a pass-through query to the configured LDAP server.
Search criteria results are cached using default Alpine CacheManager policy.
<p>
<p>Requires permission <strong>ACCESS_MANAGEMENT</strong></p>"""
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response retrieveLdapGroups () {<FILL_FUNCTION_BODY>}
@GET
@Path("/team/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns the DNs of all groups mapped to the specified team",
response = String.class,
responseContainer = "List",
notes = "<p>Requires permission <strong>ACCESS_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the team could not be found"),
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response retrieveLdapGroups (@ApiParam(value = "The UUID of the team to retrieve mappings for", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager()) {
final Team team = qm.getObjectByUuid(Team.class, uuid);
if (team != null) {
final List<MappedLdapGroup> mappings = qm.getMappedLdapGroups(team);
return Response.ok(mappings).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the team could not be found.").build();
}
}
}
@PUT
@Path("/mapping")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Adds a mapping",
response = MappedLdapGroup.class,
notes = "<p>Requires permission <strong>ACCESS_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the team could not be found"),
@ApiResponse(code = 409, message = "A mapping with the same team and dn already exists")
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response addMapping(MappedLdapGroupRequest request) {
final Validator validator = super.getValidator();
failOnValidationError(
validator.validateProperty(request, "team"),
validator.validateProperty(request, "dn")
);
try (QueryManager qm = new QueryManager()) {
final Team team = qm.getObjectByUuid(Team.class, request.getTeam());
if (team != null) {
if (!qm.isMapped(team, request.getDn())) {
final MappedLdapGroup mapping = qm.createMappedLdapGroup(team, request.getDn());
return Response.ok(mapping).build();
} else {
return Response.status(Response.Status.CONFLICT).entity("A mapping with the same team and dn already exists.").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the team could not be found.").build();
}
}
}
@DELETE
@Path("/mapping/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Removes a mapping",
response = MappedLdapGroup.class,
notes = "<p>Requires permission <strong>ACCESS_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the mapping could not be found"),
})
@PermissionRequired(Permissions.Constants.ACCESS_MANAGEMENT)
public Response deleteMapping(
@ApiParam(value = "The UUID of the mapping to delete", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager()) {
final MappedLdapGroup mapping = qm.getObjectByUuid(MappedLdapGroup.class, uuid);
if (mapping != null) {
qm.delete(mapping);
return Response.status(Response.Status.NO_CONTENT).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the mapping could not be found.").build();
}
}
}
}
|
if (!LdapConnectionWrapper.LDAP_CONFIGURED) {
return Response.ok().build();
}
if (getAlpineRequest().getFilter() == null) {
return Response.status(Response.Status.NO_CONTENT).build();
}
List<String> groups = CacheManager.getInstance().get(ArrayList.class, "ldap-group-search:" + getAlpineRequest().getFilter());
if (groups == null) {
final LdapConnectionWrapper ldap = new LdapConnectionWrapper();
DirContext dirContext = null;
try {
dirContext = ldap.createDirContext();
groups = ldap.searchForGroupName(dirContext, getAlpineRequest().getFilter());
CacheManager.getInstance().put("ldap-group-search:" + getAlpineRequest().getFilter(), groups);
} catch (SizeLimitExceededException e) {
LOGGER.warn("The LDAP server did not return results from the specified search criteria as the result list would have exceeded the size limit specified by the LDAP server");
return Response.status(Response.Status.NO_CONTENT).build();
} catch (NamingException e) {
LOGGER.error("An error occurred attempting to retrieve a list of groups from the configured LDAP server", e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} finally {
ldap.closeQuietly(dirContext);
}
}
final List<String> result = groups.stream()
.skip(getAlpineRequest().getPagination().getOffset())
.limit(getAlpineRequest().getPagination().getLimit())
.collect(Collectors.toList());
return Response.ok(result).header(TOTAL_COUNT_HEADER, groups.size()).build();
| 1,463
| 458
| 1,921
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/LicenseResource.java
|
LicenseResource
|
createLicense
|
class LicenseResource extends AlpineResource {
private static final Logger LOGGER = Logger.getLogger(LicenseResource.class);
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all licenses with complete metadata for each license",
response = License.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of licenses")
)
@PaginatedApi
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
public Response getLicenses() {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final PaginatedResult result = qm.getLicenses();
return Response.ok(result.getObjects()).header(TOTAL_COUNT_HEADER, result.getTotal()).build();
}
}
@GET
@Path("/concise")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a concise listing of all licenses",
response = License.class,
responseContainer = "List"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
public Response getLicenseListing() {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final List<License> result = qm.getAllLicensesConcise();
return Response.ok(result).build();
}
}
@GET
@Path("/{licenseId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a specific license",
response = License.class
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The license could not be found")
})
public Response getLicense(
@ApiParam(value = "The SPDX License ID of the license to retrieve", required = true)
@PathParam("licenseId") String licenseId) {
try (QueryManager qm = new QueryManager()) {
final License license = qm.getLicense(licenseId);
if (license != null) {
return Response.ok(license).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The license could not be found.").build();
}
}
}
@PUT
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Creates a new custom license",
response = License.class,
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 409, message = "A license with the specified ID already exists.")
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response createLicense(License jsonLicense) {<FILL_FUNCTION_BODY>}
@DELETE
@Path("/{licenseId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Deletes a custom license",
code = 204,
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The license could not be found"),
@ApiResponse(code = 409, message = "Only custom licenses can be deleted.")
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response deleteLicense(
@ApiParam(value = "The SPDX License ID of the license to delete", required = true)
@PathParam("licenseId") String licenseId) {
try (QueryManager qm = new QueryManager()) {
final License license = qm.getLicense(licenseId);
if (license != null) {
if (Boolean.TRUE.equals(license.isCustomLicense())) {
LOGGER.info("License " + license + " deletion request by " + super.getPrincipal().getName());
qm.deleteLicense(license, true);
return Response.status(Response.Status.NO_CONTENT).build();
} else {
return Response.status(Response.Status.CONFLICT).entity("Only custom licenses can be deleted.").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The license could not be found.").build();
}
}
}
}
|
final Validator validator = super.getValidator();
failOnValidationError(
validator.validateProperty(jsonLicense, "name"),
validator.validateProperty(jsonLicense, "licenseId")
);
try (QueryManager qm = new QueryManager()) {
License license = qm.getLicense(jsonLicense.getLicenseId());
if (license == null){
license = qm.createCustomLicense(jsonLicense, true);
LOGGER.info("License " + license.getName() + " created by " + super.getPrincipal().getName());
return Response.status(Response.Status.CREATED).entity(license).build();
} else {
return Response.status(Response.Status.CONFLICT).entity("A license with the specified name already exists.").build();
}
}
| 1,273
| 200
| 1,473
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/PolicyConditionResource.java
|
PolicyConditionResource
|
createPolicyCondition
|
class PolicyConditionResource extends AlpineResource {
@PUT
@Path("/{uuid}/condition")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Creates a new policy condition",
response = PolicyCondition.class,
code = 201,
notes = "<p>Requires permission <strong>POLICY_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the policy could not be found")
})
@PermissionRequired(Permissions.Constants.POLICY_MANAGEMENT)
public Response createPolicyCondition(
@ApiParam(value = "The UUID of the policy", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid,
PolicyCondition jsonPolicyCondition) {<FILL_FUNCTION_BODY>}
@POST
@Path("/condition")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Updates a policy condition",
response = PolicyCondition.class,
notes = "<p>Requires permission <strong>POLICY_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the policy condition could not be found")
})
@PermissionRequired(Permissions.Constants.POLICY_MANAGEMENT)
public Response updatePolicyCondition(PolicyCondition jsonPolicyCondition) {
final Validator validator = super.getValidator();
failOnValidationError(
validator.validateProperty(jsonPolicyCondition, "value")
);
try (QueryManager qm = new QueryManager()) {
PolicyCondition pc = qm.getObjectByUuid(PolicyCondition.class, jsonPolicyCondition.getUuid());
if (pc != null) {
pc = qm.updatePolicyCondition(jsonPolicyCondition);
return Response.status(Response.Status.CREATED).entity(pc).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the policy condition could not be found.").build();
}
}
}
@DELETE
@Path("/condition/{uuid}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Deletes a policy condition",
code = 204,
notes = "<p>Requires permission <strong>POLICY_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The UUID of the policy condition could not be found")
})
@PermissionRequired(Permissions.Constants.POLICY_MANAGEMENT)
public Response deletePolicyCondition(
@ApiParam(value = "The UUID of the policy condition to delete", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager()) {
final PolicyCondition pc = qm.getObjectByUuid(PolicyCondition.class, uuid);
if (pc != null) {
qm.deletePolicyCondition(pc);
return Response.status(Response.Status.NO_CONTENT).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the policy condition could not be found.").build();
}
}
}
}
|
final Validator validator = super.getValidator();
failOnValidationError(
validator.validateProperty(jsonPolicyCondition, "value")
);
try (QueryManager qm = new QueryManager()) {
Policy policy = qm.getObjectByUuid(Policy.class, uuid);
if (policy != null) {
final PolicyCondition pc = qm.createPolicyCondition(policy, jsonPolicyCondition.getSubject(),
jsonPolicyCondition.getOperator(), StringUtils.trimToNull(jsonPolicyCondition.getValue()));
return Response.status(Response.Status.CREATED).entity(pc).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The UUID of the policy could not be found.").build();
}
}
| 1,003
| 193
| 1,196
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/PolicyViolationResource.java
|
PolicyViolationResource
|
getViolations
|
class PolicyViolationResource extends AlpineResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all policy violations for the entire portfolio",
response = PolicyViolation.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of policy violations"),
notes = "<p>Requires permission <strong>VIEW_POLICY_VIOLATION</strong></p>"
)
@PaginatedApi
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_POLICY_VIOLATION)
public Response getViolations(@ApiParam(value = "Optionally includes suppressed violations")
@QueryParam("suppressed") boolean suppressed) {<FILL_FUNCTION_BODY>}
@GET
@Path("/project/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all policy violations for a specific project",
response = PolicyViolation.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of policy violations"),
notes = "<p>Requires permission <strong>VIEW_POLICY_VIOLATION</strong></p>"
)
@PaginatedApi
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Access to the specified project is forbidden"),
@ApiResponse(code = 404, message = "The project could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_POLICY_VIOLATION)
public Response getViolationsByProject(@ApiParam(value = "The UUID of the project", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid,
@ApiParam(value = "Optionally includes suppressed violations")
@QueryParam("suppressed") boolean suppressed) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
if (qm.hasAccess(super.getPrincipal(), project)) {
final PaginatedResult result = qm.getPolicyViolations(project, suppressed);
return Response.ok(detachViolations(qm, result.getList(PolicyViolation.class)))
.header(TOTAL_COUNT_HEADER, result.getTotal())
.build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
@GET
@Path("/component/{uuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all policy violations for a specific component",
response = PolicyViolation.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of policy violations"),
notes = "<p>Requires permission <strong>VIEW_POLICY_VIOLATION</strong></p>"
)
@PaginatedApi
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 403, message = "Access to the specified component is forbidden"),
@ApiResponse(code = 404, message = "The component could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_POLICY_VIOLATION)
public Response getViolationsByComponent(@ApiParam(value = "The UUID of the component", format = "uuid", required = true)
@PathParam("uuid") @ValidUuid String uuid,
@ApiParam(value = "Optionally includes suppressed violations")
@QueryParam("suppressed") boolean suppressed) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Component component = qm.getObjectByUuid(Component.class, uuid);
if (component != null) {
if (qm.hasAccess(super.getPrincipal(), component.getProject())) {
final PaginatedResult result = qm.getPolicyViolations(component, suppressed);
return Response.ok(detachViolations(qm, result.getList(PolicyViolation.class)))
.header(TOTAL_COUNT_HEADER, result.getTotal())
.build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified component is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
}
}
/**
* Detach a given {@link Collection} of {@link PolicyViolation} suitable for use in API responses.
* <p>
* This ensures that responses include not only the violations themselves, but also the associated
* {@link org.dependencytrack.model.Policy}, which is required to tell the policy name and violation state.
*
* @param qm The {@link QueryManager} to use
* @param violations The {@link PolicyViolation}s to detach
* @return A detached {@link Collection} of {@link PolicyViolation}s
* @see <a href="https://github.com/DependencyTrack/dependency-track/issues/2043">GitHub issue</a>
*/
private Collection<PolicyViolation> detachViolations(final QueryManager qm, final Collection<PolicyViolation> violations) {
final PersistenceManager pm = qm.getPersistenceManager();
pm.getFetchPlan().setMaxFetchDepth(2); // Ensure policy is included
pm.getFetchPlan().setDetachmentOptions(FetchPlan.DETACH_LOAD_FIELDS);
return qm.getPersistenceManager().detachCopyAll(violations);
}
}
|
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final PaginatedResult result = qm.getPolicyViolations(suppressed);
return Response.ok(detachViolations(qm, result.getList(PolicyViolation.class)))
.header(TOTAL_COUNT_HEADER, result.getTotal())
.build();
}
| 1,688
| 99
| 1,787
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/SearchResource.java
|
SearchResource
|
aggregateSearch
|
class SearchResource extends AlpineResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Processes and returns search results",
response = SearchResult.class,
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response aggregateSearch(@QueryParam("query") String query) {<FILL_FUNCTION_BODY>}
@Path("/project")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Processes and returns search results",
response = SearchResult.class,
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response projectSearch(@QueryParam("query") String query) {
final SearchManager searchManager = new SearchManager();
final SearchResult searchResult = searchManager.searchProjectIndex(query, 1000);
return Response.ok(searchResult).build();
}
@Path("/component")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Processes and returns search results",
response = SearchResult.class,
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response componentSearch(@QueryParam("query") String query) {
final SearchManager searchManager = new SearchManager();
final SearchResult searchResult = searchManager.searchComponentIndex(query, 1000);
return Response.ok(searchResult).build();
}
@Path("/service")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Processes and returns search results",
response = SearchResult.class,
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response serviceSearch(@QueryParam("query") String query) {
final SearchManager searchManager = new SearchManager();
final SearchResult searchResult = searchManager.searchServiceComponentIndex(query, 1000);
return Response.ok(searchResult).build();
}
@Path("/license")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Processes and returns search results",
response = SearchResult.class,
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response licenseSearch(@QueryParam("query") String query) {
final SearchManager searchManager = new SearchManager();
final SearchResult searchResult = searchManager.searchLicenseIndex(query, 1000);
return Response.ok(searchResult).build();
}
@Path("/vulnerability")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Processes and returns search results",
response = SearchResult.class,
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response vulnerabilitySearch(@QueryParam("query") String query) {
final SearchManager searchManager = new SearchManager();
final SearchResult searchResult = searchManager.searchVulnerabilityIndex(query, 1000);
return Response.ok(searchResult).build();
}
@Path("/vulnerablesoftware")
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Processes and returns search results",
response = SearchResult.class,
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response vulnerableSoftwareSearch(@QueryParam("query") String query, @QueryParam("cpe") String cpe) {
if (StringUtils.isNotBlank(cpe)) {
final FuzzyVulnerableSoftwareSearchManager searchManager = new FuzzyVulnerableSoftwareSearchManager(false);
final SearchResult searchResult = searchManager.searchIndex(FuzzyVulnerableSoftwareSearchManager.getLuceneCpeRegexp(cpe));
return Response.ok(searchResult).build();
} else {
final SearchManager searchManager = new SearchManager();
final SearchResult searchResult = searchManager.searchVulnerableSoftwareIndex(query, 1000);
return Response.ok(searchResult).build();
}
}
@Path("/reindex")
@POST
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Rebuild lucene indexes for search operations",
notes = "<p>Requires permission <strong>SYSTEM_CONFIGURATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 400, message = "No valid index type was provided")
})
@PermissionRequired(Permissions.Constants.SYSTEM_CONFIGURATION)
public Response reindex(@QueryParam("type") Set<String> type) {
if (type == null || type.isEmpty()) {
return Response.status(Response.Status.BAD_REQUEST).entity("No valid index type was provided").build();
}
try {
final SearchManager searchManager = new SearchManager();
String chainIdentifier = searchManager.reindex(type);
return Response.ok(Collections.singletonMap("token", chainIdentifier)).build();
} catch (IllegalArgumentException exception) {
return Response.status(Response.Status.BAD_REQUEST).entity(exception.getMessage()).build();
}
}
}
|
final SearchManager searchManager = new SearchManager();
final SearchResult searchResult = searchManager.searchIndices(query, 1000);
return Response.ok(searchResult).build();
| 1,837
| 50
| 1,887
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/TagResource.java
|
TagResource
|
getTags
|
class TagResource extends AlpineResource {
@GET
@Path("/{policyUuid}")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Returns a list of all tags associated with a given policy",
response = Tag.class,
responseContainer = "List",
responseHeaders = @ResponseHeader(name = TOTAL_COUNT_HEADER, response = Long.class, description = "The total number of tags"),
notes = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getTags(@ApiParam(value = "The UUID of the policy", format = "uuid", required = true)
@PathParam("policyUuid") @ValidUuid String policyUuid){<FILL_FUNCTION_BODY>}
}
|
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final PaginatedResult result = qm.getTags(policyUuid);
return Response.ok(result.getObjects()).header(TOTAL_COUNT_HEADER, result.getTotal()).build();
}
| 260
| 75
| 335
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/ViolationAnalysisResource.java
|
ViolationAnalysisResource
|
updateAnalysis
|
class ViolationAnalysisResource extends AlpineResource {
@GET
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Retrieves a violation analysis trail",
response = ViolationAnalysis.class,
notes = "<p>Requires permission <strong>VIEW_POLICY_VIOLATION</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The component or policy violation could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_POLICY_VIOLATION)
public Response retrieveAnalysis(@ApiParam(value = "The UUID of the component", format = "uuid", required = true)
@QueryParam("component") @ValidUuid String componentUuid,
@ApiParam(value = "The UUID of the policy violation", format = "uuid", required = true)
@QueryParam("policyViolation") @ValidUuid String violationUuid) {
failOnValidationError(
new ValidationTask(RegexSequence.Pattern.UUID, componentUuid, "Component is not a valid UUID"),
new ValidationTask(RegexSequence.Pattern.UUID, violationUuid, "Policy violation is not a valid UUID")
);
try (QueryManager qm = new QueryManager()) {
final Component component = qm.getObjectByUuid(Component.class, componentUuid);
if (component == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
final PolicyViolation policyViolation = qm.getObjectByUuid(PolicyViolation.class, violationUuid);
if (policyViolation == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The policy violation could not be found.").build();
}
final ViolationAnalysis analysis = qm.getViolationAnalysis(component, policyViolation);
return Response.ok(analysis).build();
}
}
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Records a violation analysis decision",
response = ViolationAnalysis.class,
notes = "<p>Requires permission <strong>POLICY_VIOLATION_ANALYSIS</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 404, message = "The component or policy violation could not be found")
})
@PermissionRequired(Permissions.Constants.POLICY_VIOLATION_ANALYSIS)
public Response updateAnalysis(ViolationAnalysisRequest request) {<FILL_FUNCTION_BODY>}
}
|
final Validator validator = getValidator();
failOnValidationError(
validator.validateProperty(request, "component"),
validator.validateProperty(request, "policyViolation"),
validator.validateProperty(request, "analysisState"),
validator.validateProperty(request, "comment")
);
try (QueryManager qm = new QueryManager()) {
final Component component = qm.getObjectByUuid(Component.class, request.getComponent());
if (component == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
final PolicyViolation violation = qm.getObjectByUuid(PolicyViolation.class, request.getPolicyViolation());
if (violation == null) {
return Response.status(Response.Status.NOT_FOUND).entity("The policy violation could not be found.").build();
}
String commenter = null;
if (getPrincipal() instanceof LdapUser || getPrincipal() instanceof ManagedUser || getPrincipal() instanceof OidcUser) {
commenter = ((UserPrincipal) getPrincipal()).getUsername();
}
boolean analysisStateChange = false;
boolean suppressionChange = false;
ViolationAnalysis analysis = qm.getViolationAnalysis(component, violation);
if (analysis != null) {
if (request.getAnalysisState() != null && analysis.getAnalysisState() != request.getAnalysisState()) {
analysisStateChange = true;
qm.makeViolationAnalysisComment(analysis, String.format("%s → %s", analysis.getAnalysisState(), request.getAnalysisState()), commenter);
}
if (request.isSuppressed() != null && analysis.isSuppressed() != request.isSuppressed()) {
suppressionChange = true;
final String message = (request.isSuppressed()) ? "Suppressed" : "Unsuppressed";
qm.makeViolationAnalysisComment(analysis, message, commenter);
}
analysis = qm.makeViolationAnalysis(component, violation, request.getAnalysisState(), request.isSuppressed());
} else {
analysis = qm.makeViolationAnalysis(component, violation, request.getAnalysisState(), request.isSuppressed());
analysisStateChange = true; // this is a new analysis - so set to true because it was previously null
if (ViolationAnalysisState.NOT_SET != request.getAnalysisState()) {
qm.makeViolationAnalysisComment(analysis, String.format("%s → %s", ViolationAnalysisState.NOT_SET, request.getAnalysisState()), commenter);
}
}
final String comment = StringUtils.trimToNull(request.getComment());
qm.makeViolationAnalysisComment(analysis, comment, commenter);
analysis = qm.getObjectById(ViolationAnalysis.class, analysis.getId());
NotificationUtil.analyzeNotificationCriteria(qm, analysis, analysisStateChange, suppressionChange);
return Response.ok(analysis).build();
}
| 746
| 766
| 1,512
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/exception/ConstraintViolationExceptionMapper.java
|
ConstraintViolationExceptionMapper
|
mapToValidationErrors
|
class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
@Override
public Response toResponse(final ConstraintViolationException exception) {
final List<ValidationError> errors = mapToValidationErrors(exception.getConstraintViolations());
return Response
.status(Response.Status.BAD_REQUEST)
.entity(errors)
.build();
}
/**
* Copied from {@link AlpineResource#contOnValidationError(Set[])}.
*
* @param violations A {@link Collection} or one or more {@link ConstraintViolation}s
* @return A {@link List} of zero or more {@link ValidationError}s
* @see <a href="https://github.com/stevespringett/Alpine/blob/76f5bfd6b2d9469e8a42ba360b3b3feef7a87a8b/alpine-server/src/main/java/alpine/server/resources/AlpineResource.java#L155-L190">Source</a>
*/
private static List<ValidationError> mapToValidationErrors(final Collection<ConstraintViolation<?>> violations) {<FILL_FUNCTION_BODY>}
}
|
final List<ValidationError> errors = new ArrayList<>(violations.size());
for (final ConstraintViolation<?> violation : violations) {
if (violation.getPropertyPath().iterator().next().getName() != null) {
final String path = violation.getPropertyPath() != null ? violation.getPropertyPath().toString() : null;
final String message = violation.getMessage() != null ? StringUtils.removeStart(violation.getMessage(), path + ".") : null;
final String messageTemplate = violation.getMessageTemplate();
final String invalidValue = violation.getInvalidValue() != null ? violation.getInvalidValue().toString() : null;
final ValidationError error = new ValidationError(message, messageTemplate, path, invalidValue);
errors.add(error);
}
}
return errors;
| 327
| 207
| 534
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/exception/JsonMappingExceptionMapper.java
|
JsonMappingExceptionMapper
|
createDetail
|
class JsonMappingExceptionMapper implements ExceptionMapper<JsonMappingException> {
@Override
public Response toResponse(final JsonMappingException exception) {
final var problemDetails = new ProblemDetails();
problemDetails.setStatus(400);
problemDetails.setTitle("The provided JSON payload could not be mapped");
problemDetails.setDetail(createDetail(exception));
return Response
.status(Response.Status.BAD_REQUEST)
.type(ProblemDetails.MEDIA_TYPE_JSON)
.entity(problemDetails)
.build();
}
private static String createDetail(final JsonMappingException exception) {<FILL_FUNCTION_BODY>}
}
|
if (!(exception.getCause() instanceof StreamConstraintsException)) {
return exception.getMessage();
}
final JsonMappingException.Reference reference = exception.getPath().get(0);
if (Objects.equals(reference.getFrom(), BomSubmitRequest.class)
&& "bom".equals(reference.getFieldName())) {
return """
The BOM is too large to be transmitted safely via Base64 encoded JSON value. \
Please use the "POST /api/v1/bom" endpoint with Content-Type "multipart/form-data" instead. \
Original cause: %s""".formatted(exception.getMessage());
} else if (Objects.equals(reference.getFrom(), VexSubmitRequest.class)
&& "vex".equals(reference.getFieldName())) {
return """
The VEX is too large to be transmitted safely via Base64 encoded JSON value. \
Please use the "POST /api/v1/vex" endpoint with Content-Type "multipart/form-data" instead. \
Original cause: %s""".formatted(exception.getMessage());
}
return exception.getMessage();
| 170
| 282
| 452
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/misc/Badger.java
|
Badger
|
generateViolations
|
class Badger {
private static final PebbleEngine ENGINE = new PebbleEngine.Builder().newLineTrimming(false).build();
private static final PebbleTemplate PROJECT_VULNS_TEMPLATE = ENGINE.getTemplate("templates/badge/project-vulns.peb");
private static final PebbleTemplate PROJECT_VULNS_NONE_TEMPLATE = ENGINE.getTemplate("templates/badge/project-vulns-none.peb");
private static final PebbleTemplate PROJECT_VULNS_NO_METRICS_TEMPLATE = ENGINE.getTemplate("templates/badge/project-vulns-nometrics.peb");
private static final PebbleTemplate PROJECT_VIOLATIONS_TEMPLATE = ENGINE.getTemplate("templates/badge/project-violations.peb");
private static final PebbleTemplate PROJECT_VIOLATIONS_NONE_TEMPLATE = ENGINE.getTemplate("templates/badge/project-violations-none.peb");
private static final PebbleTemplate PROJECT_VIOLATIONS_NO_METRICS_TEMPLATE = ENGINE.getTemplate("templates/badge/project-violations-nometrics.peb");
public String generateVulnerabilities(ProjectMetrics metrics) {
final Map<String, Object> context = new HashMap<>();
context.put("roundedPixels", "3");
if (metrics == null) {
return writeSvg(PROJECT_VULNS_NO_METRICS_TEMPLATE, context);
} else if (metrics.getVulnerabilities() > 0) {
context.put("critical", String.valueOf(metrics.getCritical()));
context.put("high", String.valueOf(metrics.getHigh()));
context.put("medium", String.valueOf(metrics.getMedium()));
context.put("low", String.valueOf(metrics.getLow()));
context.put("unassigned", String.valueOf(metrics.getUnassigned()));
return writeSvg(PROJECT_VULNS_TEMPLATE, context);
} else {
return writeSvg(PROJECT_VULNS_NONE_TEMPLATE, context);
}
}
public String generateViolations(ProjectMetrics metrics) {<FILL_FUNCTION_BODY>}
private String writeSvg(PebbleTemplate template, Map<String, Object> context) {
try (Writer writer = new StringWriter()) {
template.evaluate(writer, context);
return writer.toString();
} catch (IOException e) {
Logger.getLogger(this.getClass()).error("An error was encountered evaluating template", e);
return null;
}
}
}
|
final Map<String, Object> context = new HashMap<>();
context.put("roundedPixels", "3");
if (metrics == null) {
return writeSvg(PROJECT_VIOLATIONS_NO_METRICS_TEMPLATE, context);
} else if (metrics.getPolicyViolationsTotal() > 0) {
context.put("fail", String.valueOf(metrics.getPolicyViolationsFail()));
context.put("warn", String.valueOf(metrics.getPolicyViolationsWarn()));
context.put("info", String.valueOf(metrics.getPolicyViolationsInfo()));
return writeSvg(PROJECT_VIOLATIONS_TEMPLATE, context);
} else {
return writeSvg(PROJECT_VIOLATIONS_NONE_TEMPLATE, context);
}
| 720
| 218
| 938
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/serializers/CweDeserializer.java
|
CweDeserializer
|
deserialize
|
class CweDeserializer extends JsonDeserializer<List<Integer>> {
@Override
public List<Integer> deserialize(JsonParser jsonParser, DeserializationContext ctx) throws IOException {<FILL_FUNCTION_BODY>}
}
|
if (jsonParser.getCurrentToken() == JsonToken.START_ARRAY) {
final List<Integer> cweIds = new ArrayList<>();
while(jsonParser.nextToken() != JsonToken.END_ARRAY) {
if (jsonParser.getCurrentToken() == JsonToken.START_OBJECT) {
final Cwe cwe = jsonParser.readValueAs(Cwe.class);
if (cwe.getCweId() > 0) {
cweIds.add(cwe.getCweId());
}
}
}
return cweIds;
}
return null;
| 62
| 157
| 219
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/serializers/CweSerializer.java
|
CweSerializer
|
serialize
|
class CweSerializer extends JsonSerializer<List<Integer>> {
@Override
public void serialize(List<Integer> cweIds, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {<FILL_FUNCTION_BODY>}
}
|
jsonGenerator.writeStartArray();
for (final Integer cweId: cweIds) {
final Cwe cwe = CweResolver.getInstance().lookup(cweId);
if (cwe != null) {
jsonGenerator.writeObject(cwe);
}
}
jsonGenerator.writeEndArray();
| 70
| 86
| 156
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/vo/AnalysisRequest.java
|
AnalysisRequest
|
getAnalysisJustification
|
class AnalysisRequest {
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", message = "The project must be a valid 36 character UUID")
private final String project;
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", message = "The component must be a valid 36 character UUID")
private final String component;
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", message = "The vulnerability must be a valid 36 character UUID")
private final String vulnerability;
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS_PLUS, message = "The comment may only contain printable characters")
private final String comment;
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS_PLUS, message = "The comment may only contain printable characters")
private final String analysisDetails;
private final AnalysisState analysisState;
private final AnalysisJustification analysisJustification;
private final AnalysisResponse analysisResponse;
private final Boolean suppressed; // Optional. If not specified, we do not want to set value to false, thus using Boolean object rather than primitive.
@JsonCreator
public AnalysisRequest(@JsonProperty(value = "project") String project,
@JsonProperty(value = "component", required = true) String component,
@JsonProperty(value = "vulnerability", required = true) String vulnerability,
@JsonProperty(value = "analysisState") AnalysisState analysisState,
@JsonProperty(value = "analysisJustification") AnalysisJustification analysisJustification,
@JsonProperty(value = "analysisResponse") AnalysisResponse analysisResponse,
@JsonProperty(value = "analysisDetails") String analysisDetails,
@JsonProperty(value = "comment") String comment,
@JsonProperty(value = "isSuppressed") Boolean suppressed) {
this.project = project;
this.component = component;
this.vulnerability = vulnerability;
this.analysisState = analysisState;
this.analysisJustification = analysisJustification;
this.analysisResponse = analysisResponse;
this.analysisDetails = analysisDetails;
this.comment = comment;
this.suppressed = suppressed;
}
public String getProject() {
return project;
}
public String getComponent() {
return component;
}
public String getVulnerability() {
return vulnerability;
}
public AnalysisState getAnalysisState() {
if (analysisState == null) {
return AnalysisState.NOT_SET;
} else {
return analysisState;
}
}
public AnalysisJustification getAnalysisJustification() {<FILL_FUNCTION_BODY>}
public AnalysisResponse getAnalysisResponse() {
if (analysisResponse == null) {
return AnalysisResponse.NOT_SET;
} else {
return analysisResponse;
}
}
public String getAnalysisDetails() {
return analysisDetails;
}
public String getComment() {
return comment;
}
public Boolean isSuppressed() {
return suppressed;
}
}
|
if (analysisJustification == null) {
return AnalysisJustification.NOT_SET;
} else {
return analysisJustification;
}
| 954
| 40
| 994
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/resources/v1/vo/ViolationAnalysisRequest.java
|
ViolationAnalysisRequest
|
getAnalysisState
|
class ViolationAnalysisRequest {
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", message = "The component must be a valid 36 character UUID")
private final String component;
@NotNull
@Pattern(regexp = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", message = "The policy violation must be a valid 36 character UUID")
private final String policyViolation;
@JsonDeserialize(using = TrimmedStringDeserializer.class)
@Pattern(regexp = RegexSequence.Definition.PRINTABLE_CHARS_PLUS, message = "The comment may only contain printable characters")
private final String comment;
private final ViolationAnalysisState analysisState;
private final Boolean suppressed; // Optional. If not specified, we do not want to set value to false, thus using Boolean object rather than primitive.
@JsonCreator
public ViolationAnalysisRequest(@JsonProperty(value = "component", required = true) String component,
@JsonProperty(value = "policyViolation", required = true) String policyViolation,
@JsonProperty(value = "analysisState") ViolationAnalysisState analysisState,
@JsonProperty(value = "comment") String comment,
@JsonProperty(value = "isSuppressed") Boolean suppressed) {
this.component = component;
this.policyViolation = policyViolation;
this.analysisState = analysisState;
this.comment = comment;
this.suppressed = suppressed;
}
public String getComponent() {
return component;
}
public String getPolicyViolation() {
return policyViolation;
}
public ViolationAnalysisState getAnalysisState() {<FILL_FUNCTION_BODY>}
public String getComment() {
return comment;
}
public Boolean isSuppressed() {
return suppressed;
}
}
|
if (analysisState == null) {
return ViolationAnalysisState.NOT_SET;
} else {
return analysisState;
}
| 563
| 40
| 603
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/ComponentIndexer.java
|
ComponentIndexer
|
reindex
|
class ComponentIndexer extends IndexManager implements ObjectIndexer<ComponentDocument> {
private static final Logger LOGGER = Logger.getLogger(ComponentIndexer.class);
private static final ComponentIndexer INSTANCE = new ComponentIndexer();
static ComponentIndexer getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private ComponentIndexer() {
super(IndexType.COMPONENT);
}
@Override
public String[] getSearchFields() {
return IndexConstants.COMPONENT_SEARCH_FIELDS;
}
/**
* Adds a Component object to a Lucene index.
*
* @param component A persisted Component object.
*/
public void add(final ComponentDocument component) {
final Document doc = convertToDocument(component);
addDocument(doc);
}
@Override
public void update(ComponentDocument component) {
final Term term = convertToTerm(component);
final Document doc = convertToDocument(component);
updateDocument(term, doc);
}
/**
* Deletes a Component object from the Lucene index.
*
* @param component A persisted Component object.
*/
public void remove(final ComponentDocument component) {
final Term term = convertToTerm(component);
deleteDocuments(term);
}
/**
* Re-indexes all Component objects.
* @since 3.4.0
*/
public void reindex() {<FILL_FUNCTION_BODY>}
private static List<ComponentDocument> fetchNext(final QueryManager qm, final Long lastId) {
final Query<Component> query = qm.getPersistenceManager().newQuery(Component.class);
var filterParts = new ArrayList<String>();
var params = new HashMap<String, Object>();
filterParts.add("(project.active == null || project.active)");
if (lastId != null) {
filterParts.add("id > :lastId");
params.put("lastId", lastId);
}
query.setFilter(String.join(" && ", filterParts));
query.setNamedParameters(params);
query.setOrdering("id ASC");
query.setRange(0, 1000);
query.setResult("id, uuid, \"group\", name, version, description, sha1");
try {
return List.copyOf(query.executeResultList(ComponentDocument.class));
} finally {
query.closeAll();
}
}
private Document convertToDocument(final ComponentDocument component) {
final var doc = new Document();
addField(doc, IndexConstants.COMPONENT_UUID, component.uuid().toString(), Field.Store.YES, false);
addField(doc, IndexConstants.COMPONENT_NAME, component.name(), Field.Store.YES, true);
addField(doc, IndexConstants.COMPONENT_GROUP, component.group(), Field.Store.YES, true);
addField(doc, IndexConstants.COMPONENT_VERSION, component.version(), Field.Store.YES, false);
addField(doc, IndexConstants.COMPONENT_SHA1, component.sha1(), Field.Store.YES, true);
addField(doc, IndexConstants.COMPONENT_DESCRIPTION, component.description(), Field.Store.YES, true);
return doc;
}
private static Term convertToTerm(final ComponentDocument component) {
return new Term(IndexConstants.COMPONENT_UUID, component.uuid().toString());
}
}
|
LOGGER.info("Starting reindex task. This may take some time.");
super.reindex();
long docsIndexed = 0;
final long startTimeNs = System.nanoTime();
try (final QueryManager qm = new QueryManager()) {
List<ComponentDocument> docs = fetchNext(qm, null);
while (!docs.isEmpty()) {
docs.forEach(this::add);
docsIndexed += docs.size();
commit();
docs = fetchNext(qm, docs.get(docs.size() - 1).id());
}
}
LOGGER.info("Reindexing of %d components completed in %s"
.formatted(docsIndexed, Duration.ofNanos(System.nanoTime() - startTimeNs)));
| 900
| 206
| 1,106
|
<methods>public void addDocument(Document) ,public static void checkIndexesConsistency() ,public void close() ,public void commit() ,public static void delete(org.dependencytrack.search.IndexManager.IndexType) ,public void deleteDocuments(Term) ,public static void ensureIndexesExists() ,public org.dependencytrack.search.IndexManager.IndexType getIndexType() ,public java.lang.String[] getSearchFields() ,public void reindex() ,public void updateDocument(Term, Document) <variables>private static final Logger LOGGER,private final non-sealed Counter addOperationCounter,private final non-sealed Counter commitOperationCounter,private final non-sealed Counter deleteOperationCounter,private Gauge docsRamTotalGauge,private final non-sealed Tag indexTag,private final non-sealed org.dependencytrack.search.IndexManager.IndexType indexType,private IndexWriter iwriter,private final non-sealed Logger logger,private Gauge numDocsGauge,private Gauge ramBytesUsedGauge,private DirectoryReader searchReader,private final non-sealed Counter updateOperationCounter
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/FuzzyVulnerableSoftwareSearchManager.java
|
SearchTerm
|
fuzzyAnalysis
|
class SearchTerm {
private String product;
private String vendor;
public SearchTerm(String vendor,String product) {
this.product = product;
this.vendor = StringUtils.isBlank(vendor) ? "*" : vendor;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SearchTerm that = (SearchTerm) o;
return product.equals(that.product) && Objects.equals(vendor, that.vendor);
}
public String getVendor() {
return vendor;
}
public String getProduct() {
return product;
}
@Override
public int hashCode() {
return Objects.hash(product, vendor);
}
}
public List<VulnerableSoftware> fuzzyAnalysis(QueryManager qm, final Component component, us.springett.parsers.cpe.Cpe parsedCpe) {<FILL_FUNCTION_BODY>
|
List<VulnerableSoftware> fuzzyList = Collections.emptyList();
if (component.getPurl() == null || !excludeComponentsWithPurl || "deb".equals(component.getPurl().getType())) {
Set<SearchTerm> searches = new LinkedHashSet<>();
try {
boolean attemptLuceneFuzzing = true;
Part part = Part.ANY;
String nameToFuzz = component.getName();
if (parsedCpe != null) {
part = parsedCpe.getPart();
searches.add(new SearchTerm(parsedCpe.getVendor(), parsedCpe.getProduct()));
nameToFuzz = parsedCpe.getProduct();
}
if (component.getPurl() != null) {
if (component.getPurl().getType().equals("golang")) {
searches.add(new SearchTerm(StringUtils.substringAfterLast(component.getPurl().getNamespace(), "/"), component.getPurl().getName()));
} else {
searches.add(new SearchTerm(component.getPurl().getNamespace(), component.getPurl().getName()));
if (component.getName().equals(nameToFuzz)) {
nameToFuzz = component.getPurl().getName();
}
}
attemptLuceneFuzzing = !SKIP_LUCENE_FUZZING_FOR_TYPE.contains(component.getPurl().getType());
}
searches.add(new SearchTerm(component.getGroup(), component.getName()));
for (SearchTerm search : searches) {
fuzzyList = fuzzySearch(qm, part, search.getVendor(), search.getProduct());
if (fuzzyList.isEmpty() && !"*".equals(search.getVendor())) {
fuzzyList = fuzzySearch(qm, part, "*", search.getProduct());
}
if (!fuzzyList.isEmpty()) {
break;
}
}
// If no luck, get fuzzier but not with small values as fuzzy 2 chars are easy to match
if (fuzzyList.isEmpty() && nameToFuzz.length() > 2 && attemptLuceneFuzzing && !DO_NOT_FUZZ.contains(nameToFuzz)) {
us.springett.parsers.cpe.Cpe justThePart = new us.springett.parsers.cpe.Cpe(part, "*", "*", "*", "*", "*", "*", "*", "*", "*", "*");
// wildcard all components after part to constrain fuzzing to components of same type e.g. application, operating-system
String fuzzyTerm = getLuceneCpeRegexp(justThePart.toCpe23FS());
LOGGER.debug(null, "Performing lucene ~ fuzz matching on '{}'", nameToFuzz);
//The tilde makes it fuzzy. e.g. Will match libexpat1 to libexpat and product exact matches with vendor mismatch
fuzzyList = fuzzySearch(qm, "product:" + nameToFuzz + "~0.88 AND " + fuzzyTerm);
}
} catch (CpeValidationException cve) {
LOGGER.error("Failed to validate fuzz search CPE", cve);
}
}
return fuzzyList;
| 271
| 846
| 1,117
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/IndexManagerFactory.java
|
IndexManagerFactory
|
getIndexManager
|
class IndexManagerFactory {
public static ObjectIndexer<? extends SearchDocument> getIndexManager(final IndexEvent event) {
if (Config.isUnitTestsEnabled()) {
return new ObjectIndexer<DummyDocument>() {
@Override
public String[] getSearchFields() { return new String[0]; }
@Override
public void add(final DummyDocument object) { }
@Override
public void update(final DummyDocument object) { }
@Override
public void remove(final DummyDocument object) { }
@Override
public void commit() { }
@Override
public void reindex() { }
};
}
if (event.getDocument() instanceof ProjectDocument || Project.class == event.getIndexableClass()) {
return ProjectIndexer.getInstance();
} else if (event.getDocument() instanceof ComponentDocument || Component.class == event.getIndexableClass()) {
return ComponentIndexer.getInstance();
} else if (event.getDocument() instanceof ServiceComponentDocument || ServiceComponent.class == event.getIndexableClass()) {
return ServiceComponentIndexer.getInstance();
} else if (event.getDocument() instanceof VulnerabilityDocument || Vulnerability.class == event.getIndexableClass()) {
return VulnerabilityIndexer.getInstance();
} else if (event.getDocument() instanceof LicenseDocument || License.class == event.getIndexableClass()) {
return LicenseIndexer.getInstance();
} else if (event.getDocument() instanceof VulnerableSoftwareDocument || VulnerableSoftware.class == event.getIndexableClass()) {
return VulnerableSoftwareIndexer.getInstance();
}
throw new IllegalArgumentException("Unsupported indexer requested");
}
public static IndexManager getIndexManager(final Class<?> clazz) {<FILL_FUNCTION_BODY>}
}
|
if (Project.class == clazz) {
return ProjectIndexer.getInstance();
} else if (Component.class == clazz) {
return ComponentIndexer.getInstance();
} else if (ServiceComponent.class == clazz) {
return ServiceComponentIndexer.getInstance();
} else if (Vulnerability.class == clazz) {
return VulnerabilityIndexer.getInstance();
} else if (License.class == clazz) {
return LicenseIndexer.getInstance();
} else if (VulnerableSoftware.class == clazz) {
return VulnerableSoftwareIndexer.getInstance();
}
throw new IllegalArgumentException("Unsupported indexer requested");
| 457
| 173
| 630
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/IndexSubsystemInitializer.java
|
IndexSubsystemInitializer
|
contextInitialized
|
class IndexSubsystemInitializer implements ServletContextListener {
private static final Logger LOGGER = Logger.getLogger(IndexSubsystemInitializer.class);
/**
* {@inheritDoc}
*/
@Override
public void contextInitialized(final ServletContextEvent event) {<FILL_FUNCTION_BODY>}
/**
* {@inheritDoc}
*/
@Override
public void contextDestroyed(final ServletContextEvent event) {
LOGGER.info("Closing search indexes");
Arrays.stream(IndexManager.IndexType.values())
.map(IndexManager.IndexType::getClazz)
.map(IndexManagerFactory::getIndexManager)
.forEach(IndexManager::close);
}
}
|
LOGGER.info("Building lucene indexes if required");
if (RequirementsVerifier.failedValidation()) {
return;
}
IndexManager.ensureIndexesExists();
| 190
| 49
| 239
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/LicenseIndexer.java
|
LicenseIndexer
|
reindex
|
class LicenseIndexer extends IndexManager implements ObjectIndexer<LicenseDocument> {
private static final Logger LOGGER = Logger.getLogger(LicenseIndexer.class);
private static final LicenseIndexer INSTANCE = new LicenseIndexer();
static LicenseIndexer getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private LicenseIndexer() {
super(IndexType.LICENSE);
}
@Override
public String[] getSearchFields() {
return IndexConstants.LICENSE_SEARCH_FIELDS;
}
/**
* Adds a License object to a Lucene index.
*
* @param license A persisted License object.
*/
public void add(final LicenseDocument license) {
final Document doc = convertToDocument(license);
addDocument(doc);
}
@Override
public void update(final LicenseDocument license) {
final Term term = convertToTerm(license);
final Document doc = convertToDocument(license);
updateDocument(term, doc);
}
/**
* Deletes a License object from the Lucene index.
*
* @param license A persisted License object.
*/
public void remove(final LicenseDocument license) {
final Term term = convertToTerm(license);
deleteDocuments(term);
}
/**
* Re-indexes all License objects.
* @since 3.4.0
*/
public void reindex() {<FILL_FUNCTION_BODY>}
private static List<LicenseDocument> fetchNext(final QueryManager qm, final Long lastId) {
final Query<License> query = qm.getPersistenceManager().newQuery(License.class);
if (lastId != null) {
query.setFilter("id > :lastId");
query.setParameters(lastId);
}
query.setOrdering("id ASC");
query.setRange(0, 1000);
query.setResult("id, uuid, licenseId, name");
try {
return List.copyOf(query.executeResultList(LicenseDocument.class));
} finally {
query.closeAll();
}
}
private Document convertToDocument(final LicenseDocument license) {
final var doc = new Document();
addField(doc, IndexConstants.LICENSE_UUID, license.uuid().toString(), Field.Store.YES, false);
addField(doc, IndexConstants.LICENSE_LICENSEID, license.licenseId(), Field.Store.YES, true);
addField(doc, IndexConstants.LICENSE_NAME, license.name(), Field.Store.YES, true);
return doc;
}
private static Term convertToTerm(final LicenseDocument license) {
return new Term(IndexConstants.LICENSE_UUID, license.uuid().toString());
}
}
|
LOGGER.info("Starting reindex task. This may take some time.");
super.reindex();
long docsIndexed = 0;
final long startTimeNs = System.nanoTime();
try (QueryManager qm = new QueryManager()) {
List<LicenseDocument> docs = fetchNext(qm, null);
while (!docs.isEmpty()) {
docs.forEach(this::add);
docsIndexed += docs.size();
commit();
docs = fetchNext(qm, docs.get(docs.size() - 1).id());
}
}
LOGGER.info("Reindexing of %d licenses completed in %s"
.formatted(docsIndexed, Duration.ofNanos(System.nanoTime() - startTimeNs)));
| 721
| 206
| 927
|
<methods>public void addDocument(Document) ,public static void checkIndexesConsistency() ,public void close() ,public void commit() ,public static void delete(org.dependencytrack.search.IndexManager.IndexType) ,public void deleteDocuments(Term) ,public static void ensureIndexesExists() ,public org.dependencytrack.search.IndexManager.IndexType getIndexType() ,public java.lang.String[] getSearchFields() ,public void reindex() ,public void updateDocument(Term, Document) <variables>private static final Logger LOGGER,private final non-sealed Counter addOperationCounter,private final non-sealed Counter commitOperationCounter,private final non-sealed Counter deleteOperationCounter,private Gauge docsRamTotalGauge,private final non-sealed Tag indexTag,private final non-sealed org.dependencytrack.search.IndexManager.IndexType indexType,private IndexWriter iwriter,private final non-sealed Logger logger,private Gauge numDocsGauge,private Gauge ramBytesUsedGauge,private DirectoryReader searchReader,private final non-sealed Counter updateOperationCounter
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/ProjectIndexer.java
|
ProjectIndexer
|
convertToDocument
|
class ProjectIndexer extends IndexManager implements ObjectIndexer<ProjectDocument> {
private static final Logger LOGGER = Logger.getLogger(ProjectIndexer.class);
private static final ProjectIndexer INSTANCE = new ProjectIndexer();
static ProjectIndexer getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private ProjectIndexer() {
super(IndexType.PROJECT);
}
@Override
public String[] getSearchFields() {
return IndexConstants.PROJECT_SEARCH_FIELDS;
}
/**
* Adds a Project object to a Lucene index.
*
* @param project A persisted Project object.
*/
public void add(final ProjectDocument project) {
final Document doc = convertToDocument(project);
addDocument(doc);
}
@Override
public void update(final ProjectDocument project) {
final Term term = convertToTerm(project);
final Document doc = convertToDocument(project);
updateDocument(term, doc);
}
/**
* Deletes a Project object from the Lucene index.
*
* @param project A persisted Project object.
*/
public void remove(final ProjectDocument project) {
final Term term = convertToTerm(project);
deleteDocuments(term);
}
/**
* Re-indexes all Project objects.
* @since 3.4.0
*/
public void reindex() {
LOGGER.info("Starting reindex task. This may take some time.");
super.reindex();
long docsIndexed = 0;
final long startTimeNs = System.nanoTime();
try (final QueryManager qm = new QueryManager()) {
List<ProjectDocument> docs = fetchNext(qm, null);
while (!docs.isEmpty()) {
docs.forEach(this::add);
docsIndexed += docs.size();
commit();
docs = fetchNext(qm, docs.get(docs.size() - 1).id());
}
}
LOGGER.info("Reindexing of %d projects completed in %s"
.formatted(docsIndexed, Duration.ofNanos(System.nanoTime() - startTimeNs)));
}
private static List<ProjectDocument> fetchNext(final QueryManager qm, final Long lastId) {
final Query<Project> query = qm.getPersistenceManager().newQuery(Project.class);
var filterParts = new ArrayList<String>();
var params = new HashMap<String, Object>();
filterParts.add("(active == null || active)");
if (lastId != null) {
filterParts.add("id > :lastId");
params.put("lastId", lastId);
}
query.setFilter(String.join(" && ", filterParts));
query.setNamedParameters(params);
query.setOrdering("id ASC");
query.setRange(0, 1000);
query.setResult("id, uuid, name, version, description");
try {
return List.copyOf(query.executeResultList(ProjectDocument.class));
} finally {
query.closeAll();
}
}
private Document convertToDocument(final ProjectDocument project) {<FILL_FUNCTION_BODY>}
private static Term convertToTerm(final ProjectDocument project) {
return new Term(IndexConstants.PROJECT_UUID, project.uuid().toString());
}
}
|
final var doc = new Document();
addField(doc, IndexConstants.PROJECT_UUID, project.uuid().toString(), Field.Store.YES, false);
addField(doc, IndexConstants.PROJECT_NAME, project.name(), Field.Store.YES, true);
addField(doc, IndexConstants.PROJECT_VERSION, project.version(), Field.Store.YES, false);
addField(doc, IndexConstants.PROJECT_DESCRIPTION, project.description(), Field.Store.YES, true);
/*
// There's going to potentially be confidential information in the project properties. Do not index.
final StringBuilder sb = new StringBuilder();
if (project.getProperties() != null) {
for (ProjectProperty property : project.getProperties()) {
sb.append(property.getPropertyValue()).append(" ");
}
}
addField(doc, IndexConstants.PROJECT_PROPERTIES, sb.toString().trim(), Field.Store.YES, true);
*/
return doc;
| 892
| 251
| 1,143
|
<methods>public void addDocument(Document) ,public static void checkIndexesConsistency() ,public void close() ,public void commit() ,public static void delete(org.dependencytrack.search.IndexManager.IndexType) ,public void deleteDocuments(Term) ,public static void ensureIndexesExists() ,public org.dependencytrack.search.IndexManager.IndexType getIndexType() ,public java.lang.String[] getSearchFields() ,public void reindex() ,public void updateDocument(Term, Document) <variables>private static final Logger LOGGER,private final non-sealed Counter addOperationCounter,private final non-sealed Counter commitOperationCounter,private final non-sealed Counter deleteOperationCounter,private Gauge docsRamTotalGauge,private final non-sealed Tag indexTag,private final non-sealed org.dependencytrack.search.IndexManager.IndexType indexType,private IndexWriter iwriter,private final non-sealed Logger logger,private Gauge numDocsGauge,private Gauge ramBytesUsedGauge,private DirectoryReader searchReader,private final non-sealed Counter updateOperationCounter
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/SearchManager.java
|
SearchManager
|
searchIndices
|
class SearchManager {
private static final Logger LOGGER = Logger.getLogger(SearchManager.class);
public SearchResult searchIndices(final String queryString, final int limit) {<FILL_FUNCTION_BODY>}
public SearchResult searchIndex(final IndexManager indexManager, final String queryString, final int limit) {
final SearchResult searchResult = new SearchResult();
final List<Map<String, String>> resultSet = new ArrayList<>();
try {
String escaped = escape(queryString);
final String sb = escaped +
"^100" +
" OR " +
escaped +
"*" +
"^5" +
" OR " +
"*" +
escaped +
"*";
final Query query = indexManager.getQueryParser().parse(sb);
final TopDocs results = indexManager.getIndexSearcher().search(query, limit);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Searching for: " + escaped + " - Total Hits: " + results.totalHits);
}
for (final ScoreDoc scoreDoc: results.scoreDocs) {
final Document doc = indexManager.getIndexSearcher().doc(scoreDoc.doc);
final Map<String, String> fields = new HashMap<>();
for (final IndexableField field: doc.getFields()) {
if (StringUtils.isNotBlank(field.stringValue())) {
fields.put(field.name(), field.stringValue());
}
}
resultSet.add(fields);
}
searchResult.addResultSet(indexManager.getIndexType().name().toLowerCase(), resultSet);
} catch (ParseException e) {
LOGGER.error("Failed to parse search string", e);
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.INDEXING_SERVICE)
.title(NotificationConstants.Title.CORE_INDEXING_SERVICES)
.content("Failed to parse search string. Check log for details. " + e.getMessage())
.level(NotificationLevel.ERROR)
);
} catch (CorruptIndexException e) {
LOGGER.error("Corrupted Lucene index detected", e);
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.INDEXING_SERVICE)
.title(NotificationConstants.Title.CORE_INDEXING_SERVICES)
.content("Corrupted Lucene index detected. Check log for details. " + e.getMessage())
.level(NotificationLevel.ERROR)
);
LOGGER.info("Trying to rebuild the corrupted index "+indexManager.getIndexType().name());
Event.dispatch(new IndexEvent(IndexEvent.Action.REINDEX, indexManager.getIndexType().getClazz()));
} catch (IOException e) {
LOGGER.error("An I/O Exception occurred while searching Lucene index", e);
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.INDEXING_SERVICE)
.title(NotificationConstants.Title.CORE_INDEXING_SERVICES)
.content("An I/O Exception occurred while searching Lucene index. Check log for details. " + e.getMessage())
.level(NotificationLevel.ERROR)
);
}
indexManager.close();
return searchResult;
}
public SearchResult searchProjectIndex(final String queryString, final int limit) {
return searchIndex(ProjectIndexer.getInstance(), queryString, limit);
}
public SearchResult searchComponentIndex(final String queryString, final int limit) {
return searchIndex(ComponentIndexer.getInstance(), queryString, limit);
}
public SearchResult searchServiceComponentIndex(final String queryString, final int limit) {
return searchIndex(ServiceComponentIndexer.getInstance(), queryString, limit);
}
public SearchResult searchLicenseIndex(final String queryString, final int limit) {
return searchIndex(LicenseIndexer.getInstance(), queryString, limit);
}
public SearchResult searchVulnerabilityIndex(final String queryString, final int limit) {
return searchIndex(VulnerabilityIndexer.getInstance(), queryString, limit);
}
public SearchResult searchVulnerableSoftwareIndex(final String queryString, final int limit) {
return searchIndex(VulnerableSoftwareIndexer.getInstance(), queryString, limit);
}
public String reindex(Set<String> type) {
List<IndexManager.IndexType> indexTypes = type.stream().flatMap(t -> IndexManager.IndexType.getIndexType(t).stream()).toList();
if(indexTypes.isEmpty()) {
throw new IllegalArgumentException("No valid index type was provided");
}
IndexEvent firstReindexEvent = new IndexEvent(IndexEvent.Action.REINDEX, indexTypes.get(0).getClazz());
String uuid = firstReindexEvent.getChainIdentifier().toString();
IndexEvent currentReindexEvent = firstReindexEvent;
for(IndexManager.IndexType indexType : indexTypes) {
if(indexType != indexTypes.get(0)) {
IndexEvent reindexEvent = new IndexEvent(IndexEvent.Action.REINDEX, indexType.getClazz());
currentReindexEvent.onSuccess(reindexEvent);
currentReindexEvent.onFailure(reindexEvent);
currentReindexEvent = reindexEvent;
}
}
Event.dispatch(firstReindexEvent);
return uuid;
}
/**
* Escapes special characters used in Lucene query syntax.
* + - && || ! ( ) { } [ ] ^ " ~ * ? : \ /
*
* @param input the text to escape
* @return escaped text
*/
private static String escape(final String input) {
if(input == null) {
return null;
}
char[] specialChars = {'+', '-', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '\\', '/'};
final StringBuilder sb = new StringBuilder();
for (int i = 0; i < input.length(); i++) {
final char c = input.charAt(i);
if (contains(specialChars, c)) {
sb.append("\\" + c);
} else {
sb.append(String.valueOf(c));
}
}
return sb.toString();
}
private static boolean contains(char[] chars, char queryChar) {
for (char c : chars) {
if (c == queryChar) {
return true;
}
}
return false;
}
}
|
final SearchResult searchResult = new SearchResult();
final IndexManager[] indexManagers = {
ProjectIndexer.getInstance(),
ComponentIndexer.getInstance(),
ServiceComponentIndexer.getInstance(),
VulnerabilityIndexer.getInstance(),
LicenseIndexer.getInstance()
};
Stream.of(indexManagers).parallel().forEach(
indexManager -> {
final SearchResult individualResult = searchIndex(indexManager, queryString, limit);
searchResult.getResults().putAll(individualResult.getResults());
}
);
return searchResult;
| 1,698
| 143
| 1,841
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/ServiceComponentIndexer.java
|
ServiceComponentIndexer
|
reindex
|
class ServiceComponentIndexer extends IndexManager implements ObjectIndexer<ServiceComponentDocument> {
private static final Logger LOGGER = Logger.getLogger(ServiceComponentIndexer.class);
private static final ServiceComponentIndexer INSTANCE = new ServiceComponentIndexer();
static ServiceComponentIndexer getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private ServiceComponentIndexer() {
super(IndexType.SERVICECOMPONENT);
}
@Override
public String[] getSearchFields() {
return IndexConstants.SERVICECOMPONENT_SEARCH_FIELDS;
}
/**
* Adds a Component object to a Lucene index.
*
* @param service A persisted ServiceComponent object.
*/
public void add(final ServiceComponentDocument service) {
final Document doc = convertToDocument(service);
addDocument(doc);
}
@Override
public void update(final ServiceComponentDocument service) {
final Term term = convertToTerm(service);
final Document doc = convertToDocument(service);
updateDocument(term, doc);
}
/**
* Deletes a ServiceComponent object from the Lucene index.
*
* @param service A persisted ServiceComponent object.
*/
public void remove(final ServiceComponentDocument service) {
final Term term = convertToTerm(service);
deleteDocuments(term);
}
/**
* Re-indexes all ServiceComponent objects.
* @since 4.2.0
*/
public void reindex() {<FILL_FUNCTION_BODY>}
private static List<ServiceComponentDocument> fetchNext(final QueryManager qm, final Long lastId) {
final Query<ServiceComponent> query = qm.getPersistenceManager().newQuery(ServiceComponent.class);
if (lastId != null) {
query.setFilter("id > :lastId");
query.setParameters(lastId);
}
query.setOrdering("id ASC");
query.setRange(0, 1000);
query.setResult("id, uuid, \"group\", name, version, description");
try {
return List.copyOf(query.executeResultList(ServiceComponentDocument.class));
} finally {
query.closeAll();
}
}
private Document convertToDocument(final ServiceComponentDocument service) {
final var doc = new Document();
addField(doc, IndexConstants.SERVICECOMPONENT_UUID, service.uuid().toString(), Field.Store.YES, false);
addField(doc, IndexConstants.SERVICECOMPONENT_NAME, service.name(), Field.Store.YES, true);
addField(doc, IndexConstants.SERVICECOMPONENT_GROUP, service.group(), Field.Store.YES, true);
addField(doc, IndexConstants.SERVICECOMPONENT_VERSION, service.version(), Field.Store.YES, false);
// TODO: addField(doc, IndexConstants.SERVICECOMPONENT_URL, service.getUrl(), Field.Store.YES, true);
addField(doc, IndexConstants.SERVICECOMPONENT_DESCRIPTION, service.description(), Field.Store.YES, true);
return doc;
}
private static Term convertToTerm(final ServiceComponentDocument service) {
return new Term(IndexConstants.SERVICECOMPONENT_UUID, service.uuid().toString());
}
}
|
LOGGER.info("Starting reindex task. This may take some time.");
super.reindex();
long docsIndexed = 0;
final long startTimeNs = System.nanoTime();
try (QueryManager qm = new QueryManager()) {
List<ServiceComponentDocument> docs = fetchNext(qm, null);
while (!docs.isEmpty()) {
docs.forEach(this::add);
docsIndexed += docs.size();
commit();
docs = fetchNext(qm, docs.get(docs.size() - 1).id());
}
}
LOGGER.info("Reindexing of %d services completed in %s"
.formatted(docsIndexed, Duration.ofNanos(System.nanoTime() - startTimeNs)));
| 860
| 206
| 1,066
|
<methods>public void addDocument(Document) ,public static void checkIndexesConsistency() ,public void close() ,public void commit() ,public static void delete(org.dependencytrack.search.IndexManager.IndexType) ,public void deleteDocuments(Term) ,public static void ensureIndexesExists() ,public org.dependencytrack.search.IndexManager.IndexType getIndexType() ,public java.lang.String[] getSearchFields() ,public void reindex() ,public void updateDocument(Term, Document) <variables>private static final Logger LOGGER,private final non-sealed Counter addOperationCounter,private final non-sealed Counter commitOperationCounter,private final non-sealed Counter deleteOperationCounter,private Gauge docsRamTotalGauge,private final non-sealed Tag indexTag,private final non-sealed org.dependencytrack.search.IndexManager.IndexType indexType,private IndexWriter iwriter,private final non-sealed Logger logger,private Gauge numDocsGauge,private Gauge ramBytesUsedGauge,private DirectoryReader searchReader,private final non-sealed Counter updateOperationCounter
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/VulnerabilityIndexer.java
|
VulnerabilityIndexer
|
convertToDocument
|
class VulnerabilityIndexer extends IndexManager implements ObjectIndexer<VulnerabilityDocument> {
private static final Logger LOGGER = Logger.getLogger(VulnerabilityIndexer.class);
private static final VulnerabilityIndexer INSTANCE = new VulnerabilityIndexer();
static VulnerabilityIndexer getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private VulnerabilityIndexer() {
super(IndexType.VULNERABILITY);
}
@Override
public String[] getSearchFields() {
return IndexConstants.VULNERABILITY_SEARCH_FIELDS;
}
/**
* Adds a Vulnerability object to a Lucene index.
*
* @param vulnerability A persisted Vulnerability object.
*/
public void add(final VulnerabilityDocument vulnerability) {
final Document doc = convertToDocument(vulnerability);
addDocument(doc);
}
@Override
public void update(final VulnerabilityDocument vuln) {
final Term term = convertToTerm(vuln);
final Document doc = convertToDocument(vuln);
updateDocument(term, doc);
}
/**
* Deletes a Vulnerability object from the Lucene index.
*
* @param vulnerability A persisted Vulnerability object.
*/
public void remove(final VulnerabilityDocument vulnerability) {
final Term term = convertToTerm(vulnerability);
deleteDocuments(term);
}
/**
* Re-indexes all Vulnerability objects.
* @since 3.4.0
*/
public void reindex() {
LOGGER.info("Starting reindex task. This may take some time.");
super.reindex();
long docsIndexed = 0;
final long startTimeNs = System.nanoTime();
try (QueryManager qm = new QueryManager()) {
List<VulnerabilityDocument> docs = fetchNext(qm, null);
while (!docs.isEmpty()) {
docs.forEach(this::add);
docsIndexed += docs.size();
commit();
docs = fetchNext(qm, docs.get(docs.size() - 1).id());
}
}
LOGGER.info("Reindexing of %d vulnerabilities completed in %s"
.formatted(docsIndexed, Duration.ofNanos(System.nanoTime() - startTimeNs)));
}
private static List<VulnerabilityDocument> fetchNext(final QueryManager qm, final Long lastId) {
final Query<Vulnerability> query = qm.getPersistenceManager().newQuery(Vulnerability.class);
if (lastId != null) {
query.setFilter("id > :lastId");
query.setParameters(lastId);
}
query.setOrdering("id ASC");
query.setRange(0, 500); // Descriptions can be large, keep batch size conservative.
query.setResult("id, uuid, vulnId, source, description");
try {
return List.copyOf(query.executeResultList(VulnerabilityDocument.class));
} finally {
query.closeAll();
}
}
private Document convertToDocument(final VulnerabilityDocument vuln) {<FILL_FUNCTION_BODY>}
private static Term convertToTerm(final VulnerabilityDocument vuln) {
return new Term(IndexConstants.VULNERABILITY_UUID, vuln.uuid().toString());
}
}
|
final var doc = new Document();
addField(doc, IndexConstants.VULNERABILITY_UUID, vuln.uuid().toString(), Field.Store.YES, false);
addField(doc, IndexConstants.VULNERABILITY_VULNID, vuln.vulnId(), Field.Store.YES, true);
addField(doc, IndexConstants.VULNERABILITY_DESCRIPTION, vuln.description(), Field.Store.YES, true);
addField(doc, IndexConstants.VULNERABILITY_SOURCE, vuln.source(), Field.Store.YES, false);
return doc;
| 929
| 156
| 1,085
|
<methods>public void addDocument(Document) ,public static void checkIndexesConsistency() ,public void close() ,public void commit() ,public static void delete(org.dependencytrack.search.IndexManager.IndexType) ,public void deleteDocuments(Term) ,public static void ensureIndexesExists() ,public org.dependencytrack.search.IndexManager.IndexType getIndexType() ,public java.lang.String[] getSearchFields() ,public void reindex() ,public void updateDocument(Term, Document) <variables>private static final Logger LOGGER,private final non-sealed Counter addOperationCounter,private final non-sealed Counter commitOperationCounter,private final non-sealed Counter deleteOperationCounter,private Gauge docsRamTotalGauge,private final non-sealed Tag indexTag,private final non-sealed org.dependencytrack.search.IndexManager.IndexType indexType,private IndexWriter iwriter,private final non-sealed Logger logger,private Gauge numDocsGauge,private Gauge ramBytesUsedGauge,private DirectoryReader searchReader,private final non-sealed Counter updateOperationCounter
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/search/VulnerableSoftwareIndexer.java
|
VulnerableSoftwareIndexer
|
reindex
|
class VulnerableSoftwareIndexer extends IndexManager implements ObjectIndexer<VulnerableSoftwareDocument> {
private static final Logger LOGGER = Logger.getLogger(VulnerableSoftwareIndexer.class);
private static final VulnerableSoftwareIndexer INSTANCE = new VulnerableSoftwareIndexer();
static VulnerableSoftwareIndexer getInstance() {
return INSTANCE;
}
/**
* Private constructor.
*/
private VulnerableSoftwareIndexer() {
super(IndexType.VULNERABLESOFTWARE);
}
@Override
public String[] getSearchFields() {
return IndexConstants.VULNERABLESOFTWARE_SEARCH_FIELDS;
}
/**
* Adds a VulnerableSoftware object to a Lucene index.
*
* @param vs A persisted VulnerableSoftware object.
*/
public void add(final VulnerableSoftwareDocument vs) {
final Document doc = convertToDocument(vs);
addDocument(doc);
}
@Override
public void update(final VulnerableSoftwareDocument vs) {
final Term term = convertToTerm(vs);
final Document doc = convertToDocument(vs);
updateDocument(term, doc);
}
/**
* Deletes a VulnerableSoftware object from the Lucene index.
*
* @param vs A persisted VulnerableSoftware object.
*/
public void remove(final VulnerableSoftwareDocument vs) {
final Term term = convertToTerm(vs);
deleteDocuments(term);
}
/**
* Re-indexes all VulnerableSoftware objects.
*/
public void reindex() {<FILL_FUNCTION_BODY>}
private static List<VulnerableSoftwareDocument> fetchNext(final QueryManager qm, final Long lastId) {
final Query<VulnerableSoftware> query = qm.getPersistenceManager().newQuery(VulnerableSoftware.class);
if (lastId != null) {
query.setFilter("id > :lastId");
query.setParameters(lastId);
}
query.setOrdering("id ASC");
query.setRange(0, 1000);
query.setResult("id, uuid, cpe22, cpe23, vendor, product, version");
try {
return List.copyOf(query.executeResultList(VulnerableSoftwareDocument.class));
} finally {
query.closeAll();
}
}
private Document convertToDocument(final VulnerableSoftwareDocument vs) {
final var doc = new Document();
addField(doc, IndexConstants.VULNERABLESOFTWARE_UUID, vs.uuid().toString(), Field.Store.YES, false);
addField(doc, IndexConstants.VULNERABLESOFTWARE_CPE_22, vs.cpe22(), Field.Store.YES, false);
addField(doc, IndexConstants.VULNERABLESOFTWARE_CPE_23, vs.cpe23(), Field.Store.YES, false);
addField(doc, IndexConstants.VULNERABLESOFTWARE_VENDOR, vs.vendor(), Field.Store.YES, true);
addField(doc, IndexConstants.VULNERABLESOFTWARE_PRODUCT, vs.product(), Field.Store.YES, true);
addField(doc, IndexConstants.VULNERABLESOFTWARE_VERSION, vs.version(), Field.Store.YES, true);
//todo: index the affected version range fields as well
return doc;
}
private static Term convertToTerm(final VulnerableSoftwareDocument vs) {
return new Term(IndexConstants.VULNERABLESOFTWARE_UUID, vs.uuid().toString());
}
}
|
LOGGER.info("Starting reindex task. This may take some time.");
super.reindex();
long indexedDocs = 0;
final long startTimeNs = System.nanoTime();
try (QueryManager qm = new QueryManager()) {
List<VulnerableSoftwareDocument> docs = fetchNext(qm, null);
while (!docs.isEmpty()) {
docs.forEach(this::add);
indexedDocs += docs.size();
commit();
docs = fetchNext(qm, docs.get(docs.size() - 1).id());
}
}
LOGGER.info("Reindexing of %d VulnerableSoftwares completed in %s"
.formatted(indexedDocs, Duration.ofNanos(System.nanoTime() - startTimeNs)));
| 993
| 217
| 1,210
|
<methods>public void addDocument(Document) ,public static void checkIndexesConsistency() ,public void close() ,public void commit() ,public static void delete(org.dependencytrack.search.IndexManager.IndexType) ,public void deleteDocuments(Term) ,public static void ensureIndexesExists() ,public org.dependencytrack.search.IndexManager.IndexType getIndexType() ,public java.lang.String[] getSearchFields() ,public void reindex() ,public void updateDocument(Term, Document) <variables>private static final Logger LOGGER,private final non-sealed Counter addOperationCounter,private final non-sealed Counter commitOperationCounter,private final non-sealed Counter deleteOperationCounter,private Gauge docsRamTotalGauge,private final non-sealed Tag indexTag,private final non-sealed org.dependencytrack.search.IndexManager.IndexType indexType,private IndexWriter iwriter,private final non-sealed Logger logger,private Gauge numDocsGauge,private Gauge ramBytesUsedGauge,private DirectoryReader searchReader,private final non-sealed Counter updateOperationCounter
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/CallbackTask.java
|
CallbackTask
|
inform
|
class CallbackTask implements Subscriber {
@Override
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof final CallbackEvent event) {
event.getCallback().run();
}
| 41
| 28
| 69
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/ClearComponentAnalysisCacheTask.java
|
ClearComponentAnalysisCacheTask
|
inform
|
class ClearComponentAnalysisCacheTask implements LoggableSubscriber {
private static final Logger LOGGER = Logger.getLogger(ClearComponentAnalysisCacheTask.class);
/**
* {@inheritDoc}
*/
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof ClearComponentAnalysisCacheEvent) {
LOGGER.info("Clearing ComponentAnalysisCache");
try (QueryManager qm = new QueryManager()) {
ConfigProperty cacheClearPeriod = qm.getConfigProperty(ConfigPropertyConstants.SCANNER_ANALYSIS_CACHE_VALIDITY_PERIOD.getGroupName(), ConfigPropertyConstants.SCANNER_ANALYSIS_CACHE_VALIDITY_PERIOD.getPropertyName());
long cacheValidityPeriodMs = Long.parseLong(cacheClearPeriod.getPropertyValue());
Date threshold = Date.from(Instant.now().minusMillis(cacheValidityPeriodMs));
qm.clearComponentAnalysisCache(threshold);
} catch (Exception ex) {
LOGGER.error("An unknown error occurred while clearing component analysis cache", ex);
}
LOGGER.info("Complete");
}
| 79
| 215
| 294
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/CloneProjectTask.java
|
CloneProjectTask
|
inform
|
class CloneProjectTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(CloneProjectTask.class);
/**
* {@inheritDoc}
*/
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof CloneProjectEvent) {
final CloneProjectEvent event = (CloneProjectEvent)e;
final CloneProjectRequest request = event.getRequest();
LOGGER.info("Cloning project: " + request.getProject());
try (QueryManager qm = new QueryManager()) {
final Project project = qm.clone(UUID.fromString(request.getProject()),
request.getVersion(), request.includeTags(), request.includeProperties(),
request.includeComponents(), request.includeServices(), request.includeAuditHistory(), request.includeACL(), request.includePolicyViolations());
LOGGER.info("Cloned project: " + request.getProject() + " to " + project.getUuid());
}
}
| 74
| 186
| 260
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/DefectDojoUploadTask.java
|
DefectDojoUploadTask
|
inform
|
class DefectDojoUploadTask extends VulnerabilityManagementUploadTask {
private static final Logger LOGGER = Logger.getLogger(DefectDojoUploadTask.class);
/**
* {@inheritDoc}
*/
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof DefectDojoUploadEventAbstract) {
final DefectDojoUploadEventAbstract event = (DefectDojoUploadEventAbstract) e;
LOGGER.debug("Starting DefectDojo upload task");
super.inform(event, new DefectDojoUploader());
LOGGER.debug("DefectDojo upload complete");
}
| 82
| 90
| 172
|
<methods>public non-sealed void <init>() <variables>private static final Logger LOGGER
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/FortifySscUploadTask.java
|
FortifySscUploadTask
|
inform
|
class FortifySscUploadTask extends VulnerabilityManagementUploadTask {
private static final Logger LOGGER = Logger.getLogger(FortifySscUploadTask.class);
/**
* {@inheritDoc}
*/
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof FortifySscUploadEventAbstract) {
final FortifySscUploadEventAbstract event = (FortifySscUploadEventAbstract) e;
LOGGER.debug("Starting Fortify Software Security Center upload task");
super.inform(event, new FortifySscUploader());
LOGGER.debug("Fortify Software Security Center upload complete");
}
| 82
| 92
| 174
|
<methods>public non-sealed void <init>() <variables>private static final Logger LOGGER
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/IndexTask.java
|
IndexTask
|
inform
|
class IndexTask implements Subscriber {
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof final IndexEvent event) {
if (IndexEvent.Action.CHECK == event.getAction()) {
IndexManager.checkIndexesConsistency();
return;
}
final ObjectIndexer indexManager = IndexManagerFactory.getIndexManager(event);
if (IndexEvent.Action.CREATE == event.getAction()) {
indexManager.add(event.getDocument());
} else if (IndexEvent.Action.UPDATE == event.getAction()) {
indexManager.update(event.getDocument());
} else if (IndexEvent.Action.DELETE == event.getAction()) {
indexManager.remove(event.getDocument());
} else if (IndexEvent.Action.COMMIT == event.getAction()) {
indexManager.commit();
} else if (IndexEvent.Action.REINDEX == event.getAction()) {
Timer timer = Timer.builder("lucene_index_rebuild")
.description("Lucene index rebuild")
.tags("type", event.getIndexableClass().getName().toLowerCase())
.register(Metrics.getRegistry());
Timer.Sample recording = Timer.start();
indexManager.reindex();
recording.stop(timer);
}
}
| 60
| 306
| 366
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/InternalComponentIdentificationTask.java
|
InternalComponentIdentificationTask
|
analyze
|
class InternalComponentIdentificationTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(InternalComponentIdentificationTask.class);
@Override
public void inform(final Event e) {
if (e instanceof InternalComponentIdentificationEvent) {
LOGGER.info("Starting internal component identification");
final Instant startTime = Instant.now();
try {
analyze();
} catch (Exception ex) {
LOGGER.error("An unexpected error occurred while identifying internal components", ex);
}
LOGGER.info("Internal component identification completed in "
+ DateFormatUtils.format(Duration.between(startTime, Instant.now()).toMillis(), "mm:ss:SS"));
}
}
private void analyze() throws Exception {<FILL_FUNCTION_BODY>}
/**
* Efficiently page through all components using keyset pagination.
*
* @param pm The {@link PersistenceManager} to use
* @param lastId ID of the last {@link Component} in the previous result set, or {@code null} if this is the first invocation
* @return A {@link List} representing a page of up to {@code 500} {@link Component}s
* @throws Exception When closing the query failed
* @see <a href="https://use-the-index-luke.com/no-offset">Keyset pagination</a>
*/
private List<Component> fetchNextComponentsPage(final PersistenceManager pm, final Long lastId) throws Exception {
try (final Query<Component> query = pm.newQuery(Component.class)) {
if (lastId != null) {
query.setFilter("id < :lastId");
query.setParameters(lastId);
}
query.setOrdering("id DESC");
query.setRange(0, 500);
query.getFetchPlan().setGroup(Component.FetchGroup.INTERNAL_IDENTIFICATION.name());
return List.copyOf(query.executeList());
}
}
}
|
try (final var qm = new QueryManager()) {
final PersistenceManager pm = qm.getPersistenceManager();
// Disable the DataNucleus L2 cache for this persistence manager.
// The cache will hold references to the queried objects, preventing them
// from being garbage collected. This is not required the case of this task.
pm.setProperty(PropertyNames.PROPERTY_CACHE_L2_TYPE, "none");
final var internalComponentIdentifier = new InternalComponentIdentifier();
List<Component> components = fetchNextComponentsPage(pm, null);
while (!components.isEmpty()) {
for (final Component component : components) {
String coordinates = component.getName();
if (StringUtils.isNotBlank(component.getGroup())) {
coordinates = component.getGroup() + ":" + coordinates;
}
final boolean internal = internalComponentIdentifier.isInternal(component);
if (internal) {
LOGGER.debug("Component " + coordinates + " (" + component.getUuid() + ") was identified to be internal");
}
if (component.isInternal() != internal) {
if (internal) {
LOGGER.info("Component " + coordinates + " (" + component.getUuid()
+ ") was identified to be internal. It was previously not an internal component.");
} else {
LOGGER.info("Component " + coordinates + " (" + component.getUuid()
+ ") was previously identified as internal. It is no longer identified as internal.");
}
}
if (component.isInternal() != internal) {
final Transaction trx = pm.currentTransaction();
try {
trx.begin();
component.setInternal(internal);
trx.commit();
} finally {
if (trx.isActive()) {
trx.rollback();
}
}
}
}
final long lastId = components.get(components.size() - 1).getId();
components = fetchNextComponentsPage(pm, lastId);
}
}
| 514
| 511
| 1,025
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/KennaSecurityUploadTask.java
|
KennaSecurityUploadTask
|
inform
|
class KennaSecurityUploadTask extends VulnerabilityManagementUploadTask {
private static final Logger LOGGER = Logger.getLogger(KennaSecurityUploadTask.class);
/**
* {@inheritDoc}
*/
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof KennaSecurityUploadEventAbstract) {
final KennaSecurityUploadEventAbstract event = (KennaSecurityUploadEventAbstract) e;
LOGGER.debug("Starting Kenna Security upload task");
super.inform(event, new KennaSecurityUploader());
LOGGER.debug("Kenna Security upload complete");
}
| 81
| 86
| 167
|
<methods>public non-sealed void <init>() <variables>private static final Logger LOGGER
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/NewVulnerableDependencyAnalysisTask.java
|
NewVulnerableDependencyAnalysisTask
|
inform
|
class NewVulnerableDependencyAnalysisTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(NewVulnerableDependencyAnalysisTask.class);
@Override
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof final NewVulnerableDependencyAnalysisEvent event) {
for (Component component : event.components()) {
try (final var qm = new QueryManager()) {
component = qm.getObjectById(Component.class, component.getId());
LOGGER.debug("Analyzing notification criteria for component " + component.getUuid());
NotificationUtil.analyzeNotificationCriteria(qm, component);
} catch (Exception ex) {
LOGGER.error("An unknown error occurred while analyzing notification criteria for component " + component.getUuid(), ex);
}
}
}
| 74
| 150
| 224
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/PolicyEvaluationTask.java
|
PolicyEvaluationTask
|
inform
|
class PolicyEvaluationTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(PolicyEvaluationTask.class);
/**
* {@inheritDoc}
*/
@Override
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
private void performPolicyEvaluation(Project project, List<Component> components) {
// Evaluate the components against applicable policies via the PolicyEngine.
final PolicyEngine pe = new PolicyEngine();
pe.evaluate(components);
if (project != null) {
Event.dispatch(new ProjectMetricsUpdateEvent(project.getUuid()));
}
}
}
|
if (e instanceof PolicyEvaluationEvent event) {
if (event.getProject() != null) {
if (event.getComponents() != null && !event.getComponents().isEmpty()) {
performPolicyEvaluation(event.getProject(), event.getComponents());
} else {
performPolicyEvaluation(event.getProject(), new ArrayList<>());
}
}
}
| 169
| 102
| 271
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/TaskScheduler.java
|
TaskScheduler
|
getCadenceConfigPropertyValueInMilliseconds
|
class TaskScheduler extends AlpineTaskScheduler {
// Holds an instance of TaskScheduler
private static final TaskScheduler INSTANCE = new TaskScheduler();
/**
* Private constructor.
*/
private TaskScheduler() {
try (QueryManager qm = new QueryManager()) {
// Creates a new event that executes every 6 hours (21600000) by default after an initial 10 second (10000) delay
scheduleEvent(new LdapSyncEvent(), 10000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_LDAP_SYNC_CADENCE));
// Creates a new event that executes every 24 hours (86400000) by default after an initial 10 second (10000) delay
scheduleEvent(new GitHubAdvisoryMirrorEvent(), 10000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_GHSA_MIRROR_CADENCE));
// Creates a new event that executes every 24 hours (86400000) by default after an initial 10 second (10000) delay
scheduleEvent(new OsvMirrorEvent(), 10000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_OSV_MIRROR_CADENCE));
// Creates a new event that executes every 24 hours (86400000) by default after an initial 1 minute (60000) delay
scheduleEvent(new NistMirrorEvent(), 60000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_NIST_MIRROR_CADENCE));
// Creates a new event that executes every 24 hours (86400000) by default after an initial 1 minute (60000) delay
scheduleEvent(new VulnDbSyncEvent(), 60000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_VULNDB_MIRROR_CADENCE));
// Creates a new event that executes every 1 hour (3600000) by default after an initial 10 second (10000) delay
scheduleEvent(new PortfolioMetricsUpdateEvent(), 10000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_PORTFOLIO_METRICS_UPDATE_CADENCE));
// Creates a new event that executes every 1 hour (3600000) by default after an initial 10 second (10000) delay
scheduleEvent(new VulnerabilityMetricsUpdateEvent(), 10000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_VULNERABILITY_METRICS_UPDATE_CADENCE));
// Creates a new event that executes every 24 hours (86400000) by default after an initial 6 hour (21600000) delay
scheduleEvent(new PortfolioVulnerabilityAnalysisEvent(), 21600000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_PORTFOLIO_VULNERABILITY_ANALYSIS_CADENCE));
// Creates a new event that executes every 24 hours (86400000) by default after an initial 1 hour (3600000) delay
scheduleEvent(new RepositoryMetaEvent(), 3600000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_REPOSITORY_METADATA_FETCH_CADENCE));
// Creates a new event that executes every 6 hours (21600000) by default after an initial 1 hour (3600000) delay
scheduleEvent(new InternalComponentIdentificationEvent(), 3600000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_INTERNAL_COMPONENT_IDENTIFICATION_CADENCE));
// Creates a new event that executes every 72 hours (259200000) by default after an initial 10 second (10000) delay
scheduleEvent(new ClearComponentAnalysisCacheEvent(), 10000, getCadenceConfigPropertyValueInMilliseconds(qm, TASK_SCHEDULER_COMPONENT_ANALYSIS_CACHE_CLEAR_CADENCE));
}
// Configurable tasks
scheduleConfigurableTask(300000, FORTIFY_SSC_ENABLED, FORTIFY_SSC_SYNC_CADENCE, new FortifySscUploadEventAbstract());
scheduleConfigurableTask(300000, DEFECTDOJO_ENABLED, DEFECTDOJO_SYNC_CADENCE, new DefectDojoUploadEventAbstract());
scheduleConfigurableTask(300000, KENNA_ENABLED, KENNA_SYNC_CADENCE, new KennaSecurityUploadEventAbstract());
scheduleConfigurableTask(10800000, SEARCH_INDEXES_CONSISTENCY_CHECK_ENABLED, SEARCH_INDEXES_CONSISTENCY_CHECK_CADENCE, new IndexEvent(IndexEvent.Action.CHECK, Object.class));
}
/**
* Return an instance of the TaskScheduler instance.
* @return a TaskScheduler instance
*/
public static TaskScheduler getInstance() {
return INSTANCE;
}
private void scheduleConfigurableTask(final long initialDelay, final ConfigPropertyConstants enabledConstraint,
final ConfigPropertyConstants constraint, final Event event) {
try (QueryManager qm = new QueryManager()) {
final ConfigProperty enabledProperty = qm.getConfigProperty(
enabledConstraint.getGroupName(), enabledConstraint.getPropertyName());
if (enabledProperty != null && enabledProperty.getPropertyValue() != null) {
final boolean isEnabled = BooleanUtil.valueOf(enabledProperty.getPropertyValue());
if (!isEnabled) {
return;
}
} else {
return;
}
final ConfigProperty property = qm.getConfigProperty(constraint.getGroupName(), constraint.getPropertyName());
if (property != null && property.getPropertyValue() != null) {
final Integer minutes = Integer.valueOf(property.getPropertyValue());
scheduleEvent(event, initialDelay, (long)minutes * (long)60 * (long)1000);
}
}
}
private long getCadenceConfigPropertyValueInMilliseconds(QueryManager qm, ConfigPropertyConstants configProperty) {<FILL_FUNCTION_BODY>}
}
|
long result = 0;
ConfigProperty property = qm.getConfigProperty(configProperty.getGroupName(), configProperty.getPropertyName());
if(PropertyType.INTEGER.equals(property.getPropertyType()) && property.getPropertyValue() != null) {
result = Long.valueOf(property.getPropertyValue()) * 3600 * 1000;
}
return result;
| 1,771
| 103
| 1,874
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/VexUploadProcessingTask.java
|
VexUploadProcessingTask
|
inform
|
class VexUploadProcessingTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(VexUploadProcessingTask.class);
/**
* {@inheritDoc}
*/
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
}
|
if (e instanceof VexUploadEvent) {
final VexUploadEvent event = (VexUploadEvent) e;
final byte[] vexBytes = CompressUtil.optionallyDecompress(event.getVex());
try(final QueryManager qm = new QueryManager()) {
final Project project = qm.getObjectByUuid(Project.class, event.getProjectUuid());
final List<Vulnerability> vulnerabilities;
// Holds a list of all Components that are existing dependencies of the specified project
final List<Vulnerability> existingProjectVulnerabilities = qm.getVulnerabilities(project, true);
final Vex.Format vexFormat;
final String vexSpecVersion;
final Integer vexVersion;
final String serialNumnber;
org.cyclonedx.model.Bom cycloneDxBom = null;
if (BomParserFactory.looksLikeCycloneDX(vexBytes)) {
if (qm.isEnabled(ConfigPropertyConstants.ACCEPT_ARTIFACT_CYCLONEDX)) {
LOGGER.info("Processing CycloneDX VEX uploaded to project: " + event.getProjectUuid());
vexFormat = Vex.Format.CYCLONEDX;
final Parser parser = BomParserFactory.createParser(vexBytes);
cycloneDxBom = parser.parse(vexBytes);
vexSpecVersion = cycloneDxBom.getSpecVersion();
vexVersion = cycloneDxBom.getVersion();
serialNumnber = cycloneDxBom.getSerialNumber();
final CycloneDXVexImporter vexImporter = new CycloneDXVexImporter();
vexImporter.applyVex(qm, cycloneDxBom, project);
LOGGER.info("Completed processing of CycloneDX VEX for project: " + event.getProjectUuid());
} else {
LOGGER.warn("A CycloneDX VEX was uploaded but accepting CycloneDX format is disabled. Aborting");
return;
}
// TODO: Add support for CSAF
} else {
LOGGER.warn("The VEX uploaded is not in a supported format. Supported formats include CycloneDX XML and JSON");
return;
}
final Project copyOfProject = qm.detach(Project.class, qm.getObjectById(Project.class, project.getId()).getId());
Notification.dispatch(new Notification()
.scope(NotificationScope.PORTFOLIO)
.group(NotificationGroup.VEX_CONSUMED)
.title(NotificationConstants.Title.VEX_CONSUMED)
.level(NotificationLevel.INFORMATIONAL)
.content("A " + vexFormat.getFormatShortName() + " VEX was consumed and will be processed")
.subject(new VexConsumedOrProcessed(copyOfProject, Base64.getEncoder().encodeToString(vexBytes), vexFormat, vexSpecVersion)));
qm.createVex(project, new Date(), vexFormat, vexSpecVersion, vexVersion, serialNumnber);
final Project detachedProject = qm.detach(Project.class, project.getId());
Notification.dispatch(new Notification()
.scope(NotificationScope.PORTFOLIO)
.group(NotificationGroup.VEX_PROCESSED)
.title(NotificationConstants.Title.VEX_PROCESSED)
.level(NotificationLevel.INFORMATIONAL)
.content("A " + vexFormat.getFormatShortName() + " VEX was processed")
.subject(new VexConsumedOrProcessed(detachedProject, Base64.getEncoder().encodeToString(vexBytes), vexFormat, vexSpecVersion)));
} catch (Exception ex) {
LOGGER.error("Error while processing vex", ex);
}
}
| 78
| 984
| 1,062
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/VulnDbSyncTask.java
|
VulnDbSyncTask
|
inform
|
class VulnDbSyncTask implements LoggableSubscriber {
private static final Logger LOGGER = Logger.getLogger(VulnDbSyncTask.class);
private boolean successful = true;
/**
* {@inheritDoc}
*/
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
/**
* Synchronizes the VulnDB vulnerabilities with the internal Dependency-Track database.
*
* @param results the results to synchronize
*/
private void updateDatasource(final Results results) {
LOGGER.info("Updating datasource with VulnDB vulnerabilities");
try (QueryManager qm = new QueryManager()) {
for (final Object o : results.getResults()) {
if (o instanceof org.dependencytrack.parser.vulndb.model.Vulnerability) {
final org.dependencytrack.parser.vulndb.model.Vulnerability vulnDbVuln = (org.dependencytrack.parser.vulndb.model.Vulnerability) o;
final org.dependencytrack.model.Vulnerability vulnerability = ModelConverter.convert(qm, vulnDbVuln);
final Vulnerability synchronizeVulnerability = qm.synchronizeVulnerability(vulnerability, false);
final List<VulnerableSoftware> vsListOld = qm.detach(qm.getVulnerableSoftwareByVulnId(synchronizeVulnerability.getSource(), synchronizeVulnerability.getVulnId()));
List<VulnerableSoftware> vsList = parseCpes(qm, synchronizeVulnerability, vulnDbVuln);
qm.updateAffectedVersionAttributions(synchronizeVulnerability, vsList, Vulnerability.Source.VULNDB);
vsList = qm.reconcileVulnerableSoftware(synchronizeVulnerability, vsListOld, vsList, Vulnerability.Source.VULNDB);
synchronizeVulnerability.setVulnerableSoftware(vsList);
qm.persist(synchronizeVulnerability);
}
}
}
}
public static List<VulnerableSoftware> parseCpes(final QueryManager qm, final Vulnerability vulnerability,
final org.dependencytrack.parser.vulndb.model.Vulnerability vulnDbVuln) {
// cpe:2.3:a:belavier_commerce:abantecart:1.2.8:*:*:*:*:*:*:*
final List<VulnerableSoftware> vsList = new ArrayList<>();
if (vulnDbVuln.vendors() != null) {
for (Vendor vendor : vulnDbVuln.vendors()) {
if (vendor.products() != null) {
for (Product product : vendor.products()) {
if (product.versions() != null) {
for (Version version : product.versions()) {
if (version != null) {
if (version.affected()) {
if (version.cpes() != null) {
for (org.dependencytrack.parser.vulndb.model.Cpe cpeObject : version.cpes()) {
try {
final Cpe cpe = CpeParser.parse(cpeObject.cpe(), true);
final VulnerableSoftware vs = generateVulnerableSoftware(qm, cpe, vulnerability);
if (vs != null) {
vsList.add(vs);
}
} catch (CpeParsingException e) {
// Normally, this would be logged to error, however, VulnDB contains a lot of invalid CPEs
LOGGER.debug("An error occurred parsing " + cpeObject.cpe(), e);
}
}
}
}
}
}
}
}
}
}
}
return vsList;
}
private static VulnerableSoftware generateVulnerableSoftware(final QueryManager qm, final Cpe cpe,
final Vulnerability vulnerability) {
VulnerableSoftware vs = qm.getVulnerableSoftwareByCpe23(cpe.toCpe23FS(), null, null, null, null);
if (vs != null) {
return vs;
}
try {
vs = org.dependencytrack.parser.nvd.ModelConverter.convertCpe23UriToVulnerableSoftware(cpe.toCpe23FS());
vs.setVulnerable(true);
vs.addVulnerability(vulnerability);
// VulnDB does not provide version ranges for the CPEs that exist inside Vendor->Product->Version->CPE
vs.setVersionEndExcluding(null);
vs.setVersionEndIncluding(null);
vs.setVersionStartExcluding(null);
vs.setVersionStartIncluding(null);
vs = qm.persist(vs);
return vs;
} catch (CpeParsingException | CpeEncodingException e) {
LOGGER.warn("An error occurred while parsing: " + cpe.toCpe23FS() + " - The CPE is invalid and will be discarded.");
}
return null;
}
}
|
if (e instanceof VulnDbSyncEvent) {
LOGGER.info("Starting VulnDB mirror synchronization task");
final File vulndbDir = new File(Config.getInstance().getDataDirectorty(), "vulndb");
if (!vulndbDir.exists()) {
LOGGER.info("VulnDB mirror directory does not exist. Skipping.");
return;
}
final File[] files = vulndbDir.listFiles(
(dir, name) -> name.toLowerCase(Locale.ENGLISH).startsWith("vulnerabilities_")
);
if (files != null) {
for (final File file : files) {
LOGGER.info("Parsing: " + file.getName());
final VulnDbParser parser = new VulnDbParser();
try {
final Results results = parser.parse(file, org.dependencytrack.parser.vulndb.model.Vulnerability.class);
updateDatasource(results);
} catch (IOException ex) {
LOGGER.error("An error occurred while parsing VulnDB payload: " + file.getName(), ex);
successful = false;
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.DATASOURCE_MIRRORING)
.title(NotificationConstants.Title.VULNDB_MIRROR)
.content("An error occurred parsing VulnDB payload. Check log for details. " + ex.getMessage())
.level(NotificationLevel.ERROR)
);
}
}
}
Event.dispatch(new IndexEvent(IndexEvent.Action.COMMIT, Vulnerability.class));
LOGGER.info("VulnDB mirror synchronization task complete");
if (successful) {
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.DATASOURCE_MIRRORING)
.title(NotificationConstants.Title.VULNDB_MIRROR)
.content("Mirroring of VulnDB completed successfully")
.level(NotificationLevel.INFORMATIONAL)
);
}
}
| 1,373
| 558
| 1,931
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/VulnerabilityAnalysisTask.java
|
VulnerabilityAnalysisTask
|
analyzeComponents
|
class VulnerabilityAnalysisTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(VulnerabilityAnalysisTask.class);
/**
* {@inheritDoc}
*/
@Override
public void inform(final Event e) {
if (e instanceof VulnerabilityAnalysisEvent event) {
if (event.getComponents() != null && event.getComponents().size() > 0) {
final List<Component> components = new ArrayList<>();
try (final QueryManager qm = new QueryManager()) {
for (final Component c : event.getComponents()) {
// Ensures the current component (and related objects such as Project) are attached to the
// current persistence manager. This may cause duplicate projects to be created and other
// unexpected behavior.
components.add(qm.getObjectByUuid(Component.class, c.getUuid()));
}
analyzeComponents(qm, components, e);
}
}
} else if (e instanceof PortfolioVulnerabilityAnalysisEvent event) {
LOGGER.info("Analyzing portfolio");
try (final QueryManager qm = new QueryManager()) {
final List<UUID> projectUuids = qm.getAllProjects(true)
.stream()
.map(Project::getUuid)
.collect(Collectors.toList());
for (final UUID projectUuid : projectUuids) {
final Project project = qm.getObjectByUuid(Project.class, projectUuid);
if (project == null) continue;
final List<Component> components = qm.getAllComponents(project);
LOGGER.info("Analyzing " + components.size() + " components in project: " + project.getUuid());
analyzeComponents(qm, components, e);
performPolicyEvaluation(project, components);
LOGGER.info("Completed scheduled analysis of " + components.size() + " components in project: " + project.getUuid());
}
}
LOGGER.info("Portfolio analysis complete");
}
}
private void analyzeComponents(final QueryManager qm, final List<Component> components, final Event event) {<FILL_FUNCTION_BODY>}
private void performPolicyEvaluation(Project project, List<Component> components) {
// Evaluate the components against applicable policies via the PolicyEngine.
final PolicyEngine pe = new PolicyEngine();
pe.evaluate(components);
if (project != null) {
Event.dispatch(new ProjectMetricsUpdateEvent(project.getUuid()));
}
}
private void inspectComponentReadiness(final Component component, final ScanTask scanTask, final List<Component> candidates) {
if (scanTask.isCapable(component)) {
if (scanTask.getClass().isAssignableFrom(CacheableScanTask.class)) {
final CacheableScanTask cacheableScanTask = (CacheableScanTask) scanTask;
if (cacheableScanTask.shouldAnalyze(component.getPurl())) {
candidates.add(component);
} else {
cacheableScanTask.applyAnalysisFromCache(component);
}
} else {
candidates.add(component);
}
}
}
private void performAnalysis(final Subscriber scanTask, final VulnerabilityAnalysisEvent event,
final AnalyzerIdentity analyzerIdentity, final Event eventType) {
Instant start = Instant.now();
event.setVulnerabilityAnalysisLevel(VulnerabilityAnalysisLevel.PERIODIC_ANALYSIS);
if (eventType instanceof VulnerabilityAnalysisEvent) {
event.setVulnerabilityAnalysisLevel(VulnerabilityAnalysisLevel.BOM_UPLOAD_ANALYSIS);
}
if (CollectionUtils.isNotEmpty(event.getComponents())) {
// Clear the transient cache result for each component.
// Each analyzer will have its own result. Therefore, we do not want to mix them.
event.getComponents().forEach(c -> c.setCacheResult(null));
try {
scanTask.inform(event);
} catch (Exception ex) {
LOGGER.error("An unexpected error occurred performing a vulnerability analysis task", ex);
}
// Clear the transient cache result for each component.
// Each analyzer will have its own result. Therefore, we do not want to mix them.
event.getComponents().forEach(c -> c.setCacheResult(null));
Instant end = Instant.now();
Duration timeElapsed = Duration.between(start, end);
LOGGER.debug("Time taken by perform analysis task by " + analyzerIdentity.name() + " : " + timeElapsed.toMillis() + " milliseconds");
}
}
}
|
/*
When this task is processing events that specify the components to scan,
separate them out into 'candidates' so that we can fire off multiple events
in hopes of perform parallel analysis using different analyzers.
*/
final InternalAnalysisTask internalAnalysisTask = new InternalAnalysisTask();
final OssIndexAnalysisTask ossIndexAnalysisTask = new OssIndexAnalysisTask();
final VulnDbAnalysisTask vulnDbAnalysisTask = new VulnDbAnalysisTask();
final SnykAnalysisTask snykAnalysisTask = new SnykAnalysisTask();
final TrivyAnalysisTask trivyAnalysisTask = new TrivyAnalysisTask();
final List<Component> internalCandidates = new ArrayList<>();
final List<Component> ossIndexCandidates = new ArrayList<>();
final List<Component> vulnDbCandidates = new ArrayList<>();
final List<Component> snykCandidates = new ArrayList<>();
final List<Component> trivyCandidates = new ArrayList<>();
for (final Component component : components) {
inspectComponentReadiness(component, internalAnalysisTask, internalCandidates);
inspectComponentReadiness(component, ossIndexAnalysisTask, ossIndexCandidates);
inspectComponentReadiness(component, vulnDbAnalysisTask, vulnDbCandidates);
inspectComponentReadiness(component, snykAnalysisTask, snykCandidates);
inspectComponentReadiness(component, trivyAnalysisTask, trivyCandidates);
}
qm.detach(components);
// Do not call individual async events when processing a known list of components.
// Call each analyzer task sequentially and catch any exceptions as to prevent one analyzer
// from interrupting the successful execution of all analyzers.
performAnalysis(internalAnalysisTask, new InternalAnalysisEvent(internalCandidates), internalAnalysisTask.getAnalyzerIdentity(), event);
performAnalysis(ossIndexAnalysisTask, new OssIndexAnalysisEvent(ossIndexCandidates), ossIndexAnalysisTask.getAnalyzerIdentity(), event);
performAnalysis(snykAnalysisTask, new SnykAnalysisEvent(snykCandidates), snykAnalysisTask.getAnalyzerIdentity(), event);
performAnalysis(trivyAnalysisTask, new TrivyAnalysisEvent(trivyCandidates), trivyAnalysisTask.getAnalyzerIdentity(), event);
performAnalysis(vulnDbAnalysisTask, new VulnDbAnalysisEvent(vulnDbCandidates), vulnDbAnalysisTask.getAnalyzerIdentity(), event);
| 1,181
| 614
| 1,795
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/VulnerabilityManagementUploadTask.java
|
VulnerabilityManagementUploadTask
|
processProjectFindings
|
class VulnerabilityManagementUploadTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(VulnerabilityManagementUploadTask.class);
protected void inform(final Event e, final FindingUploader findingsUploader) {
if (e instanceof AbstractVulnerabilityManagementUploadEvent) {
try (QueryManager qm = new QueryManager()) {
findingsUploader.setQueryManager(qm);
if (findingsUploader.isEnabled()) {
if (findingsUploader instanceof ProjectFindingUploader) {
for (final Project project : qm.getAllProjects()) {
processProjectFindings((ProjectFindingUploader) findingsUploader, qm, project);
}
} else if (findingsUploader instanceof PortfolioFindingUploader) {
final PortfolioFindingUploader uploader = (PortfolioFindingUploader) findingsUploader;
final InputStream payload = uploader.process();
uploader.upload(payload);
}
}
} catch (Exception ex) {
LOGGER.error(ex.getMessage());
}
}
}
private void processProjectFindings(final ProjectFindingUploader uploader, final QueryManager qm, final Project project) {<FILL_FUNCTION_BODY>}
}
|
if (uploader.isProjectConfigured(project)) {
LOGGER.debug("Initializing integration point: " + uploader.name() + " for project: " + project.getUuid());
final List<Finding> findings = qm.getFindings(project);
final InputStream payload = uploader.process(project, findings);
LOGGER.debug("Uploading findings to " + uploader.name() + " for project: " + project.getUuid());
uploader.upload(project, payload);
}
| 320
| 131
| 451
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/metrics/PortfolioMetricsUpdateTask.java
|
PortfolioMetricsUpdateTask
|
updateMetrics
|
class PortfolioMetricsUpdateTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(PortfolioMetricsUpdateTask.class);
private static final long BATCH_SIZE = SystemUtil.getCpuCores();
@Override
public void inform(final Event e) {
if (e instanceof PortfolioMetricsUpdateEvent) {
try {
updateMetrics();
} catch (Exception ex) {
LOGGER.error("An unexpected error occurred while updating portfolio metrics", ex);
}
}
}
private void updateMetrics() throws Exception {<FILL_FUNCTION_BODY>}
private List<Project> fetchNextActiveProjectsPage(final PersistenceManager pm, final Long lastId) throws Exception {
try (final Query<Project> query = pm.newQuery(Project.class)) {
if (lastId == null) {
query.setFilter("(active == null || active == true)");
} else {
query.setFilter("(active == null || active == true) && id < :lastId");
query.setParameters(lastId);
}
query.setOrdering("id DESC");
query.range(0, BATCH_SIZE);
query.getFetchPlan().setGroup(Project.FetchGroup.METRICS_UPDATE.name());
return List.copyOf(query.executeList());
}
}
}
|
LOGGER.info("Executing portfolio metrics update");
final var counters = new Counters();
try (final var qm = new QueryManager()) {
final PersistenceManager pm = qm.getPersistenceManager();
LOGGER.debug("Fetching first " + BATCH_SIZE + " projects");
List<Project> activeProjects = fetchNextActiveProjectsPage(pm, null);
while (!activeProjects.isEmpty()) {
final long firstId = activeProjects.get(0).getId();
final long lastId = activeProjects.get(activeProjects.size() - 1).getId();
final int batchCount = activeProjects.size();
final var countDownLatch = new CountDownLatch(batchCount);
for (final Project project : activeProjects) {
LOGGER.debug("Dispatching metrics update event for project " + project.getUuid());
final var callbackEvent = new CallbackEvent(countDownLatch::countDown);
Event.dispatch(new ProjectMetricsUpdateEvent(project.getUuid())
.onSuccess(callbackEvent)
.onFailure(callbackEvent));
}
LOGGER.debug("Waiting for metrics updates for projects " + firstId + "-" + lastId + " to complete");
if (!countDownLatch.await(15, TimeUnit.MINUTES)) {
// Depending on the system load, it may take a while for the queued events
// to be processed. And depending on how large the projects are, it may take a
// while for the processing of the respective event to complete.
// It is unlikely though that either of these situations causes a block for
// over 15 minutes. If that happens, the system is under-resourced.
LOGGER.warn("Updating metrics for projects " + firstId + "-" + lastId +
" took longer than expected (15m); Proceeding with potentially stale data");
}
LOGGER.debug("Completed metrics updates for projects " + firstId + "-" + lastId);
for (final Project project : activeProjects) {
LOGGER.debug("Processing latest metrics for project " + project.getUuid());
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
if (metrics == null) {
// The project metrics calculation task failed, or the project has been
// deleted after the event being dispatched. Either way, nothing we can
// do anything about.
LOGGER.debug("No metrics found for project " + project.getUuid() + " - skipping");
continue;
}
counters.critical += metrics.getCritical();
counters.high += metrics.getHigh();
counters.medium += metrics.getMedium();
counters.low += metrics.getLow();
counters.unassigned += metrics.getUnassigned();
counters.vulnerabilities += metrics.getVulnerabilities();
counters.findingsTotal += metrics.getFindingsTotal();
counters.findingsAudited += metrics.getFindingsAudited();
counters.findingsUnaudited += metrics.getFindingsUnaudited();
counters.suppressions += metrics.getSuppressed();
counters.inheritedRiskScore = Metrics.inheritedRiskScore(counters.critical, counters.high, counters.medium, counters.low, counters.unassigned);
counters.projects++;
if (metrics.getVulnerabilities() > 0) {
counters.vulnerableProjects++;
}
counters.components += metrics.getComponents();
counters.vulnerableComponents += metrics.getVulnerableComponents();
counters.policyViolationsFail += metrics.getPolicyViolationsFail();
counters.policyViolationsWarn += metrics.getPolicyViolationsWarn();
counters.policyViolationsInfo += metrics.getPolicyViolationsInfo();
counters.policyViolationsTotal += metrics.getPolicyViolationsTotal();
counters.policyViolationsAudited += metrics.getPolicyViolationsAudited();
counters.policyViolationsUnaudited += metrics.getPolicyViolationsUnaudited();
counters.policyViolationsSecurityTotal += metrics.getPolicyViolationsSecurityTotal();
counters.policyViolationsSecurityAudited += metrics.getPolicyViolationsSecurityAudited();
counters.policyViolationsSecurityUnaudited += metrics.getPolicyViolationsSecurityUnaudited();
counters.policyViolationsLicenseTotal += metrics.getPolicyViolationsLicenseTotal();
counters.policyViolationsLicenseAudited += metrics.getPolicyViolationsLicenseAudited();
counters.policyViolationsLicenseUnaudited += metrics.getPolicyViolationsLicenseUnaudited();
counters.policyViolationsOperationalTotal += metrics.getPolicyViolationsOperationalTotal();
counters.policyViolationsOperationalAudited += metrics.getPolicyViolationsOperationalAudited();
counters.policyViolationsOperationalUnaudited += metrics.getPolicyViolationsOperationalUnaudited();
}
LOGGER.debug("Fetching next " + BATCH_SIZE + " projects");
activeProjects = fetchNextActiveProjectsPage(pm, lastId);
}
qm.runInTransaction(() -> {
final PortfolioMetrics latestMetrics = qm.getMostRecentPortfolioMetrics();
if (!counters.hasChanged(latestMetrics)) {
LOGGER.debug("Portfolio metrics did not change");
latestMetrics.setLastOccurrence(counters.measuredAt);
} else {
LOGGER.debug("Portfolio metrics changed");
final PortfolioMetrics metrics = counters.createPortfolioMetrics();
pm.makePersistent(metrics);
}
});
}
LOGGER.info("Completed portfolio metrics update in " +
DurationFormatUtils.formatDuration(new Date().getTime() - counters.measuredAt.getTime(), "mm:ss:SS"));
| 346
| 1,505
| 1,851
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/metrics/ProjectMetricsUpdateTask.java
|
ProjectMetricsUpdateTask
|
inform
|
class ProjectMetricsUpdateTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(ProjectMetricsUpdateTask.class);
@Override
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
private void updateMetrics(final UUID uuid) throws Exception {
final var counters = new Counters();
try (final QueryManager qm = new QueryManager()) {
final PersistenceManager pm = qm.getPersistenceManager();
final Project project = qm.getObjectByUuid(Project.class, uuid, List.of(Project.FetchGroup.METRICS_UPDATE.name()));
if (project == null) {
throw new NoSuchElementException("Project " + uuid + " does not exist");
}
LOGGER.debug("Fetching first components page for project " + uuid);
List<Component> components = fetchNextComponentsPage(pm, project, null);
while (!components.isEmpty()) {
for (final Component component : components) {
final Counters componentCounters;
try {
componentCounters = ComponentMetricsUpdateTask.updateMetrics(component.getUuid());
} catch (NoSuchElementException ex) {
// This will happen when a component or its associated project have been deleted after the
// task started. Instead of splurging the log with to-be-expected errors, we just log it
// with DEBUG, and ignore it otherwise.
LOGGER.debug("Couldn't update metrics of component " + component.getUuid() + " because the component was not found", ex);
continue;
} catch (Exception ex) {
LOGGER.error("An unexpected error occurred while updating metrics of component " + component.getUuid(), ex);
continue;
}
counters.critical += componentCounters.critical;
counters.high += componentCounters.high;
counters.medium += componentCounters.medium;
counters.low += componentCounters.low;
counters.unassigned += componentCounters.unassigned;
counters.vulnerabilities += componentCounters.vulnerabilities;
counters.findingsTotal += componentCounters.findingsTotal;
counters.findingsAudited += componentCounters.findingsAudited;
counters.findingsUnaudited += componentCounters.findingsUnaudited;
counters.suppressions += componentCounters.suppressions;
counters.inheritedRiskScore = Metrics.inheritedRiskScore(counters.critical, counters.high, counters.medium, counters.low, counters.unassigned);
counters.components++;
if (componentCounters.vulnerabilities > 0) {
counters.vulnerableComponents += 1;
}
counters.policyViolationsFail += componentCounters.policyViolationsFail;
counters.policyViolationsWarn += componentCounters.policyViolationsWarn;
counters.policyViolationsInfo += componentCounters.policyViolationsInfo;
counters.policyViolationsTotal += componentCounters.policyViolationsTotal;
counters.policyViolationsAudited += componentCounters.policyViolationsAudited;
counters.policyViolationsUnaudited += componentCounters.policyViolationsUnaudited;
counters.policyViolationsSecurityTotal += componentCounters.policyViolationsSecurityTotal;
counters.policyViolationsSecurityAudited += componentCounters.policyViolationsSecurityAudited;
counters.policyViolationsSecurityUnaudited += componentCounters.policyViolationsSecurityUnaudited;
counters.policyViolationsLicenseTotal += componentCounters.policyViolationsLicenseTotal;
counters.policyViolationsLicenseAudited += componentCounters.policyViolationsLicenseAudited;
counters.policyViolationsLicenseUnaudited += componentCounters.policyViolationsLicenseUnaudited;
counters.policyViolationsOperationalTotal += componentCounters.policyViolationsOperationalTotal;
counters.policyViolationsOperationalAudited += componentCounters.policyViolationsOperationalAudited;
counters.policyViolationsOperationalUnaudited += componentCounters.policyViolationsOperationalUnaudited;
}
LOGGER.debug("Fetching next components page for project " + uuid);
final long lastId = components.get(components.size() - 1).getId();
components = fetchNextComponentsPage(pm, project, lastId);
}
qm.runInTransaction(() -> {
final ProjectMetrics latestMetrics = qm.getMostRecentProjectMetrics(project);
if (!counters.hasChanged(latestMetrics)) {
LOGGER.debug("Metrics of project " + uuid + " did not change");
latestMetrics.setLastOccurrence(counters.measuredAt);
} else {
LOGGER.debug("Metrics of project " + uuid + " changed");
final ProjectMetrics metrics = counters.createProjectMetrics(project);
pm.makePersistent(metrics);
}
});
if (project.getLastInheritedRiskScore() == null ||
project.getLastInheritedRiskScore() != counters.inheritedRiskScore) {
LOGGER.debug("Updating inherited risk score of project " + uuid);
qm.runInTransaction(() -> project.setLastInheritedRiskScore(counters.inheritedRiskScore));
}
}
LOGGER.debug("Completed metrics update for project " + uuid + " in " +
DurationFormatUtils.formatDuration(new Date().getTime() - counters.measuredAt.getTime(), "mm:ss:SS"));
}
private List<Component> fetchNextComponentsPage(final PersistenceManager pm, final Project project, final Long lastId) throws Exception {
try (final Query<Component> query = pm.newQuery(Component.class)) {
if (lastId == null) {
query.setFilter("project == :project");
query.setParameters(project);
} else {
query.setFilter("project == :project && id < :lastId");
query.setParameters(project, lastId);
}
query.setOrdering("id DESC");
query.setRange(0, 500);
query.getFetchPlan().setGroup(Component.FetchGroup.METRICS_UPDATE.name());
return List.copyOf(query.executeList());
}
}
}
|
if (e instanceof final ProjectMetricsUpdateEvent event) {
try {
final UUID uuid = event.getUuid();
LOGGER.info("Executing metrics update for project " + uuid);
updateMetrics(uuid);
} catch (Exception ex) {
LOGGER.error("An unexpected error occurred while updating metrics for project " + event.getUuid(), ex);
}
}
| 1,629
| 100
| 1,729
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/metrics/VulnerabilityMetricsUpdateTask.java
|
VulnerabilityMetricsUpdateTask
|
updateMetrics
|
class VulnerabilityMetricsUpdateTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(VulnerabilityMetricsUpdateTask.class);
@Override
public void inform(final Event e) {
if (e instanceof VulnerabilityMetricsUpdateEvent) {
try {
updateMetrics();
} catch (Exception ex) {
LOGGER.error("An unexpected error occurred while updating vulnerability metrics", ex);
}
}
}
private void updateMetrics() throws Exception {<FILL_FUNCTION_BODY>}
private static Collection<YearMonthMetric> queryForMetrics(PersistenceManager pm, String dateField, String expectedNullField) throws Exception {
// You cannot seem to parametrize fieldnames in JDOQL, so we use String formatting
// You cannot seem to use aliases with GROUP BY in JDOQL
// You cannot seem to use IF ELSE with GROUP BY in JDOQL
// So we end up doing two queries instead of one with an IF ELSE
String queryTemplate =
"SELECT %s.getYear() as y, %s.getMonth()+1 as m, count(this) as count " +
"FROM org.dependencytrack.model.Vulnerability " +
"WHERE %s != null && %s == null " +
"GROUP BY %s.getYear(), %s.getMonth() + 1";
try (Query query = pm.newQuery("javax.jdo.query.JDOQL", String.format(queryTemplate, dateField, dateField, dateField, expectedNullField, dateField, dateField))) {
List<YearMonthMetric> flatMetrics = query.executeResultList(YearMonthMetric.class);
// the flatMetrics list is bound to the Query, so we need to copy it to a new array to survive query closure
return new ArrayList<YearMonthMetric>(flatMetrics);
}
}
}
|
LOGGER.info("Executing metrics update on vulnerability database");
final var measuredAt = new Date();
try (final var qm = new QueryManager()) {
final PersistenceManager pm = qm.getPersistenceManager();
/**
*
* The created field has priotiy over the published field, which is used as a fallback
* However, the created field is always empty (in my instances)
* But we leave this mechanism and field juggling in place for backwards compatibility,
* and for (future) analyzers/sources that might provide this field.
*
* BTW the queries to get these vulnerability counts are very fast,
* so strictly speaking there is no reason to create this extra table with metrics
*
*/
// Get metrics by published date but only if created field is null
Collection<YearMonthMetric> published = queryForMetrics(pm, "published", "created");
// Get metrics by created date regardless of value of published field
Collection<YearMonthMetric> created = queryForMetrics(pm, "created", null);
// Merge flat lists
published.addAll(created);
// Collect into nested map so we can sum the counts
Map<Integer, Map<Integer, Long>> metrics = published.stream()
.filter(ymm -> ymm.year != null)
.collect(Collectors.groupingBy(ymm -> ymm.year,
Collectors.groupingBy(ymm -> ymm.month, Collectors.summingLong(ymm -> ymm.count))));
// Flatten again, but now into VulnerabilityMetrics that can be persisted
Stream<VulnerabilityMetrics> monthlyStream = metrics.entrySet().stream()
.flatMap(e -> e.getValue().entrySet().stream().map(
v -> new VulnerabilityMetrics(e.getKey(), v.getKey(), v.getValue().intValue(), measuredAt)));
// Flatten another time, for the yearly counts
Stream<VulnerabilityMetrics> yearlyStream = metrics.entrySet().stream()
.map(e -> new VulnerabilityMetrics(e.getKey(), null, e.getValue().values().stream().mapToInt(d->d.intValue()).sum(), measuredAt));
qm.synchronizeVulnerabilityMetrics(Stream.concat(monthlyStream, yearlyStream).toList());
LOGGER.info("Completed metrics update on vulnerability database in " +
DurationFormatUtils.formatDuration(new Date().getTime() - measuredAt.getTime(), "mm:ss:SS"));
}
| 472
| 648
| 1,120
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/AbstractMetaAnalyzer.java
|
AbstractMetaAnalyzer
|
setRepositoryBaseUrl
|
class AbstractMetaAnalyzer implements IMetaAnalyzer {
protected String baseUrl;
protected String username;
protected String password;
/**
* {@inheritDoc}
*/
public void setRepositoryBaseUrl(String baseUrl) {<FILL_FUNCTION_BODY>}
public void setRepositoryUsernameAndPassword(String username, String password) {
this.username = StringUtils.trimToNull(username);
this.password = StringUtils.trimToNull(password);
}
protected String urlEncode(final String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
}
protected void handleUnexpectedHttpResponse(final Logger logger, String url, final int statusCode, final String statusText, final Component component) {
logger.debug("HTTP Status : " + statusCode + " " + statusText);
logger.debug(" - RepositoryType URL : " + url);
logger.debug(" - Package URL : " + component.getPurl().canonicalize());
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.REPOSITORY)
.title(NotificationConstants.Title.REPO_ERROR)
.content("An error occurred while communicating with an " + supportedRepositoryType().name() + " repository. URL: " + url + " HTTP Status: " + statusCode + ". Check log for details." )
.level(NotificationLevel.ERROR)
);
}
protected void handleRequestException(final Logger logger, final Exception e) {
logger.error("Request failure", e);
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.REPOSITORY)
.title(NotificationConstants.Title.REPO_ERROR)
.content("An error occurred while communicating with an " + supportedRepositoryType().name() + " repository. Check log for details. " + e.getMessage())
.level(NotificationLevel.ERROR)
);
}
protected CloseableHttpResponse processHttpRequest(String url) throws IOException {
final Logger logger = Logger.getLogger(getClass());
try {
URIBuilder uriBuilder = new URIBuilder(url);
final HttpUriRequest request = new HttpGet(uriBuilder.build().toString());
request.addHeader("accept", "application/json");
if (username != null || password != null) {
request.addHeader("Authorization", HttpUtil.basicAuthHeaderValue(username, password));
}
return HttpClientPool.getClient().execute(request);
}catch (URISyntaxException ex){
handleRequestException(logger, ex);
return null;
}
}
}
|
baseUrl = StringUtils.trimToNull(baseUrl);
if (baseUrl == null) {
return;
}
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
}
this.baseUrl = baseUrl;
| 683
| 82
| 765
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/CargoMetaAnalyzer.java
|
CargoMetaAnalyzer
|
analyze
|
class CargoMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(CargoMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://crates.io";
private static final String API_URL = "/api/v1/crates/%s";
CargoMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.CARGO.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.CARGO;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final HttpEntity entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity);
var jsonObject = new JSONObject(responseString);
final JSONObject crate = jsonObject.optJSONObject("crate");
if (crate != null) {
final String latest = crate.getString("newest_version");
meta.setLatestVersion(latest);
}
final JSONArray versions = jsonObject.optJSONArray("versions");
if (versions != null) {
for (int i = 0; i < versions.length(); i++) {
final JSONObject version = versions.getJSONObject(i);
final String versionString = version.optString("num");
if (meta.getLatestVersion() != null && meta.getLatestVersion().equals(versionString)) {
final String publishedTimestamp = version.optString("created_at");
try {
meta.setPublishedTimestamp(DateUtil.fromISO8601(publishedTimestamp));
} catch (IllegalArgumentException e) {
LOGGER.warn("An error occurred while parsing published time", e);
}
}
}
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException ex) {
handleRequestException(LOGGER, ex);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 251
| 491
| 742
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/ComposerMetaAnalyzer.java
|
ComposerMetaAnalyzer
|
analyze
|
class ComposerMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(ComposerMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://repo.packagist.org";
/**
* @see <a href="https://packagist.org/apidoc#get-package-metadata-v1">Packagist's API doc for "Getting package data - Using the Composer v1 metadata (DEPRECATED)"</a>
*/
private static final String API_URL = "/p/%s/%s.json";
ComposerMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.COMPOSER.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.COMPOSER;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
private static String stripLeadingV(String s) {
return s.startsWith("v")
? s.substring(1)
: s;
}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() == null) {
return meta;
}
final String url = String.format(baseUrl + API_URL, component.getPurl().getNamespace(), component.getPurl().getName());
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
return meta;
}
if (response.getEntity().getContent() == null) {
return meta;
}
String jsonString = EntityUtils.toString(response.getEntity());
if (jsonString.equalsIgnoreCase("")) {
return meta;
}
if (jsonString.equalsIgnoreCase("{}")) {
return meta;
}
JSONObject jsonObject = new JSONObject(jsonString);
final String expectedResponsePackage = component.getPurl().getNamespace() + "/" + component.getPurl().getName();
final JSONObject responsePackages = jsonObject
.getJSONObject("packages");
if (!responsePackages.has(expectedResponsePackage)) {
// the package no longer exists - like this one: https://repo.packagist.org/p/magento/adobe-ims.json
return meta;
}
final JSONObject composerPackage = responsePackages.getJSONObject(expectedResponsePackage);
final ComparableVersion latestVersion = new ComparableVersion(stripLeadingV(component.getPurl().getVersion()));
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
composerPackage.names().forEach(key_ -> {
String key = (String) key_;
if (key.startsWith("dev-") || key.endsWith("-dev")) {
// dev versions are excluded, since they are not pinned but a VCS-branch.
return;
}
final String version_normalized = composerPackage.getJSONObject(key).getString("version_normalized");
ComparableVersion currentComparableVersion = new ComparableVersion(version_normalized);
if (currentComparableVersion.compareTo(latestVersion) < 0) {
// smaller version can be skipped
return;
}
final String version = composerPackage.getJSONObject(key).getString("version");
latestVersion.parseVersion(stripLeadingV(version_normalized));
meta.setLatestVersion(version);
final String published = composerPackage.getJSONObject(key).getString("time");
try {
meta.setPublishedTimestamp(dateFormat.parse(published));
} catch (ParseException e) {
LOGGER.warn("An error occurred while parsing upload time", e);
}
});
} catch (IOException ex) {
handleRequestException(LOGGER, ex);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
return meta;
| 370
| 786
| 1,156
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/CpanMetaAnalyzer.java
|
CpanMetaAnalyzer
|
analyze
|
class CpanMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(CpanMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://fastapi.metacpan.org/v1";
private static final String API_URL = "/module/%s";
CpanMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && "cpan".equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.CPAN;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String packageName;
if (component.getPurl().getNamespace() != null) {
packageName = component.getPurl().getNamespace() + "%2F" + component.getPurl().getName();
} else {
packageName = component.getPurl().getName();
}
final String url = String.format(baseUrl + API_URL, packageName);
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity()!=null) {
String responseString = EntityUtils.toString(response.getEntity());
var jsonObject = new JSONObject(responseString);
final String latest = jsonObject.optString("version");
if (latest != null) {
meta.setLatestVersion(latest);
}
final String published = jsonObject.optString("date");
if (published != null) {
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
meta.setPublishedTimestamp(dateFormat.parse(published));
} catch (ParseException e) {
LOGGER.warn("An error occurred while parsing upload time", e);
}
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException e) {
handleRequestException(LOGGER, e);
}
}
return meta;
| 246
| 436
| 682
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/GemMetaAnalyzer.java
|
GemMetaAnalyzer
|
analyze
|
class GemMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(GemMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://rubygems.org";
private static final String API_URL = "/api/v1/versions/%s/latest.json";
GemMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.GEM.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.GEM;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
if(response.getEntity()!=null){
String responseString = EntityUtils.toString(response.getEntity());
var jsonObject = new JSONObject(responseString);
final String latest = jsonObject.getString("version");
meta.setLatestVersion(latest);
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
}catch (IOException ex){
handleRequestException(LOGGER, ex);
}catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 253
| 265
| 518
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/GithubMetaAnalyzer.java
|
GithubMetaAnalyzer
|
analyze
|
class GithubMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(GithubMetaAnalyzer.class);
private enum VersionType {
RELEASE,
COMMIT;
}
private static final VersionType DEFAULT_VERSION_TYPE = VersionType.RELEASE;
private static final String REPOSITORY_DEFAULT_URL = "https://github.com";
private String repositoryUrl;
private String repositoryUser;
private String repositoryPassword;
GithubMetaAnalyzer() {
this.repositoryUrl = REPOSITORY_DEFAULT_URL;
}
/**
* {@inheritDoc}
*/
@Override
public void setRepositoryBaseUrl(String baseUrl) {
this.repositoryUrl = baseUrl;
}
/**
* {@inheritDoc}
*/
@Override
public void setRepositoryUsernameAndPassword(String username, String password) {
this.repositoryUser = username;
this.repositoryPassword = password;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.GITHUB.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.GITHUB;
}
/**
* Checks whether the pURL version is a release or commit
* @param component Component Object
* @param repository The GH Repository Object defined by the pURL
* @return VersionType
* @throws IOException when GitHub API Calls fail
*/
private VersionType get_version_type(final Component component, GHRepository repository) throws IOException {
if (component.getPurl().getVersion() == null){
LOGGER.debug(String.format("Version is not set, assuming %s", DEFAULT_VERSION_TYPE.name()));
return DEFAULT_VERSION_TYPE;
}
if (repository.getReleaseByTagName(component.getPurl().getVersion()) != null){
LOGGER.debug("Version is release");
return VersionType.RELEASE;
} else {
LOGGER.debug("Version is commit");
return VersionType.COMMIT;
}
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
try {
final GitHub github;
if (isNotBlank(repositoryUser) && isNotBlank(repositoryPassword)) {
github = GitHub.connect(repositoryUser, repositoryPassword);
} else if (isBlank(repositoryUser) && isNotBlank(repositoryPassword)) {
github = GitHub.connectUsingOAuth(repositoryUrl, repositoryPassword);
} else {
github = GitHub.connectAnonymously();
}
GHRepository repository = github.getRepository(String.format("%s/%s", component.getPurl().getNamespace(), component.getPurl().getName()));
LOGGER.debug(String.format("Repos is at %s", repository.getUrl()));
final VersionType version_type = get_version_type(component, repository);
if (version_type == VersionType.RELEASE) {
GHRelease latest_release = repository.getLatestRelease();
if (latest_release != null) {
meta.setLatestVersion(latest_release.getTagName());
LOGGER.debug(String.format("Latest version: %s", meta.getLatestVersion()));
}
GHRelease current_release = repository.getReleaseByTagName(component.getPurl().getVersion());
if (current_release != null) {
meta.setPublishedTimestamp(current_release.getPublished_at());
LOGGER.debug(String.format("Current version published at: %s", meta.getPublishedTimestamp()));
}
}
if (version_type == VersionType.COMMIT) {
GHBranch default_branch = repository.getBranch(repository.getDefaultBranch());
GHCommit latest_release = repository.getCommit(default_branch.getSHA1());
meta.setLatestVersion(latest_release.getSHA1());
LOGGER.debug(String.format("Latest version: %s", meta.getLatestVersion()));
GHCommit current_release = repository.getCommit(component.getPurl().getVersion());
meta.setPublishedTimestamp(current_release.getCommitDate());
LOGGER.debug(String.format("Current version published at: %s", meta.getPublishedTimestamp()));
}
} catch (IOException ex) {
handleRequestException(LOGGER, ex);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 620
| 633
| 1,253
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/GoModulesMetaAnalyzer.java
|
GoModulesMetaAnalyzer
|
analyze
|
class GoModulesMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(GoModulesMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://proxy.golang.org";
private static final String API_URL = "/%s/%s/@latest";
GoModulesMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
@Override
public RepositoryType supportedRepositoryType() {
return RepositoryType.GO_MODULES;
}
@Override
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.GOLANG.equals(component.getPurl().getType());
}
@Override
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
/**
* "To avoid ambiguity when serving from case-insensitive file systems, the $module [...] elements are
* case-encoded by replacing every uppercase letter with an exclamation mark followed by the corresponding
* lower-case letter."
*
* @param modulePath The module path to encode
* @return The encoded module path
*/
String caseEncode(final String modulePath) {
return modulePath.replaceAll("([A-Z])", "!$1").toLowerCase();
}
}
|
final var meta = new MetaModel(component);
if (component.getPurl() == null || component.getPurl().getNamespace() == null) {
return meta;
}
final String url = String.format(baseUrl + API_URL, caseEncode(component.getPurl().getNamespace()), caseEncode(component.getPurl().getName()));
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity()!=null) {
String responseString = EntityUtils.toString(response.getEntity());
final var responseJson = new JSONObject(responseString);
meta.setLatestVersion(responseJson.getString("Version"));
// Module versions are prefixed with "v" in the Go ecosystem.
// Because some services (like OSS Index as of July 2021) do not support
// versions with this prefix, components in DT may not be prefixed either.
//
// In order to make the versions comparable still, we strip the "v" prefix as well,
// if it was done for the analyzed component.
if (component.getVersion() != null && !component.getVersion().startsWith("v")) {
meta.setLatestVersion(StringUtils.stripStart(meta.getLatestVersion(), "v"));
}
final String commitTimestamp = responseJson.getString("Time");
if (StringUtils.isNotBlank(commitTimestamp)) { // Time is optional
meta.setPublishedTimestamp(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(commitTimestamp));
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException | ParseException e) {
handleRequestException(LOGGER, e);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
return meta;
| 358
| 523
| 881
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/HackageMetaAnalyzer.java
|
HackageMetaAnalyzer
|
analyze
|
class HackageMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(HackageMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://hackage.haskell.org/";
HackageMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.HACKAGE;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(Component component) {
final var purl = component.getPurl();
return purl != null && "hackage".equals(purl.getType());
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final var meta = new MetaModel(component);
final var purl = component.getPurl();
if (purl != null) {
final var url = baseUrl + "/package/" + purl.getName() + "/preferred";
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final var entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity);
final var deserialized = new JSONObject(responseString);
final var preferred = deserialized.getJSONArray("normal-version");
// the latest version is the first in the list
if (preferred != null) {
final var latest = preferred.getString(0);
meta.setLatestVersion(latest);
}
// the hackage API doesn't expose the "published_at" information
// we could use https://flora.pm/experimental/packages/{namespace}/{packageName}
// but it appears this isn't reliable yet
}
} else {
var statusLine = response.getStatusLine();
handleUnexpectedHttpResponse(LOGGER, url, statusLine.getStatusCode(), statusLine.getReasonPhrase(), component);
}
} catch (IOException ex) {
handleRequestException(LOGGER, ex);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 237
| 381
| 618
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/HexMetaAnalyzer.java
|
HexMetaAnalyzer
|
analyze
|
class HexMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(HexMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://hex.pm";
private static final String API_URL = "/api/packages/%s";
HexMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.HEX.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.HEX;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String packageName;
if (component.getPurl().getNamespace() != null) {
packageName = component.getPurl().getNamespace().replace("@", "%40") + "%2F" + component.getPurl().getName();
} else {
packageName = component.getPurl().getName();
}
final String url = String.format(baseUrl + API_URL, packageName);
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity()!=null) {
String responseString = EntityUtils.toString(response.getEntity());
var jsonObject = new JSONObject(responseString);
final JSONArray releasesArray = jsonObject.getJSONArray("releases");
if (releasesArray.length() > 0) {
// The first one in the array is always the latest version
final JSONObject release = releasesArray.getJSONObject(0);
final String latest = release.optString("version", null);
meta.setLatestVersion(latest);
final String insertedAt = release.optString("inserted_at", null);
if (insertedAt != null) {
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
final Date published = dateFormat.parse(insertedAt);
meta.setPublishedTimestamp(published);
} catch (ParseException e) {
LOGGER.warn("An error occurred while parsing published time", e);
}
}
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException e) {
handleRequestException(LOGGER, e);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 245
| 535
| 780
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/MavenMetaAnalyzer.java
|
MavenMetaAnalyzer
|
analyze
|
class MavenMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(MavenMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://repo1.maven.org/maven2";
private static final String REPO_METADATA_URL = "/%s/maven-metadata.xml";
MavenMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.MAVEN.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.MAVEN;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String mavenGavUrl = component.getPurl().getNamespace().replaceAll("\\.", "/") + "/" + component.getPurl().getName();
final String url = String.format(baseUrl + REPO_METADATA_URL, mavenGavUrl);
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final HttpEntity entity = response.getEntity();
if (entity != null) {
try (InputStream in = entity.getContent()) {
final Document document = XmlUtil.buildSecureDocumentBuilder().parse(in);
final var xpathFactory = XPathFactory.newInstance();
final XPath xpath = xpathFactory.newXPath();
final XPathExpression releaseExpression = xpath.compile("/metadata/versioning/release");
final XPathExpression latestExpression = xpath.compile("/metadata/versioning/latest");
final var release = (String) releaseExpression.evaluate(document, XPathConstants.STRING);
final String latest = (String) latestExpression.evaluate(document, XPathConstants.STRING);
final XPathExpression lastUpdatedExpression = xpath.compile("/metadata/versioning/lastUpdated");
final var lastUpdated = (String) lastUpdatedExpression.evaluate(document, XPathConstants.STRING);
meta.setLatestVersion(release != null ? release : latest);
if (lastUpdated != null) {
meta.setPublishedTimestamp(DateUtil.parseDate(lastUpdated));
}
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException | ParserConfigurationException | SAXException | XPathExpressionException e) {
handleRequestException(LOGGER, e);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 260
| 533
| 793
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/NixpkgsMetaAnalyzer.java
|
NixpkgsMetaAnalyzer
|
analyze
|
class NixpkgsMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(NixpkgsMetaAnalyzer.class);
private static final String DEFAULT_CHANNEL_URL = "https://channels.nixos.org/nixpkgs-unstable/packages.json.br";
private static final Cache<String, Map<String, String>> CACHE = Caffeine.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.maximumSize(1)
.build();
NixpkgsMetaAnalyzer() {
this.baseUrl = DEFAULT_CHANNEL_URL;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(Component component) {<FILL_FUNCTION_BODY>}
private CloseableHttpResponse processHttpRequest5(CloseableHttpClient client) throws IOException {
try {
URIBuilder uriBuilder = new URIBuilder(baseUrl);
final HttpGet request = new HttpGet(uriBuilder.build().toString());
request.addHeader("accept", "application/json");
return client.execute(request);
} catch (URISyntaxException ex) {
handleRequestException(LOGGER, ex);
return null;
}
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.NIXPKGS;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(Component component) {
final var purl = component.getPurl();
return purl != null && "nixpkgs".equals(purl.getType());
}
}
|
Map<String, String> latestVersions = CACHE.get("nixpkgs", cacheKey -> {
final var versions = new HashMap<String, String>();
try (final CloseableHttpClient client = HttpClients.createDefault()) {
try (final CloseableHttpResponse packagesResponse = processHttpRequest5(client)) {
if (packagesResponse != null && packagesResponse.getCode() == HttpStatus.SC_OK) {
var reader = new BufferedReader(new InputStreamReader(packagesResponse.getEntity().getContent()));
var packages = new JSONObject(new JSONTokener(reader)).getJSONObject("packages").toMap().values();
packages.forEach(pkg -> {
// FUTUREWORK(mangoiv): there are potentially packages with the same pname
if (pkg instanceof HashMap jsonPkg) {
final var pname = jsonPkg.get("pname");
final var version = jsonPkg.get("version");
versions.putIfAbsent((String) pname, (String) version);
}
});
}
}
} catch (IOException ex) {
LOGGER.debug(ex.toString());
handleRequestException(LOGGER, ex);
} catch (Exception ex) {
LOGGER.debug(ex.toString());
throw new MetaAnalyzerException(ex);
}
return versions;
});
final var meta = new MetaModel(component);
final var purl = component.getPurl();
if (purl != null) {
final var newerVersion = latestVersions.get(purl.getName());
if (newerVersion != null) {
meta.setLatestVersion(newerVersion);
}
}
return meta;
| 435
| 435
| 870
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/NpmMetaAnalyzer.java
|
NpmMetaAnalyzer
|
analyze
|
class NpmMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(NpmMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://registry.npmjs.org";
private static final String API_URL = "/-/package/%s/dist-tags";
NpmMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.NPM.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.NPM;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String packageName;
if (component.getPurl().getNamespace() != null) {
packageName = "%s/%s".formatted(component.getPurl().getNamespace(), component.getPurl().getName());
} else {
packageName = component.getPurl().getName();
}
final String url = String.format(baseUrl + API_URL, urlEncode(packageName));
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity()!=null) {
String responseString = EntityUtils.toString(response.getEntity());
var jsonObject = new JSONObject(responseString);
final String latest = jsonObject.optString("latest");
if (latest != null) {
meta.setLatestVersion(latest);
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException e) {
handleRequestException(LOGGER, e);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 253
| 359
| 612
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/NugetMetaAnalyzer.java
|
NugetMetaAnalyzer
|
parseUpdateTime
|
class NugetMetaAnalyzer extends AbstractMetaAnalyzer {
public static final DateFormat[] SUPPORTED_DATE_FORMATS = new DateFormat[]{
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"),
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
};
private static final Logger LOGGER = Logger.getLogger(NugetMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://api.nuget.org";
private static final String INDEX_URL = "/v3/index.json";
private static final String DEFAULT_VERSION_QUERY_ENDPOINT = "/v3-flatcontainer/%s/index.json";
private static final String DEFAULT_REGISTRATION_ENDPOINT = "/v3/registration5-semver1/%s/%s.json";
private String versionQueryUrl;
private String registrationUrl;
NugetMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
// Set defaults that work with NuGet.org just in case the index endpoint is not available
this.versionQueryUrl = baseUrl + DEFAULT_VERSION_QUERY_ENDPOINT;
this.registrationUrl = baseUrl + DEFAULT_REGISTRATION_ENDPOINT;
}
@Override
public void setRepositoryBaseUrl(String baseUrl) {
super.setRepositoryBaseUrl(baseUrl);
initializeEndpoints();
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.NUGET.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.NUGET;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
if (performVersionCheck(meta, component)) {
performLastPublishedCheck(meta, component);
}
}
return meta;
}
private boolean performVersionCheck(final MetaModel meta, final Component component) {
final String url = String.format(versionQueryUrl, component.getPurl().getName().toLowerCase());
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity() != null) {
String responseString = EntityUtils.toString(response.getEntity());
var jsonObject = new JSONObject(responseString);
final JSONArray versions = jsonObject.getJSONArray("versions");
final String latest = findLatestVersion(versions); // get the last version in the array
meta.setLatestVersion(latest);
}
return true;
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException e) {
handleRequestException(LOGGER, e);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
return false;
}
private String findLatestVersion(JSONArray versions) {
if (versions.length() < 1) {
return null;
}
ComparableVersion latestVersion = new ComparableVersion(versions.getString(0));
for (int i = 1; i < versions.length(); i++) {
ComparableVersion version = new ComparableVersion(versions.getString(i));
if (version.compareTo(latestVersion) > 0) {
latestVersion = version;
}
}
return latestVersion.toString();
}
private boolean performLastPublishedCheck(final MetaModel meta, final Component component) {
final String url = String.format(registrationUrl, component.getPurl().getName().toLowerCase(), meta.getLatestVersion());
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity() != null) {
String stringResponse = EntityUtils.toString(response.getEntity());
if (!stringResponse.equalsIgnoreCase("") && !stringResponse.equalsIgnoreCase("{}")) {
JSONObject jsonResponse = new JSONObject(stringResponse);
final String updateTime = jsonResponse.optString("published", null);
if (updateTime != null) {
meta.setPublishedTimestamp(parseUpdateTime(updateTime));
}
return true;
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException e) {
handleRequestException(LOGGER, e);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
return false;
}
private void initializeEndpoints() {
final String url = baseUrl + INDEX_URL;
try {
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if(response.getEntity()!=null){
String responseString = EntityUtils.toString(response.getEntity());
JSONObject responseJson = new JSONObject(responseString);
final JSONArray resources = responseJson.getJSONArray("resources");
final JSONObject packageBaseResource = findResourceByType(resources, "PackageBaseAddress");
final JSONObject registrationsBaseResource = findResourceByType(resources, "RegistrationsBaseUrl");
if (packageBaseResource != null && registrationsBaseResource != null) {
versionQueryUrl = packageBaseResource.getString("@id") + "%s/index.json";
registrationUrl = registrationsBaseResource.getString("@id") + "%s/%s.json";
}
}
}
}
} catch (IOException e) {
handleRequestException(LOGGER, e);
}
}
private JSONObject findResourceByType(JSONArray resources, String type) {
for (int i = 0; i < resources.length(); i++) {
String resourceType = resources.getJSONObject(i).getString("@type");
if (resourceType != null && resourceType.toLowerCase().startsWith(type.toLowerCase())) {
return resources.getJSONObject(i);
}
}
return null;
}
private Date parseUpdateTime(String updateTime) {<FILL_FUNCTION_BODY>}
}
|
if (updateTime == null) {
return null;
}
// NuGet repositories may use differing date formats, so we try a few date formats that are commonly used until the right one is found.
for (DateFormat dateFormat : SUPPORTED_DATE_FORMATS) {
try {
return dateFormat.parse(updateTime);
} catch (ParseException e) {
LOGGER.warn("An error occurred while parsing upload time for a NuGet component - Repo returned: " + updateTime);
}
}
return null;
| 1,736
| 142
| 1,878
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/repositories/PypiMetaAnalyzer.java
|
PypiMetaAnalyzer
|
analyze
|
class PypiMetaAnalyzer extends AbstractMetaAnalyzer {
private static final Logger LOGGER = Logger.getLogger(PypiMetaAnalyzer.class);
private static final String DEFAULT_BASE_URL = "https://pypi.org";
private static final String API_URL = "/pypi/%s/json";
PypiMetaAnalyzer() {
this.baseUrl = DEFAULT_BASE_URL;
}
/**
* {@inheritDoc}
*/
public boolean isApplicable(final Component component) {
return component.getPurl() != null && PackageURL.StandardTypes.PYPI.equals(component.getPurl().getType());
}
/**
* {@inheritDoc}
*/
public RepositoryType supportedRepositoryType() {
return RepositoryType.PYPI;
}
/**
* {@inheritDoc}
*/
public MetaModel analyze(final Component component) {<FILL_FUNCTION_BODY>}
}
|
final MetaModel meta = new MetaModel(component);
if (component.getPurl() != null) {
final String url = String.format(baseUrl + API_URL, component.getPurl().getName());
try (final CloseableHttpResponse response = processHttpRequest(url)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
if (response.getEntity() != null) {
String stringResponse = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(stringResponse);
final JSONObject info = jsonObject.getJSONObject("info");
final String latest = info.optString("version", null);
if (latest != null) {
meta.setLatestVersion(latest);
final JSONObject releases = jsonObject.getJSONObject("releases");
final JSONArray latestArray = releases.getJSONArray(latest);
if (latestArray.length() > 0) {
final JSONObject release = latestArray.getJSONObject(0);
final String updateTime = release.optString("upload_time", null);
if (updateTime != null) {
final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
final Date published = dateFormat.parse(updateTime);
meta.setPublishedTimestamp(published);
} catch (ParseException e) {
LOGGER.warn("An error occurred while parsing upload time", e);
}
}
}
}
}
} else {
handleUnexpectedHttpResponse(LOGGER, url, response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), component);
}
} catch (IOException e) {
handleRequestException(LOGGER, e);
} catch (Exception ex) {
throw new MetaAnalyzerException(ex);
}
}
return meta;
| 251
| 483
| 734
|
<methods>public non-sealed void <init>() ,public void setRepositoryBaseUrl(java.lang.String) ,public void setRepositoryUsernameAndPassword(java.lang.String, java.lang.String) <variables>protected java.lang.String baseUrl,protected java.lang.String password,protected java.lang.String username
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/scanners/AbstractVulnerableSoftwareAnalysisTask.java
|
AbstractVulnerableSoftwareAnalysisTask
|
compareVersions
|
class AbstractVulnerableSoftwareAnalysisTask extends BaseComponentAnalyzerTask {
/**
* Analyzes the targetVersion against a list of VulnerableSoftware objects which may contain
* specific versions or version ranges. For every match, every vulnerability associated with
* the VulnerableSoftware object will be applied to the specified component.
*
* @param qm the QueryManager to use
* @param vsList a list of VulnerableSoftware objects
* @param targetVersion the version of the component
* @param component the component being analyzed
*/
protected void analyzeVersionRange(final QueryManager qm, final List<VulnerableSoftware> vsList,
final Cpe targetCpe, final String targetVersion, final Component component,
final VulnerabilityAnalysisLevel vulnerabilityAnalysisLevel) {
for (final VulnerableSoftware vs : vsList) {
final Boolean isCpeMatch = maybeMatchCpe(vs, targetCpe, targetVersion);
if ((isCpeMatch == null || isCpeMatch) && compareVersions(vs, targetVersion)) {
if (vs.getVulnerabilities() != null) {
for (final Vulnerability vulnerability : vs.getVulnerabilities()) {
NotificationUtil.analyzeNotificationCriteria(qm, vulnerability, component, vulnerabilityAnalysisLevel);
qm.addVulnerability(vulnerability, component, this.getAnalyzerIdentity());
}
}
}
}
}
private Boolean maybeMatchCpe(final VulnerableSoftware vs, final Cpe targetCpe, final String targetVersion) {
if (targetCpe == null || vs.getCpe23() == null) {
return null;
}
final List<Relation> relations = List.of(
Cpe.compareAttribute(vs.getPart(), targetCpe.getPart().getAbbreviation()),
Cpe.compareAttribute(vs.getVendor(), targetCpe.getVendor()),
Cpe.compareAttribute(vs.getProduct(), targetCpe.getProduct()),
Cpe.compareAttribute(vs.getVersion(), targetVersion),
Cpe.compareAttribute(vs.getUpdate(), targetCpe.getUpdate()),
Cpe.compareAttribute(vs.getEdition(), targetCpe.getEdition()),
Cpe.compareAttribute(vs.getLanguage(), targetCpe.getLanguage()),
Cpe.compareAttribute(vs.getSwEdition(), targetCpe.getSwEdition()),
Cpe.compareAttribute(vs.getTargetSw(), targetCpe.getTargetSw()),
Cpe.compareAttribute(vs.getTargetHw(), targetCpe.getTargetHw()),
Cpe.compareAttribute(vs.getOther(), targetCpe.getOther())
);
if (relations.contains(Relation.DISJOINT)) {
return false;
}
boolean isMatch = true;
// Mixed SUBSET / SUPERSET relations in the vendor and product attribute are prone
// to false positives: https://github.com/DependencyTrack/dependency-track/issues/3178
final Relation vendorRelation = relations.get(1);
final Relation productRelation = relations.get(2);
isMatch &= !(vendorRelation == Relation.SUBSET && productRelation == Relation.SUPERSET);
isMatch &= !(vendorRelation == Relation.SUPERSET && productRelation == Relation.SUBSET);
if (!isMatch) {
Logger.getLogger(getClass()).debug("%s: Dropped match with %s due to ambiguous vendor/product relation"
.formatted(targetCpe.toCpe23FS(), vs.getCpe23()));
}
return isMatch;
}
/**
* Evaluates the target against the version and version range checks:
* versionEndExcluding, versionStartExcluding versionEndIncluding, and
* versionStartIncluding.
*
* @param vs a reference to the vulnerable software to compare
* @param targetVersion the version to compare
* @return <code>true</code> if the target version is matched; otherwise
* <code>false</code>
* <p>
* Ported from Dependency-Check v5.2.1
*/
private static boolean compareVersions(VulnerableSoftware vs, String targetVersion) {<FILL_FUNCTION_BODY>}
}
|
//if any of the four conditions will be evaluated - then true;
boolean result = (vs.getVersionEndExcluding() != null && !vs.getVersionEndExcluding().isEmpty())
|| (vs.getVersionStartExcluding() != null && !vs.getVersionStartExcluding().isEmpty())
|| (vs.getVersionEndIncluding() != null && !vs.getVersionEndIncluding().isEmpty())
|| (vs.getVersionStartIncluding() != null && !vs.getVersionStartIncluding().isEmpty());
// Modified from original by Steve Springett
// Added null check: vs.getVersion() != null as purl sources that use version ranges may not have version populated.
if (!result && vs.getVersion() != null && Cpe.compareAttribute(vs.getVersion(), targetVersion) != Relation.DISJOINT) {
return true;
}
final ComponentVersion target = new ComponentVersion(targetVersion);
if (target.getVersionParts().isEmpty()) {
return false;
}
if (result && vs.getVersionEndExcluding() != null && !vs.getVersionEndExcluding().isEmpty()) {
final ComponentVersion endExcluding = new ComponentVersion(vs.getVersionEndExcluding());
result = endExcluding.compareTo(target) > 0;
}
if (result && vs.getVersionStartExcluding() != null && !vs.getVersionStartExcluding().isEmpty()) {
final ComponentVersion startExcluding = new ComponentVersion(vs.getVersionStartExcluding());
result = startExcluding.compareTo(target) < 0;
}
if (result && vs.getVersionEndIncluding() != null && !vs.getVersionEndIncluding().isEmpty()) {
final ComponentVersion endIncluding = new ComponentVersion(vs.getVersionEndIncluding());
result &= endIncluding.compareTo(target) >= 0;
}
if (result && vs.getVersionStartIncluding() != null && !vs.getVersionStartIncluding().isEmpty()) {
final ComponentVersion startIncluding = new ComponentVersion(vs.getVersionStartIncluding());
result &= startIncluding.compareTo(target) <= 0;
}
return result;
| 1,107
| 542
| 1,649
|
<methods>public non-sealed void <init>() <variables>private final Logger LOGGER
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/scanners/BaseComponentAnalyzerTask.java
|
BaseComponentAnalyzerTask
|
isCacheCurrent
|
class BaseComponentAnalyzerTask implements ScanTask {
private final Logger LOGGER = Logger.getLogger(this.getClass()); // We dont want this class reporting the logger
protected boolean isEnabled(final ConfigPropertyConstants configPropertyConstants) {
try (QueryManager qm = new QueryManager()) {
final ConfigProperty property = qm.getConfigProperty(
configPropertyConstants.getGroupName(), configPropertyConstants.getPropertyName()
);
if (property != null && ConfigProperty.PropertyType.BOOLEAN == property.getPropertyType()) {
return BooleanUtil.valueOf(property.getPropertyValue());
}
return false;
}
}
protected boolean isCacheCurrent(Vulnerability.Source source, String targetHost, String target) {<FILL_FUNCTION_BODY>}
protected void applyAnalysisFromCache(Vulnerability.Source source, String targetHost, String target, Component component,
AnalyzerIdentity analyzerIdentity, VulnerabilityAnalysisLevel vulnerabilityAnalysisLevel) {
try (QueryManager qm = new QueryManager()) {
final ComponentAnalysisCache cac = qm.getComponentAnalysisCache(ComponentAnalysisCache.CacheType.VULNERABILITY, targetHost, source.name(), target);
if (cac != null) {
final JsonObject result = cac.getResult();
if (result != null) {
final JsonArray vulns = result.getJsonArray("vulnIds");
if (vulns != null) {
for (JsonNumber vulnId : vulns.getValuesAs(JsonNumber.class)) {
final Vulnerability vulnerability;
vulnerability = qm.getObjectById(Vulnerability.class, vulnId.longValue());
final Component c = qm.getObjectByUuid(Component.class, component.getUuid());
if (c == null) continue;
if (vulnerability != null) {
NotificationUtil.analyzeNotificationCriteria(qm, vulnerability, component, vulnerabilityAnalysisLevel);
qm.addVulnerability(vulnerability, c, analyzerIdentity);
}
}
}
}
}
}
}
protected synchronized void updateAnalysisCacheStats(QueryManager qm, Vulnerability.Source source, String
targetHost, String target, JsonObject result) {
qm.updateComponentAnalysisCache(ComponentAnalysisCache.CacheType.VULNERABILITY, targetHost, source.name(), target, new Date(), result);
}
protected void addVulnerabilityToCache(Component component, Vulnerability vulnerability) {
if (component.getCacheResult() == null) {
final JsonArray vulns = Json.createArrayBuilder().add(vulnerability.getId()).build();
final JsonObject result = Json.createObjectBuilder().add("vulnIds", vulns).build();
component.setCacheResult(result);
} else {
final JsonObject result = component.getCacheResult();
final JsonArrayBuilder vulnsBuilder = Json.createArrayBuilder(result.getJsonArray("vulnIds"));
final JsonArray vulns = vulnsBuilder.add(Json.createValue(vulnerability.getId())).build();
component.setCacheResult(Json.createObjectBuilder(result).add("vulnIds", vulns).build());
}
}
protected void addNoVulnerabilityToCache(final Component component) {
component.setCacheResult(Json.createObjectBuilder()
.add("vulnIds", Json.createArrayBuilder())
.build());
}
protected void handleUnexpectedHttpResponse(final Logger logger, String url, final int statusCode,
final String statusText) {
logger.error("HTTP Status : " + statusCode + " " + statusText);
logger.error(" - Analyzer URL : " + url);
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.ANALYZER)
.title(NotificationConstants.Title.ANALYZER_ERROR)
.content("An error occurred while communicating with a vulnerability intelligence source. URL: " + url + " HTTP Status: " + statusCode + ". Check log for details.")
.level(NotificationLevel.ERROR)
);
}
protected void handleRequestException(final Logger logger, final Throwable e) {
logger.error("Request failure", e);
Notification.dispatch(new Notification()
.scope(NotificationScope.SYSTEM)
.group(NotificationGroup.ANALYZER)
.title(NotificationConstants.Title.ANALYZER_ERROR)
.content("An error occurred while communicating with a vulnerability intelligence source. Check log for details. " + e.getMessage())
.level(NotificationLevel.ERROR)
);
}
}
|
try (QueryManager qm = new QueryManager()) {
boolean isCacheCurrent = false;
ConfigProperty cacheClearPeriod = qm.getConfigProperty(ConfigPropertyConstants.SCANNER_ANALYSIS_CACHE_VALIDITY_PERIOD.getGroupName(), ConfigPropertyConstants.SCANNER_ANALYSIS_CACHE_VALIDITY_PERIOD.getPropertyName());
long cacheValidityPeriod = Long.parseLong(cacheClearPeriod.getPropertyValue());
ComponentAnalysisCache cac = qm.getComponentAnalysisCache(ComponentAnalysisCache.CacheType.VULNERABILITY, targetHost, source.name(), target);
if (cac != null) {
final Date now = new Date();
if (now.getTime() > cac.getLastOccurrence().getTime()) {
final long delta = now.getTime() - cac.getLastOccurrence().getTime();
isCacheCurrent = delta <= cacheValidityPeriod;
}
}
if (isCacheCurrent) {
LOGGER.debug("Cache is current. Skipping analysis. (source: " + source + " / targetHost: " + targetHost + " / target: " + target);
} else {
LOGGER.debug("Cache is not current. Analysis should be performed (source: " + source + " / targetHost: " + targetHost + " / target: " + target);
}
return isCacheCurrent;
}
| 1,193
| 349
| 1,542
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/scanners/InternalAnalysisTask.java
|
InternalAnalysisTask
|
versionRangeAnalysis
|
class InternalAnalysisTask extends AbstractVulnerableSoftwareAnalysisTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(InternalAnalysisTask.class);
public AnalyzerIdentity getAnalyzerIdentity() {
return AnalyzerIdentity.INTERNAL_ANALYZER;
}
private VulnerabilityAnalysisLevel vulnerabilityAnalysisLevel;
/**
* {@inheritDoc}
*/
public void inform(final Event e) {
if (e instanceof InternalAnalysisEvent) {
if (!super.isEnabled(ConfigPropertyConstants.SCANNER_INTERNAL_ENABLED)) {
return;
}
final InternalAnalysisEvent event = (InternalAnalysisEvent)e;
vulnerabilityAnalysisLevel = event.getVulnerabilityAnalysisLevel();
LOGGER.info("Starting internal analysis task");
if (event.getComponents().size() > 0) {
analyze(event.getComponents());
}
LOGGER.info("Internal analysis complete");
}
}
/**
* Determines if the {@link InternalAnalysisTask} is capable of analyzing the specified Component.
*
* @param component the Component to analyze
* @return true if InternalAnalysisTask should analyze, false if not
*/
public boolean isCapable(final Component component) {
return component.getCpe() != null || component.getPurl() != null;
}
/**
* Analyzes a list of Components.
* @param components a list of Components
*/
public void analyze(final List<Component> components) {
try (QueryManager qm = new QueryManager()) {
LOGGER.info("Analyzing " + components.size() + " component(s)");
for (final Component c : components) {
final Component component = qm.getObjectByUuid(Component.class, c.getUuid()); // Refresh component and attach to current pm.
if (component == null) continue;
versionRangeAnalysis(qm, component);
}
}
}
private void versionRangeAnalysis(final QueryManager qm, final Component component) {<FILL_FUNCTION_BODY>}
}
|
final boolean fuzzyEnabled = super.isEnabled(ConfigPropertyConstants.SCANNER_INTERNAL_FUZZY_ENABLED) &&
(!component.isInternal() || !super.isEnabled(ConfigPropertyConstants.SCANNER_INTERNAL_FUZZY_EXCLUDE_INTERNAL));
final boolean excludeComponentsWithPurl = super.isEnabled(ConfigPropertyConstants.SCANNER_INTERNAL_FUZZY_EXCLUDE_PURL);
us.springett.parsers.cpe.Cpe parsedCpe = null;
if (component.getCpe() != null) {
try {
parsedCpe = CpeParser.parse(component.getCpe());
} catch (CpeParsingException e) {
LOGGER.warn("An error occurred while parsing: " + component.getCpe() + " - The CPE is invalid and will be discarded. " + e.getMessage());
}
}
List<VulnerableSoftware> vsList = Collections.emptyList();
String componentVersion;
if (parsedCpe != null) {
componentVersion = parsedCpe.getVersion();
} else if (component.getPurl() != null) {
componentVersion = component.getPurl().getVersion();
} else {
// Catch cases where the CPE couldn't be parsed and no PURL exists.
// Should be rare, but could lead to NPEs later.
LOGGER.debug("Neither CPE nor PURL of component " + component.getUuid() + " provide a version - skipping analysis");
return;
}
// In some cases, componentVersion may be null, such as when a Package URL does not have a version specified
if (componentVersion == null) {
return;
}
// https://github.com/DependencyTrack/dependency-track/issues/1574
// Some ecosystems use the "v" version prefix (e.g. v1.2.3) for their components.
// However, both the NVD and GHSA store versions without that prefix.
// For this reason, the prefix is stripped before running analyzeVersionRange.
//
// REVISIT THIS WHEN ADDING NEW VULNERABILITY SOURCES!
if (componentVersion.length() > 1 && componentVersion.startsWith("v")) {
if (componentVersion.matches("v0.0.0-\\d{14}-[a-f0-9]{12}")) {
componentVersion = componentVersion.substring(7,11) + "-" + componentVersion.substring(11,13) + "-" + componentVersion.substring(13,15);
} else {
componentVersion = componentVersion.substring(1);
}
}
if (parsedCpe != null) {
vsList = qm.getAllVulnerableSoftware(parsedCpe.getPart().getAbbreviation(), parsedCpe.getVendor(), parsedCpe.getProduct(), component.getPurl());
} else {
vsList = qm.getAllVulnerableSoftware(null, null, null, component.getPurl());
}
if (fuzzyEnabled && vsList.isEmpty()) {
FuzzyVulnerableSoftwareSearchManager fm = new FuzzyVulnerableSoftwareSearchManager(excludeComponentsWithPurl);
vsList = fm.fuzzyAnalysis(qm, component, parsedCpe);
}
super.analyzeVersionRange(qm, vsList, parsedCpe, componentVersion, component, vulnerabilityAnalysisLevel);
| 537
| 900
| 1,437
|
<methods>public non-sealed void <init>() <variables>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/tasks/scanners/VulnDbAnalysisTask.java
|
VulnDbAnalysisTask
|
inform
|
class VulnDbAnalysisTask extends BaseComponentAnalyzerTask implements Subscriber {
private static final Logger LOGGER = Logger.getLogger(VulnDbAnalysisTask.class);
private static final int PAGE_SIZE = 100;
private VulnerabilityAnalysisLevel vulnerabilityAnalysisLevel;
private String apiConsumerKey;
private String apiConsumerSecret;
private String apiBaseUrl;
@Override
public AnalyzerIdentity getAnalyzerIdentity() {
return AnalyzerIdentity.VULNDB_ANALYZER;
}
public VulnDbAnalysisTask(String apiBaseUrl) {
this.apiBaseUrl = apiBaseUrl;
}
public VulnDbAnalysisTask() {
this("https://vulndb.cyberriskanalytics.com");
}
/**
* {@inheritDoc}
*/
@Override
public void inform(final Event e) {<FILL_FUNCTION_BODY>}
/**
* Determines if the {@link VulnDbAnalysisTask} is capable of analyzing the specified Component.
*
* @param component the Component to analyze
* @return true if VulnDbAnalysisTask should analyze, false if not
*/
@Override
public boolean isCapable(final Component component) {
return component.getCpe() != null;
}
/**
* Analyzes a list of Components.
*
* @param components a list of Components
*/
@Override
public void analyze(final List<Component> components) {
final var api = new VulnDbClient(this.apiConsumerKey, this.apiConsumerSecret, this.apiBaseUrl);
for (final Component component : components) {
if (isCacheCurrent(Vulnerability.Source.VULNDB, apiBaseUrl, component.getCpe())) {
applyAnalysisFromCache(Vulnerability.Source.VULNDB, apiBaseUrl, component.getCpe(), component, AnalyzerIdentity.VULNDB_ANALYZER, vulnerabilityAnalysisLevel);
} else if (!component.isInternal() && isCapable(component)
&& !isCacheCurrent(Vulnerability.Source.VULNDB, apiBaseUrl, component.getCpe())) {
if (!component.isInternal() && isCapable(component)
&& !isCacheCurrent(Vulnerability.Source.VULNDB, apiBaseUrl, component.getCpe())) {
int page = 1;
boolean more = true;
while (more) {
try {
final Results results = api.getVulnerabilitiesByCpe(component.getCpe(), PAGE_SIZE, page);
if (results.isSuccessful()) {
more = processResults(results, component);
page++;
} else {
LOGGER.warn(results.getErrorCondition());
handleRequestException(LOGGER, new Exception(results.getErrorCondition()));
return;
}
} catch (IOException | OAuthMessageSignerException | OAuthExpectationFailedException |
URISyntaxException | OAuthCommunicationException ex) {
handleRequestException(LOGGER, ex);
}
}
}
}
}
}
@SuppressWarnings("unchecked")
private boolean processResults(final Results results, final Component component) {
try (final QueryManager qm = new QueryManager()) {
final Component vulnerableComponent = qm.getObjectByUuid(Component.class, component.getUuid()); // Refresh component and attach to current pm.
for (org.dependencytrack.parser.vulndb.model.Vulnerability vulnDbVuln : (List<org.dependencytrack.parser.vulndb.model.Vulnerability>) results.getResults()) {
Vulnerability vulnerability = qm.getVulnerabilityByVulnId(Vulnerability.Source.VULNDB, String.valueOf(vulnDbVuln.id()));
if (vulnerability == null) {
vulnerability = qm.createVulnerability(ModelConverter.convert(qm, vulnDbVuln), false);
} else {
vulnerability = qm.synchronizeVulnerability(ModelConverter.convert(qm, vulnDbVuln), false);
}
NotificationUtil.analyzeNotificationCriteria(qm, vulnerability, vulnerableComponent, vulnerabilityAnalysisLevel);
qm.addVulnerability(vulnerability, vulnerableComponent, this.getAnalyzerIdentity());
addVulnerabilityToCache(vulnerableComponent, vulnerability);
}
updateAnalysisCacheStats(qm, Vulnerability.Source.VULNDB, apiBaseUrl, vulnerableComponent.getCpe(), vulnerableComponent.getCacheResult());
return results.getPage() * PAGE_SIZE < results.getTotal();
}
}
}
|
if (e instanceof VulnDbAnalysisEvent) {
if (!super.isEnabled(ConfigPropertyConstants.SCANNER_VULNDB_ENABLED)) {
return;
}
try (QueryManager qm = new QueryManager()) {
final ConfigProperty apiConsumerKey = qm.getConfigProperty(
ConfigPropertyConstants.SCANNER_VULNDB_OAUTH1_CONSUMER_KEY.getGroupName(),
ConfigPropertyConstants.SCANNER_VULNDB_OAUTH1_CONSUMER_KEY.getPropertyName()
);
final ConfigProperty apiConsumerSecret = qm.getConfigProperty(
ConfigPropertyConstants.SCANNER_VULNDB_OAUTH1_CONSUMER_SECRET.getGroupName(),
ConfigPropertyConstants.SCANNER_VULNDB_OAUTH1_CONSUMER_SECRET.getPropertyName()
);
if (this.apiBaseUrl == null) {
LOGGER.warn("No API base URL provided; Skipping");
return;
}
if (apiConsumerKey == null || apiConsumerKey.getPropertyValue() == null) {
LOGGER.warn("An OAuth 1.0a consumer key has not been specified for use with VulnDB. Skipping");
return;
}
if (apiConsumerSecret == null || apiConsumerSecret.getPropertyValue() == null) {
LOGGER.warn("An OAuth 1.0a consumer secret has not been specified for use with VulnDB. Skipping");
return;
}
this.apiConsumerKey = apiConsumerKey.getPropertyValue();
try {
this.apiConsumerSecret = DataEncryption.decryptAsString(apiConsumerSecret.getPropertyValue());
} catch (Exception ex) {
LOGGER.error("An error occurred decrypting the VulnDB consumer secret. Skipping", ex);
return;
}
}
final var event = (VulnDbAnalysisEvent) e;
vulnerabilityAnalysisLevel = event.getVulnerabilityAnalysisLevel();
LOGGER.debug("Starting VulnDB analysis task");
if (!event.getComponents().isEmpty()) {
analyze(event.getComponents());
}
LOGGER.debug("VulnDB analysis complete");
}
| 1,220
| 569
| 1,789
|
<methods>public non-sealed void <init>() <variables>private final Logger LOGGER
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/UpgradeInitializer.java
|
UpgradeInitializer
|
contextInitialized
|
class UpgradeInitializer implements ServletContextListener {
private static final Logger LOGGER = Logger.getLogger(UpgradeInitializer.class);
/**
* {@inheritDoc}
*/
@Override
public void contextInitialized(final ServletContextEvent event) {<FILL_FUNCTION_BODY>}
/**
* {@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.
* <p>
* 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");
return (JDOPersistenceManagerFactory) JDOHelper.getPersistenceManagerFactory(dnProps, "Alpine");
}
}
|
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<String> classNames = new HashSet<>();
classNames.add(InstalledUpgrades.class.getCanonicalName());
classNames.add(SchemaVersion.class.getCanonicalName());
((SchemaAwareStoreManager) ctx.getStoreManager()).createSchemaForClasses(classNames, new Properties());
if (RequirementsVerifier.failedValidation()) {
return;
}
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());
}
}
}
| 677
| 471
| 1,148
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v410/v410Updater.java
|
v410Updater
|
executeUpgrade
|
class v410Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v410Updater.class);
@Override
public String getSchemaVersion() {
return "4.1.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager alpineQueryManager, final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Deleting index directory");
try {
final String INDEX_ROOT_DIR = Config.getInstance().getDataDirectorty().getAbsolutePath() + File.separator + "index";
FileDeleteStrategy.FORCE.delete(new File(INDEX_ROOT_DIR));
} catch (IOException e) {
LOGGER.error("An error occurred deleting the index directory", e);
}
| 115
| 105
| 220
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v4100/v4100Updater.java
|
v4100Updater
|
authRequiredForInternalReposWithCredentials
|
class v4100Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v4100Updater.class);
@Override
public String getSchemaVersion() {
return "4.10.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {
dropCpeTable(connection);
authRequiredForInternalReposWithCredentials(connection);
}
private static void dropCpeTable(final Connection connection) throws Exception {
LOGGER.info("Dropping CPE table");
try (final Statement stmt = connection.createStatement()) {
stmt.execute("DROP TABLE \"CPE\"");
}
}
private static void authRequiredForInternalReposWithCredentials(final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Marking internal repositories with credentials as \"requires authentication\"");
try (final PreparedStatement ps = connection.prepareStatement("""
UPDATE "REPOSITORY"
SET "AUTHENTICATIONREQUIRED" = ?
WHERE "INTERNAL" = ? AND ("USERNAME" IS NOT NULL OR "PASSWORD" IS NOT NULL)
""")) {
ps.setBoolean(1, true);
ps.setBoolean(2, true);
final long updatedRepositories = ps.executeUpdate();
if (updatedRepositories == 0) {
LOGGER.info("No repositories had to be updated");
} else {
LOGGER.info("Updated %d repositories".formatted(updatedRepositories));
}
}
| 233
| 193
| 426
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v4110/v4110Updater.java
|
v4110Updater
|
dropCweTable
|
class v4110Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v4110Updater.class);
@Override
public String getSchemaVersion() {
return "4.11.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {
dropCweTable(connection);
computeVulnerabilitySeverities(connection);
extendPurlColumnLengths(connection);
}
private static void dropCweTable(final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
private static void computeVulnerabilitySeverities(final Connection connection) throws Exception {
// Part of a fix for https://github.com/DependencyTrack/dependency-track/issues/2474.
// Recomputes all database severity values with value NULL of a vulnerability and updates them in the database.
LOGGER.info("Computing severities for vulnerabilities where severity is currently NULL");
try (final PreparedStatement selectStatement = connection.prepareStatement("""
SELECT
"CVSSV2BASESCORE",
"CVSSV3BASESCORE",
"OWASPRRLIKELIHOODSCORE",
"OWASPRRTECHNICALIMPACTSCORE",
"OWASPRRBUSINESSIMPACTSCORE",
"VULNID"
FROM
"VULNERABILITY"
WHERE
"SEVERITY" is NULL
""");
final PreparedStatement updateStatement = connection.prepareStatement("""
UPDATE "VULNERABILITY" SET "SEVERITY" = ? WHERE "VULNID" = ?
""")) {
int batchSize = 0, numBatches = 0, numUpdates = 0;
final ResultSet rs = selectStatement.executeQuery();
while (rs.next()) {
final String vulnID = rs.getString(6);
final Severity severity = VulnerabilityUtil.getSeverity(
rs.getBigDecimal(1),
rs.getBigDecimal(2),
rs.getBigDecimal(3),
rs.getBigDecimal(4),
rs.getBigDecimal(5)
);
updateStatement.setString(1, severity.name());
updateStatement.setString(2, vulnID);
updateStatement.addBatch();
if (++batchSize == 500) {
updateStatement.executeBatch();
numUpdates += batchSize;
numBatches++;
batchSize = 0;
}
}
if (batchSize > 0) {
updateStatement.executeBatch();
numUpdates += batchSize;
numBatches++;
}
LOGGER.info("Updated %d vulnerabilities in %d batches".formatted(numUpdates, numBatches));
}
}
private static void extendPurlColumnLengths(final Connection connection) throws Exception {
LOGGER.info("Extending length of PURL and PURLCOORDINATES columns from 255 to 786");
if (DbUtil.isH2() || DbUtil.isPostgreSQL()) {
try (final Statement statement = connection.createStatement()) {
statement.addBatch("""
ALTER TABLE "COMPONENT" ALTER COLUMN "PURL" SET DATA TYPE VARCHAR(786)""");
statement.addBatch("""
ALTER TABLE "COMPONENT" ALTER COLUMN "PURLCOORDINATES" SET DATA TYPE VARCHAR(786)""");
statement.addBatch("""
ALTER TABLE "COMPONENTANALYSISCACHE" ALTER COLUMN "TARGET" SET DATA TYPE VARCHAR(786)""");
statement.addBatch("""
ALTER TABLE "PROJECT" ALTER COLUMN "PURL" SET DATA TYPE VARCHAR(786)""");
statement.executeBatch();
}
} else if (DbUtil.isMssql()) {
try (final Statement statement = connection.createStatement()) {
statement.addBatch("""
ALTER TABLE "COMPONENT" ALTER COLUMN "PURL" VARCHAR(786) NULL""");
statement.addBatch("""
ALTER TABLE "COMPONENT" ALTER COLUMN "PURLCOORDINATES" VARCHAR(786) NULL""");
statement.addBatch("""
ALTER TABLE "COMPONENTANALYSISCACHE" ALTER COLUMN "TARGET" VARCHAR(786) NOT NULL""");
statement.addBatch("""
ALTER TABLE "PROJECT" ALTER COLUMN "PURL" VARCHAR(786) NULL""");
statement.executeBatch();
}
} else if (DbUtil.isMysql()) {
try (final Statement statement = connection.createStatement()) {
statement.addBatch("""
ALTER TABLE "COMPONENT" MODIFY COLUMN "PURL" VARCHAR(786)""");
statement.addBatch("""
ALTER TABLE "COMPONENT" MODIFY COLUMN "PURLCOORDINATES" VARCHAR(786)""");
statement.addBatch("""
ALTER TABLE "COMPONENTANALYSISCACHE" MODIFY COLUMN "TARGET" VARCHAR(786)""");
statement.addBatch("""
ALTER TABLE "PROJECT" MODIFY COLUMN "PURL" VARCHAR(786)""");
statement.executeBatch();
}
} else {
throw new IllegalStateException("Unrecognized database type");
}
}
}
|
final boolean shouldReEnableAutoCommit = connection.getAutoCommit();
connection.setAutoCommit(false);
try {
// In DT v4.4.x and older, the VULNERABILITY table had a foreign key constraint
// on the CWE table. Drop the constraint, the index on the CWE column, as well as
// the column itself if they still exist.
// Unfortunately, the FK constraint has a generic name, as it was generated by DataNucleus.
try (final Statement stmt = connection.createStatement()) {
LOGGER.info("Dropping foreign key constraint from \"VULNERABILITY\".\"CWE\"");
stmt.executeUpdate("""
ALTER TABLE "VULNERABILITY" DROP CONSTRAINT IF EXISTS "VULNERABILITY_FK1"
""");
if (DbUtil.isH2()) {
LOGGER.info("Dropping index \"VULNERABILITY_CWE_IDX\"");
stmt.executeUpdate("""
DROP INDEX IF EXISTS "VULNERABILITY_CWE_IDX"
""");
} else {
LOGGER.info("Dropping index \"VULNERABILITY\".\"VULNERABILITY_CWE_IDX\"");
stmt.executeUpdate("""
DROP INDEX IF EXISTS "VULNERABILITY"."VULNERABILITY_CWE_IDX"
""");
}
LOGGER.info("Dropping column \"VULNERABILITY\".\"CWE\"");
stmt.executeUpdate("""
ALTER TABLE "VULNERABILITY" DROP COLUMN IF EXISTS "CWE"
""");
LOGGER.info("Dropping table \"CWE\"");
stmt.executeUpdate("""
DROP TABLE IF EXISTS "CWE"
""");
} catch (Exception e) {
connection.rollback();
throw e;
}
connection.commit();
} finally {
if (shouldReEnableAutoCommit) {
connection.setAutoCommit(true);
}
}
| 1,439
| 528
| 1,967
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v420/v420Updater.java
|
v420Updater
|
executeUpgrade
|
class v420Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v420Updater.class);
private static final String STMT_1 = "DELETE FROM \"CONFIGPROPERTY\" WHERE \"GROUPNAME\" = 'integrations' AND \"PROPERTYNAME\" = 'fortify.ssc.username'";
private static final String STMT_2 = "DELETE FROM \"CONFIGPROPERTY\" WHERE \"GROUPNAME\" = 'integrations' AND \"PROPERTYNAME\" = 'fortify.ssc.password'";
@Override
public String getSchemaVersion() {
return "4.2.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager alpineQueryManager, final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Removing legacy Fortify SSC configuration settings");
DbUtil.executeUpdate(connection, STMT_1);
DbUtil.executeUpdate(connection, STMT_2);
| 214
| 52
| 266
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v440/v440Updater.java
|
v440Updater
|
executeUpgrade
|
class v440Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v440Updater.class);
private static final String STMT_1 = "INSERT INTO \"PERMISSION\" (\"NAME\", \"DESCRIPTION\") VALUES (?, ?)";
private static final String STMT_2 = "SELECT \"ID\" FROM \"PERMISSION\" WHERE \"NAME\" = ?";
private static final String STMT_3 = "SELECT \"u\".\"ID\" FROM \"MANAGEDUSER\" AS \"u\" INNER JOIN \"MANAGEDUSERS_PERMISSIONS\" AS \"up\" ON \"up\".\"MANAGEDUSER_ID\" = \"u\".\"ID\" WHERE \"up\".\"PERMISSION_ID\" = %d";
private static final String STMT_4 = "INSERT INTO \"MANAGEDUSERS_PERMISSIONS\" (\"MANAGEDUSER_ID\", \"PERMISSION_ID\") VALUES (?, ?)";
private static final String STMT_5 = "SELECT \"u\".\"ID\" FROM \"LDAPUSER\" AS \"u\" INNER JOIN \"LDAPUSERS_PERMISSIONS\" AS \"up\" ON \"up\".\"LDAPUSER_ID\" = \"u\".\"ID\" WHERE \"up\".\"PERMISSION_ID\" = %d";
private static final String STMT_6 = "INSERT INTO \"LDAPUSERS_PERMISSIONS\" (\"LDAPUSER_ID\", \"PERMISSION_ID\") VALUES (?, ?)";
private static final String STMT_7 = "SELECT \"u\".\"ID\" FROM \"OIDCUSER\" AS \"u\" INNER JOIN \"OIDCUSERS_PERMISSIONS\" AS \"up\" ON \"up\".\"OIDCUSER_ID\" = \"u\".\"ID\" WHERE \"up\".\"PERMISSION_ID\" = %d";
private static final String STMT_8 = "INSERT INTO \"OIDCUSERS_PERMISSIONS\" (\"OIDCUSER_ID\", \"PERMISSION_ID\") VALUES (?, ?)";
private static final String STMT_9 = "SELECT \"t\".\"ID\" FROM \"TEAM\" AS \"t\" INNER JOIN \"TEAMS_PERMISSIONS\" AS \"tp\" ON \"tp\".\"TEAM_ID\" = \"t\".\"ID\" WHERE \"tp\".\"PERMISSION_ID\" = %d";
private static final String STMT_10 = "INSERT INTO \"TEAMS_PERMISSIONS\" (\"TEAM_ID\", \"PERMISSION_ID\") VALUES (?, ?)";
@Override
public String getSchemaVersion() {
return "4.4.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
private long getPermissionId(final Connection connection, final Permissions permission) throws SQLException, UpgradeException {
final PreparedStatement ps = connection.prepareStatement(STMT_2);
ps.setString(1, permission.name());
final ResultSet rs = ps.executeQuery();
if (!rs.next()) {
throw new UpgradeException("Unable to determine ID of permission " + permission.name());
}
return rs.getLong(1);
}
}
|
LOGGER.info("Creating VIEW_VULNERABILITY permission");
PreparedStatement ps = connection.prepareStatement(STMT_1);
ps.setString(1, Permissions.VIEW_VULNERABILITY.name());
ps.setString(2, Permissions.VIEW_VULNERABILITY.getDescription());
ps.executeUpdate();
final long viewVulnPermissionId = getPermissionId(connection, Permissions.VIEW_VULNERABILITY);
final long vulnAnalysisPermissionId = getPermissionId(connection, Permissions.VULNERABILITY_ANALYSIS);
LOGGER.info("Granting VIEW_VULNERABILITY permission to managed users with VULNERABILITY_ANALYSIS permission");
try (final Statement stmt = connection.createStatement()) {
final ResultSet rs = stmt.executeQuery(String.format(STMT_3, vulnAnalysisPermissionId));
while (rs.next()) {
ps = connection.prepareStatement(STMT_4);
ps.setLong(1, rs.getLong(1));
ps.setLong(2, viewVulnPermissionId);
ps.executeUpdate();
}
}
LOGGER.info("Granting VIEW_VULNERABILITY permission to LDAP users with VULNERABILITY_ANALYSIS permission");
try (final Statement stmt = connection.createStatement()) {
final ResultSet rs = stmt.executeQuery(String.format(STMT_5, vulnAnalysisPermissionId));
while (rs.next()) {
ps = connection.prepareStatement(STMT_6);
ps.setLong(1, rs.getLong(1));
ps.setLong(2, viewVulnPermissionId);
ps.executeUpdate();
}
}
LOGGER.info("Granting VIEW_VULNERABILITY permission to OIDC users with VULNERABILITY_ANALYSIS permission");
try (final Statement stmt = connection.createStatement()) {
final ResultSet rs = stmt.executeQuery(String.format(STMT_7, vulnAnalysisPermissionId));
while (rs.next()) {
ps = connection.prepareStatement(STMT_8);
ps.setLong(1, rs.getLong(1));
ps.setLong(2, viewVulnPermissionId);
ps.executeUpdate();
}
}
LOGGER.info("Granting VIEW_VULNERABILITY permission to teams with VULNERABILITY_ANALYSIS permission");
try (final Statement stmt = connection.createStatement()) {
final ResultSet rs = stmt.executeQuery(String.format(STMT_9, vulnAnalysisPermissionId));
while (rs.next()) {
ps = connection.prepareStatement(STMT_10);
ps.setLong(1, rs.getLong(1));
ps.setLong(2, viewVulnPermissionId);
ps.executeUpdate();
}
}
| 832
| 757
| 1,589
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v460/v460Updater.java
|
v460Updater
|
executeUpgrade
|
class v460Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v460Updater.class);
@Override
public String getSchemaVersion() {
return "4.6.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
}
|
// Fixes https://github.com/DependencyTrack/dependency-track/issues/1661
// The JDBC type "CLOB" is mapped to the type CLOB for H2, MEDIUMTEXT for MySQL, and TEXT for PostgreSQL and SQL Server.
// - https://github.com/datanucleus/datanucleus-rdbms/blob/datanucleus-rdbms-5.2.11/src/main/java/org/datanucleus/store/rdbms/adapter/H2Adapter.java#L484
// - https://github.com/datanucleus/datanucleus-rdbms/blob/datanucleus-rdbms-5.2.11/src/main/java/org/datanucleus/store/rdbms/adapter/MySQLAdapter.java#L185-L186
// - https://github.com/datanucleus/datanucleus-rdbms/blob/datanucleus-rdbms-5.2.11/src/main/java/org/datanucleus/store/rdbms/adapter/PostgreSQLAdapter.java#L144
// - https://github.com/datanucleus/datanucleus-rdbms/blob/datanucleus-rdbms-5.2.11/src/main/java/org/datanucleus/store/rdbms/adapter/SQLServerAdapter.java#L168-L169
LOGGER.info("Changing JDBC type of \"ANALYSIS\".\"DETAILS\" from VARCHAR to CLOB");
if (DbUtil.isH2()) {
DbUtil.executeUpdate(connection, "ALTER TABLE \"ANALYSIS\" ADD \"DETAILS_V46\" CLOB");
} else if (DbUtil.isMysql()) {
DbUtil.executeUpdate(connection, "ALTER TABLE \"ANALYSIS\" ADD \"DETAILS_V46\" MEDIUMTEXT");
} else {
DbUtil.executeUpdate(connection, "ALTER TABLE \"ANALYSIS\" ADD \"DETAILS_V46\" TEXT");
}
DbUtil.executeUpdate(connection, "UPDATE \"ANALYSIS\" SET \"DETAILS_V46\" = \"DETAILS\"");
DbUtil.executeUpdate(connection, "ALTER TABLE \"ANALYSIS\" DROP COLUMN \"DETAILS\"");
if (DbUtil.isMssql()) { // Really, Microsoft? You're being weird.
DbUtil.executeUpdate(connection, "EXEC sp_rename 'ANALYSIS.DETAILS_V46', 'DETAILS', 'COLUMN'");
} else if (DbUtil.isMysql()) { // MySQL < 8.0 does not support RENAME COLUMN and needs a special treatment.
DbUtil.executeUpdate(connection, "ALTER TABLE \"ANALYSIS\" CHANGE \"DETAILS_V46\" \"DETAILS\" MEDIUMTEXT");
} else {
DbUtil.executeUpdate(connection, "ALTER TABLE \"ANALYSIS\" RENAME COLUMN \"DETAILS_V46\" TO \"DETAILS\"");
}
LOGGER.info("Updating Package URLs of PHP Packages for GHSA Vulnerabilities");
try (final Statement stmt = connection.createStatement()) {
final ResultSet rs = stmt.executeQuery("""
SELECT "ID", "PURL_NAME"
FROM "VULNERABLESOFTWARE"
WHERE "PURL_TYPE" = 'composer'
AND "PURL_NAMESPACE" IS NULL
AND "PURL_NAME" LIKE '%/%'
""");
while (rs.next()) {
final String purlName = rs.getString(2);
final String[] purlParts = purlName.split("/");
final String namespace = String.join("/", Arrays.copyOfRange(purlParts, 0, purlParts.length - 1));
final PreparedStatement ps = connection.prepareStatement("""
UPDATE "VULNERABLESOFTWARE" SET "PURL_NAMESPACE" = ?, "PURL_NAME" = ? WHERE "ID" = ?
""");
ps.setString(1, namespace);
ps.setString(2, purlParts[purlParts.length - 1]);
ps.setLong(3, rs.getLong(1));
ps.executeUpdate();
}
}
| 112
| 1,149
| 1,261
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v463/v463Updater.java
|
v463Updater
|
executeUpgrade
|
class v463Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v463Updater.class);
@Override
public String getSchemaVersion() {
return "4.6.3";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Resetting scanner cache validity period to 12h");
final PreparedStatement ps = connection.prepareStatement("""
UPDATE "CONFIGPROPERTY" SET "PROPERTYVALUE" = ?
WHERE "GROUPNAME" = ? AND "PROPERTYNAME" = ?
""");
ps.setString(1, SCANNER_ANALYSIS_CACHE_VALIDITY_PERIOD.getDefaultPropertyValue());
ps.setString(2, SCANNER_ANALYSIS_CACHE_VALIDITY_PERIOD.getGroupName());
ps.setString(3, SCANNER_ANALYSIS_CACHE_VALIDITY_PERIOD.getPropertyName());
ps.executeUpdate();
| 113
| 183
| 296
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v470/v470Updater.java
|
v470Updater
|
executeUpgrade
|
class v470Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v470Updater.class);
@Override
public String getSchemaVersion() {
return "4.7.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Setting component analysis cache clear cadence to 24H");
final PreparedStatement ps = connection.prepareStatement("""
UPDATE "CONFIGPROPERTY" SET "PROPERTYVALUE" = ?
WHERE "GROUPNAME" = ? AND "PROPERTYNAME" = ?
""");
ps.setString(1, TASK_SCHEDULER_COMPONENT_ANALYSIS_CACHE_CLEAR_CADENCE.getDefaultPropertyValue());
ps.setString(2, TASK_SCHEDULER_COMPONENT_ANALYSIS_CACHE_CLEAR_CADENCE.getGroupName());
ps.setString(3, TASK_SCHEDULER_COMPONENT_ANALYSIS_CACHE_CLEAR_CADENCE.getPropertyName());
ps.executeUpdate();
| 113
| 213
| 326
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v480/v480Updater.java
|
v480Updater
|
changeJdbcTypeOfComponentAuthorColumn
|
class v480Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v480Updater.class);
@Override
public String getSchemaVersion() {
return "4.8.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {
changeJdbcTypeOfComponentAuthorColumn(connection);
setJiraPropertyValuesFromJiraToIntegrationGroup(connection);
}
private void changeJdbcTypeOfComponentAuthorColumn(Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
private void setJiraPropertyValuesFromJiraToIntegrationGroup(Connection connection) throws Exception {
LOGGER.info("Setting Jira property values from Groupname 'jira' to Groupname 'integrations'");
try (final PreparedStatement ps = connection.prepareStatement("""
UPDATE "CONFIGPROPERTY" SET "GROUPNAME" = 'integrations'
WHERE "GROUPNAME" = 'jira' AND "PROPERTYNAME" LIKE 'jira.%'
""")) {
ps.executeUpdate();
}
}
}
|
// Fixes https://github.com/DependencyTrack/dependency-track/issues/2488
// The JDBC type "CLOB" is mapped to the type CLOB for H2, MEDIUMTEXT for MySQL, and TEXT for PostgreSQL and SQL Server.
LOGGER.info("Changing JDBC type of \"COMPONENT\".\"AUTHOR\" from VARCHAR to CLOB");
if (DbUtil.isH2()) {
DbUtil.executeUpdate(connection, "ALTER TABLE \"COMPONENT\" ADD \"AUTHOR_V48\" CLOB");
} else if (DbUtil.isMysql()) {
DbUtil.executeUpdate(connection, "ALTER TABLE \"COMPONENT\" ADD \"AUTHOR_V48\" MEDIUMTEXT");
} else {
DbUtil.executeUpdate(connection, "ALTER TABLE \"COMPONENT\" ADD \"AUTHOR_V48\" TEXT");
}
DbUtil.executeUpdate(connection, "UPDATE \"COMPONENT\" SET \"AUTHOR_V48\" = \"AUTHOR\"");
DbUtil.executeUpdate(connection, "ALTER TABLE \"COMPONENT\" DROP COLUMN \"AUTHOR\"");
if (DbUtil.isMssql()) { // Really, Microsoft? You're being weird.
DbUtil.executeUpdate(connection, "EXEC sp_rename 'COMPONENT.AUTHOR_V48', 'AUTHOR', 'COLUMN'");
} else if (DbUtil.isMysql()) { // MySQL < 8.0 does not support RENAME COLUMN and needs a special treatment.
DbUtil.executeUpdate(connection, "ALTER TABLE \"COMPONENT\" CHANGE \"AUTHOR_V48\" \"AUTHOR\" MEDIUMTEXT");
} else {
DbUtil.executeUpdate(connection, "ALTER TABLE \"COMPONENT\" RENAME COLUMN \"AUTHOR_V48\" TO \"AUTHOR\"");
}
| 296
| 489
| 785
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/upgrade/v490/v490Updater.java
|
v490Updater
|
updateDefaultSnykApiVersion
|
class v490Updater extends AbstractUpgradeItem {
private static final Logger LOGGER = Logger.getLogger(v490Updater.class);
@Override
public String getSchemaVersion() {
return "4.9.0";
}
@Override
public void executeUpgrade(final AlpineQueryManager qm, final Connection connection) throws Exception {
updateDefaultSnykApiVersion(connection);
}
/**
* Update the Snyk API version from its previous default to a current and actively supported one.
* Only do so when the version has not been modified manually.
*
* @param connection The {@link Connection} to use for executing queries
* @throws Exception When executing a query failed
*/
private static void updateDefaultSnykApiVersion(final Connection connection) throws Exception {<FILL_FUNCTION_BODY>}
}
|
LOGGER.info("Updating Snyk API version from 2022-11-14 to %s"
.formatted(SCANNER_SNYK_API_VERSION.getDefaultPropertyValue()));
try (final PreparedStatement ps = connection.prepareStatement("""
UPDATE "CONFIGPROPERTY" SET "PROPERTYVALUE" = ?
WHERE "GROUPNAME" = 'scanner'
AND "PROPERTYNAME" = 'snyk.api.version'
AND "PROPERTYVALUE" = '2022-11-14'
""")) {
ps.setString(1, SCANNER_SNYK_API_VERSION.getDefaultPropertyValue());
ps.executeUpdate();
}
| 222
| 185
| 407
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/AnalysisCommentUtil.java
|
AnalysisCommentUtil
|
makeJustificationComment
|
class AnalysisCommentUtil {
private AnalysisCommentUtil() { }
public static boolean makeStateComment(final QueryManager qm, final Analysis analysis, final AnalysisState analysisState, final String commenter) {
boolean analysisStateChange = false;
if (analysisState != null && analysisState != analysis.getAnalysisState()) {
analysisStateChange = true;
qm.makeAnalysisComment(analysis, String.format("Analysis: %s → %s", analysis.getAnalysisState(), analysisState), commenter);
}
return analysisStateChange;
}
public static void makeJustificationComment(final QueryManager qm, final Analysis analysis, final AnalysisJustification analysisJustification, final String commenter) {<FILL_FUNCTION_BODY>}
public static void makeAnalysisResponseComment(final QueryManager qm, final Analysis analysis, final AnalysisResponse analysisResponse, final String commenter) {
if (analysisResponse != null) {
if (analysis.getAnalysisResponse() == null && analysis.getAnalysisResponse() != analysisResponse) {
qm.makeAnalysisComment(analysis, String.format("Vendor Response: %s → %s", AnalysisResponse.NOT_SET, analysisResponse), commenter);
} else if (analysis.getAnalysisResponse() != null && analysis.getAnalysisResponse() != analysisResponse) {
qm.makeAnalysisComment(analysis, String.format("Vendor Response: %s → %s", analysis.getAnalysisResponse(), analysisResponse), commenter);
}
}
}
public static void makeAnalysisDetailsComment(final QueryManager qm, final Analysis analysis, final String analysisDetails, final String commenter) {
if (analysisDetails != null && !analysisDetails.equals(analysis.getAnalysisDetails())) {
final String message = "Details: " + analysisDetails.trim();
qm.makeAnalysisComment(analysis, message, commenter);
}
}
public static boolean makeAnalysisSuppressionComment(final QueryManager qm, final Analysis analysis, final Boolean suppressed, final String commenter) {
boolean suppressionChange = false;
if (suppressed != null && analysis.isSuppressed() != suppressed) {
suppressionChange = true;
final String message = (suppressed) ? "Suppressed" : "Unsuppressed";
qm.makeAnalysisComment(analysis, message, commenter);
}
return suppressionChange;
}
}
|
if (analysisJustification != null) {
if (analysis.getAnalysisJustification() == null && AnalysisJustification.NOT_SET != analysisJustification) {
qm.makeAnalysisComment(analysis, String.format("Justification: %s → %s", AnalysisJustification.NOT_SET, analysisJustification), commenter);
} else if (analysis.getAnalysisJustification() != null && analysisJustification != analysis.getAnalysisJustification()) {
qm.makeAnalysisComment(analysis, String.format("Justification: %s → %s", analysis.getAnalysisJustification(), analysisJustification), commenter);
}
}
| 580
| 158
| 738
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/ComponentIdentificationUtil.java
|
ComponentIdentificationUtil
|
doesIdentityMatch
|
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) {<FILL_FUNCTION_BODY>}
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;
}
}
|
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;
| 584
| 245
| 829
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/CompressUtil.java
|
CompressUtil
|
optionallyDecompress
|
class CompressUtil {
private CompressUtil() { }
/**
* Helper method that attempts to automatically identify an archive and its type,
* extract the contents as a byte array. If this fails, it will gracefully return
* the original input byte array without exception. If the input was not an archive
* or compressed, it will return the original byte array.
* @param input the
* @return a byte array
*/
public static byte[] optionallyDecompress(final byte[] input) {<FILL_FUNCTION_BODY>}
}
|
try (final ByteArrayInputStream bis = new ByteArrayInputStream(input);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(bis)) {
final ArchiveEntry entry = ais.getNextEntry();
if (ais.canReadEntryData(entry)) {
return IOUtils.toByteArray(ais);
}
} catch (ArchiveException | IOException e) {
// throw it away and return the original byte array
}
return input;
| 140
| 120
| 260
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/DateUtil.java
|
DateUtil
|
toISO8601
|
class DateUtil {
private DateUtil() {
}
/**
* Convenience method that parses a date in yyyyMMdd format and
* returns a Date object. If the parsing fails, null is returned.
* @param yyyyMMdd the date string to parse
* @return a Date object
* @since 3.0.0
*/
public static Date parseShortDate(final String yyyyMMdd) {
final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
try {
return format.parse(yyyyMMdd);
} catch (ParseException e) {
return null;
}
}
/**
* Convenience method that parses a date in yyyyMMddHHmmss format and
* returns a Date object. If the parsing fails, null is returned.
* @param yyyyMMddHHmmss the date string to parse
* @return a Date object
* @since 3.1.0
*/
public static Date parseDate(final String yyyyMMddHHmmss) {
final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
try {
return format.parse(yyyyMMddHHmmss);
} catch (ParseException e) {
return null;
}
}
/**
* Convenience method that returns the difference (in days) between
* two dates.
* @param start the first date
* @param end the second date
* @return the difference in days
* @since 3.0.0
*/
public static long diff(final Date start, final Date end) {
final long diff = end.getTime() - start.getTime();
return TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
}
/**
* Formats a Date object into ISO 8601 format.
* @param date the Date object to convert
* @return a String representation of an ISO 8601 date
* @since 3.4.0
*/
public static String toISO8601(final Date date) {<FILL_FUNCTION_BODY>}
public static Date fromISO8601(final String dateString) {
if (dateString == null) {
return null;
}
return javax.xml.bind.DatatypeConverter.parseDateTime(dateString).getTime();
}
}
|
final TimeZone tz = TimeZone.getTimeZone("UTC");
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // Quoted "Z" to indicate UTC, no timezone offset
df.setTimeZone(tz);
return df.format(date);
| 618
| 84
| 702
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/HashUtil.java
|
HashUtil
|
sha256
|
class HashUtil {
private HashUtil() { }
public static String md5(final File file) {
try (InputStream fis = Files.newInputStream(file.toPath())) {
return org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
} catch (IOException e){
return null;
}
}
public static String sha1(final File file) {
try (InputStream fis = Files.newInputStream(file.toPath())) {
return org.apache.commons.codec.digest.DigestUtils.sha1Hex(fis);
} catch (IOException e){
return null;
}
}
public static String sha256(final File file) {<FILL_FUNCTION_BODY>}
public static String sha512(final File file) {
try (InputStream fis = Files.newInputStream(file.toPath())) {
return org.apache.commons.codec.digest.DigestUtils.sha512Hex(fis);
} catch (IOException e){
return null;
}
}
}
|
try (InputStream fis = Files.newInputStream(file.toPath())) {
return org.apache.commons.codec.digest.DigestUtils.sha256Hex(fis);
} catch (IOException e){
return null;
}
| 280
| 65
| 345
|
<no_super_class>
|
DependencyTrack_dependency-track
|
dependency-track/src/main/java/org/dependencytrack/util/HttpUtil.java
|
HttpUtil
|
basicAuthHeaderValue
|
class HttpUtil {
/**
* Private constructor.
*/
private HttpUtil() {
}
public static String basicAuthHeader(final String username, final String password) {
return AUTHORIZATION + ": " + basicAuthHeaderValue(username, password);
}
public static String basicAuthHeaderValue(final String username, final String password) {<FILL_FUNCTION_BODY>}
}
|
return "Basic " +
Base64.getEncoder().encodeToString(
String.format("%s:%s", Objects.toString(username, ""), Objects.toString(password, ""))
.getBytes()
);
| 106
| 61
| 167
|
<no_super_class>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.