Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
import org.dependencytrack.notification.proto.v1.Notification;
import org.dependencytrack.notification.proto.v1.PolicyViolationAnalysisDecisionChangeSubject;
import org.dependencytrack.notification.proto.v1.PolicyViolationSubject;
import org.dependencytrack.notification.proto.v1.PolicyViolationUpdatedSubject;
import org.dependencytrack.notification.proto.v1.UserSubject;
import org.dependencytrack.notification.proto.v1.VexConsumedOrProcessedSubject;
import org.dependencytrack.notification.proto.v1.VulnerabilityAnalysisDecisionChangeSubject;
Expand Down Expand Up @@ -94,6 +95,7 @@ private NotificationFilterExpressionEnv() {
NewVulnerabilitySubject.getDescriptor(),
NewVulnerableDependencySubject.getDescriptor(),
PolicyViolationSubject.getDescriptor(),
PolicyViolationUpdatedSubject.getDescriptor(),
PolicyViolationAnalysisDecisionChangeSubject.getDescriptor(),
VulnerabilityAnalysisDecisionChangeSubject.getDescriptor(),
VexConsumedOrProcessedSubject.getDescriptor(),
Expand All @@ -113,6 +115,7 @@ private NotificationFilterExpressionEnv() {
NewVulnerabilitySubject.getDescriptor(),
NewVulnerableDependencySubject.getDescriptor(),
PolicyViolationSubject.getDescriptor(),
PolicyViolationUpdatedSubject.getDescriptor(),
PolicyViolationAnalysisDecisionChangeSubject.getDescriptor(),
VulnerabilityAnalysisDecisionChangeSubject.getDescriptor(),
VexConsumedOrProcessedSubject.getDescriptor(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public enum NotificationGroup {
VEX_CONSUMED,
VEX_PROCESSED,
POLICY_VIOLATION,
POLICY_VIOLATION_UPDATED,
POLICY_VIOLATION_UPDATED_REVIEWED,
PROJECT_CREATED,
USER_CREATED,
USER_DELETED,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ public static Group convert(NotificationGroup group) {
case NEW_VULNERABILITY -> Group.GROUP_NEW_VULNERABILITY;
case NEW_VULNERABLE_DEPENDENCY -> Group.GROUP_NEW_VULNERABLE_DEPENDENCY;
case POLICY_VIOLATION -> Group.GROUP_POLICY_VIOLATION;
case POLICY_VIOLATION_UPDATED -> Group.GROUP_POLICY_VIOLATION_UPDATED;
case POLICY_VIOLATION_UPDATED_REVIEWED -> Group.GROUP_POLICY_VIOLATION_UPDATED_REVIEWED;
case PROJECT_AUDIT_CHANGE -> Group.GROUP_PROJECT_AUDIT_CHANGE;
case PROJECT_CREATED -> Group.GROUP_PROJECT_CREATED;
case REPOSITORY -> Group.GROUP_REPOSITORY;
Expand Down Expand Up @@ -93,6 +95,8 @@ static NotificationGroup convert(Group protoGroup) {
case GROUP_NEW_VULNERABILITY -> NotificationGroup.NEW_VULNERABILITY;
case GROUP_NEW_VULNERABLE_DEPENDENCY -> NotificationGroup.NEW_VULNERABLE_DEPENDENCY;
case GROUP_POLICY_VIOLATION -> NotificationGroup.POLICY_VIOLATION;
case GROUP_POLICY_VIOLATION_UPDATED -> NotificationGroup.POLICY_VIOLATION_UPDATED;
case GROUP_POLICY_VIOLATION_UPDATED_REVIEWED -> NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED;
case GROUP_PROJECT_AUDIT_CHANGE -> NotificationGroup.PROJECT_AUDIT_CHANGE;
case GROUP_PROJECT_CREATED -> NotificationGroup.PROJECT_CREATED;
case GROUP_REPOSITORY -> NotificationGroup.REPOSITORY;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.dependencytrack.notification.proto.v1.Notification;
import org.dependencytrack.notification.proto.v1.PolicyViolationAnalysisDecisionChangeSubject;
import org.dependencytrack.notification.proto.v1.PolicyViolationSubject;
import org.dependencytrack.notification.proto.v1.PolicyViolationUpdatedSubject;
import org.dependencytrack.notification.proto.v1.Project;
import org.dependencytrack.notification.proto.v1.UserSubject;
import org.dependencytrack.notification.proto.v1.VexConsumedOrProcessedSubject;
Expand Down Expand Up @@ -351,6 +352,7 @@ private boolean evaluateFilterExpression(
case NewVulnerabilitySubject it -> it.getProject();
case NewVulnerableDependencySubject it -> it.getProject();
case PolicyViolationSubject it -> it.getProject();
case PolicyViolationUpdatedSubject it -> it.getProject();
case PolicyViolationAnalysisDecisionChangeSubject it -> it.getProject();
case VulnerabilityAnalysisDecisionChangeSubject it -> it.getProject();
case Project it -> it;
Expand All @@ -376,6 +378,8 @@ private boolean evaluateFilterExpression(
case GROUP_NEW_VULNERABLE_DEPENDENCY ->
notification.getSubject().unpack(NewVulnerableDependencySubject.class);
case GROUP_POLICY_VIOLATION -> notification.getSubject().unpack(PolicyViolationSubject.class);
case GROUP_POLICY_VIOLATION_UPDATED, GROUP_POLICY_VIOLATION_UPDATED_REVIEWED ->
notification.getSubject().unpack(PolicyViolationUpdatedSubject.class);
case GROUP_PROJECT_AUDIT_CHANGE -> {
if (notification.getSubject().is(PolicyViolationAnalysisDecisionChangeSubject.class)) {
yield notification.getSubject().unpack(PolicyViolationAnalysisDecisionChangeSubject.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import org.jdbi.v3.sqlobject.customizer.Bind;
import org.jdbi.v3.sqlobject.customizer.Define;
import org.jdbi.v3.sqlobject.statement.SqlQuery;
import org.jspecify.annotations.Nullable;

import java.sql.Timestamp;
import java.util.ArrayList;
Expand Down Expand Up @@ -673,7 +674,27 @@ default Map<Long, PolicyCondition> getPolicyConditionsById(Collection<Long> ids)
}

default List<PolicyViolationSubject> getForNewPolicyViolations(Collection<Long> violationIds) {
if (violationIds.isEmpty()) {
return getForPolicyViolationUpdates(violationIds, true, false).stream()
.map(PolicyViolationUpdateSubject::subject)
.toList();
}

record PolicyViolationUpdateSubject(
PolicyViolationSubject subject,
@Nullable String analysisState,
@Nullable Boolean suppressed) {

public boolean isReviewed() {
return "APPROVED".equals(analysisState) || Boolean.TRUE.equals(suppressed);
}
}

/// Fetch both classes in one statement so a concurrent review cannot move the
/// same message transition between separate active and reviewed queries.
/// Review metadata represents the snapshot observed by this statement.
default List<PolicyViolationUpdateSubject> getForPolicyViolationUpdates(
Collection<Long> violationIds, boolean includeActive, boolean includeReviewed) {
if (violationIds.isEmpty() || (!includeActive && !includeReviewed)) {
return List.of();
}

Expand Down Expand Up @@ -728,11 +749,18 @@ FROM UNNEST(:violationIds) AS req(violation_id)
ON p."ID" = pv."PROJECT_ID"
LEFT JOIN "VIOLATIONANALYSIS" AS va
ON va."POLICYVIOLATION_ID" = pv."ID"
WHERE va."SUPPRESSED" IS DISTINCT FROM TRUE
AND va."STATE" IS DISTINCT FROM 'APPROVED'
AND va."COMPONENT_ID" = pv."COMPONENT_ID"
AND va."PROJECT_ID" = pv."PROJECT_ID"
WHERE (:includeActive
AND va."SUPPRESSED" IS DISTINCT FROM TRUE
AND va."STATE" IS DISTINCT FROM 'APPROVED')
OR (:includeReviewed
AND (va."SUPPRESSED" IS TRUE OR va."STATE" = 'APPROVED'))
""")
.bindArray("violationIds", Long.class, violationIds)
.map((RowViewMapper<PolicyViolationSubject>) row -> {
.bind("includeActive", includeActive)
.bind("includeReviewed", includeReviewed)
.map((RowViewMapper<PolicyViolationUpdateSubject>) row -> {
final Component component = row.getRow(Component.class);
final Project project = row.getRow(Project.class);

Expand Down Expand Up @@ -761,11 +789,15 @@ FROM UNNEST(:violationIds) AS req(violation_id)
}
final PolicyViolation violation = violationBuilder.build();

return PolicyViolationSubject.newBuilder()
final var subject = PolicyViolationSubject.newBuilder()
.setProject(project)
.setComponent(component)
.setPolicyViolation(violation)
.build();
return new PolicyViolationUpdateSubject(
subject,
row.getColumn("analysisState", String.class),
row.getColumn("analysisSuppressed", Boolean.class));
})
.list();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import org.dependencytrack.policy.cel.persistence.CelPolicyDao;
import org.dependencytrack.policy.cel.persistence.CelPolicyDao.ComponentVulnerability;
import org.dependencytrack.policy.cel.persistence.CelPolicyDao.ComponentWithLicenseId;
import org.dependencytrack.policy.cel.persistence.CelPolicyDao.MessageChange;
import org.dependencytrack.proto.policy.v1.Component;
import org.dependencytrack.proto.policy.v1.License;
import org.dependencytrack.proto.policy.v1.Project;
Expand All @@ -71,7 +72,9 @@
import java.util.UUID;
import java.util.stream.Collectors;

import static java.util.Objects.requireNonNull;
import static org.dependencytrack.notification.api.NotificationFactory.createPolicyViolationNotification;
import static org.dependencytrack.notification.api.NotificationFactory.createPolicyViolationUpdatedNotification;
import static org.dependencytrack.persistence.jdbi.JdbiFactory.inJdbiTransaction;
import static org.dependencytrack.persistence.jdbi.JdbiFactory.useJdbiTransaction;
import static org.dependencytrack.persistence.jdbi.JdbiFactory.withJdbiHandle;
Expand Down Expand Up @@ -268,29 +271,75 @@ public void evaluateProject(UUID uuid) throws InterruptedException {
violationsByComponentId);
}

final Set<Long> newViolationIds = inJdbiTransaction(
handle -> new CelPolicyDao(handle).reconcileViolations(projectId, violationsByComponentId));
LOGGER.info("Identified {} new violations", newViolationIds.size());

if (!newViolationIds.isEmpty()) {
useJdbiTransaction(handle -> {
final var notificationSubjectDao = handle.attach(NotificationSubjectDao.class);

// Assembling notification subjects is expensive. Skip it for groups that no
// enabled rule subscribes to. The emitter would discard those notifications anyway.
if (!notificationSubjectDao
.getSubscribedNotificationGroups()
.contains(NotificationGroup.POLICY_VIOLATION.name())) {
return;
}
// Persist message transitions and their durable notification outbox records
// atomically. A failure must not consume a transition without its event.
useJdbiTransaction(handle -> {
final var changes = new CelPolicyDao(handle).reconcileViolationChanges(projectId, violationsByComponentId);
LOGGER.info(
"Identified {} new and {} updated violations",
changes.createdIds().size(),
changes.updatedById().size());
if (changes.createdIds().isEmpty() && changes.updatedById().isEmpty()) {
return;
}
final var notificationSubjectDao = handle.attach(NotificationSubjectDao.class);
final var subscribedGroups = notificationSubjectDao.getSubscribedNotificationGroups();
final var emitter = new JdbiNotificationEmitter(handle);

// Assembling notification subjects is expensive. Skip it for groups that no
// enabled rule subscribes to. The emitter would discard those notifications anyway.
if (!changes.createdIds().isEmpty()
&& subscribedGroups.contains(NotificationGroup.POLICY_VIOLATION.name())) {
emitter.emitAll(notificationSubjectDao.getForNewPolicyViolations(changes.createdIds()).stream()
.map(subject -> createPolicyViolationNotification(
subject.getProject(), subject.getComponent(), subject.getPolicyViolation()))
.toList());
}

new JdbiNotificationEmitter(handle)
.emitAll(notificationSubjectDao.getForNewPolicyViolations(newViolationIds).stream()
.map(subject -> createPolicyViolationNotification(
subject.getProject(), subject.getComponent(), subject.getPolicyViolation()))
// Ordinary subscriptions retain the existing approval/suppression
// filter. Reviewed changes require their own explicit subscription.
final boolean includeActive = subscribedGroups.contains(NotificationGroup.POLICY_VIOLATION_UPDATED.name());
final boolean includeReviewed =
subscribedGroups.contains(NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED.name());
if (!changes.updatedById().isEmpty() && (includeActive || includeReviewed)) {
final Map<String, MessageChange> updatedByUuid = changes.updatedById().values().stream()
.collect(Collectors.toMap(change -> change.uuid().toString(), change -> change));
emitter.emitAll(
notificationSubjectDao
.getForPolicyViolationUpdates(
changes.updatedById().keySet(), includeActive, includeReviewed)
.stream()
.map(row -> {
final var subject = row.subject();
final MessageChange change = requireNonNull(updatedByUuid.get(
subject.getPolicyViolation().getUuid()));
final Timestamp changedAt = Timestamp.newBuilder()
.setSeconds(change.changedAt().getEpochSecond())
.setNanos(change.changedAt().getNano())
.build();
if (row.isReviewed()) {
return createPolicyViolationUpdatedNotification(
subject.getProject(),
subject.getComponent(),
subject.getPolicyViolation(),
change.previousMessage(),
change.currentMessage(),
changedAt,
row.analysisState(),
row.suppressed());
}
// Preserve the ordinary event's original payload shape.
return createPolicyViolationUpdatedNotification(
subject.getProject(),
subject.getComponent(),
subject.getPolicyViolation(),
change.previousMessage(),
change.currentMessage(),
changedAt);
})
.toList());
});
}
}
});
}

record ConditionScript(PolicyCondition condition, CelPolicyProgram script) {}
Expand Down
Loading