From 4e3d2cf20a6628295216e138fa5478f967028ab3 Mon Sep 17 00:00:00 2001 From: WenFeng Gao Date: Sat, 7 Nov 2026 18:23:58 +0800 Subject: [PATCH 1/2] Notify subscribers when policy violation messages change Existing CEL violations retain their identity when matching content changes, so later KEVs do not produce the creation notification. Persist message transitions and notification outbox entries together, and expose separate subscriptions for active and explicitly opted-in reviewed violations. Preserve creation notifications and review decisions. Cover PostgreSQL concurrency, rollback, review ownership and API-to-webhook delivery with regression tests, and document the message-based contract in a proposed ADR. Signed-off-by: WenFeng Gao --- .../NotificationFilterExpressionEnv.java | 3 + .../notification/NotificationGroup.java | 2 + .../NotificationModelConverter.java | 4 + .../notification/NotificationRouter.java | 4 + .../notification/NotificationSubjectDao.java | 42 +- .../policy/cel/CelPolicyEngine.java | 91 +- .../policy/cel/persistence/CelPolicyDao.java | 98 ++- .../notification/NotificationGroupTest.java | 22 + .../NotificationModelConverterTest.java | 8 + .../notification/NotificationRouterTest.java | 159 ++++ .../NotificationSubjectDaoTest.java | 174 ++++ ...PolicyViolationUpdatedIntegrationTest.java | 806 ++++++++++++++++++ .../cel/persistence/CelPolicyDaoTest.java | 67 ++ .../CelPolicyViolationChangesTest.java | 399 +++++++++ .../v1/NotificationRuleResourceTest.java | 34 + docs/POLICY_VIOLATION_UPDATES.md | 64 ++ ...4-policy-violation-update-notifications.md | 79 ++ .../PolicyViolationUpdatedReviewedE2ET.java | 392 +++++++++ .../notification/api/NotificationFactory.java | 77 ++ .../api/TestNotificationFactory.java | 32 + .../notification/v1/notification.proto | 23 + ...olicyViolationUpdatedNotificationTest.java | 233 +++++ .../kafka/KafkaNotificationPublisher.java | 6 + .../publishing/console/default-template.peb | 11 + .../publishing/email/default-template.peb | 13 +- .../publishing/jira/default-template.peb | 2 + .../mattermost/default-template.peb | 2 +- .../publishing/msteams/default-template.peb | 32 +- .../publishing/slack/default-template.peb | 15 +- .../publishing/webex/default-template.peb | 2 +- .../PolicyViolationUpdatedTemplateTest.java | 157 ++++ .../PebbleNotificationTemplateRenderer.java | 3 + 32 files changed, 3014 insertions(+), 42 deletions(-) create mode 100644 apiserver/src/test/java/org/dependencytrack/notification/PolicyViolationUpdatedIntegrationTest.java create mode 100644 apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyViolationChangesTest.java create mode 100644 docs/POLICY_VIOLATION_UPDATES.md create mode 100644 docs/adr/044-policy-violation-update-notifications.md create mode 100644 e2e/src/test/java/org/dependencytrack/e2e/PolicyViolationUpdatedReviewedE2ET.java create mode 100644 notification/api/src/test/java/org/dependencytrack/notification/api/PolicyViolationUpdatedNotificationTest.java create mode 100644 notification/publishing/src/test/java/org/dependencytrack/notification/publishing/PolicyViolationUpdatedTemplateTest.java diff --git a/apiserver/src/main/java/org/dependencytrack/notification/NotificationFilterExpressionEnv.java b/apiserver/src/main/java/org/dependencytrack/notification/NotificationFilterExpressionEnv.java index 9e09d22504..ac5e6b2ca4 100644 --- a/apiserver/src/main/java/org/dependencytrack/notification/NotificationFilterExpressionEnv.java +++ b/apiserver/src/main/java/org/dependencytrack/notification/NotificationFilterExpressionEnv.java @@ -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; @@ -94,6 +95,7 @@ private NotificationFilterExpressionEnv() { NewVulnerabilitySubject.getDescriptor(), NewVulnerableDependencySubject.getDescriptor(), PolicyViolationSubject.getDescriptor(), + PolicyViolationUpdatedSubject.getDescriptor(), PolicyViolationAnalysisDecisionChangeSubject.getDescriptor(), VulnerabilityAnalysisDecisionChangeSubject.getDescriptor(), VexConsumedOrProcessedSubject.getDescriptor(), @@ -113,6 +115,7 @@ private NotificationFilterExpressionEnv() { NewVulnerabilitySubject.getDescriptor(), NewVulnerableDependencySubject.getDescriptor(), PolicyViolationSubject.getDescriptor(), + PolicyViolationUpdatedSubject.getDescriptor(), PolicyViolationAnalysisDecisionChangeSubject.getDescriptor(), VulnerabilityAnalysisDecisionChangeSubject.getDescriptor(), VexConsumedOrProcessedSubject.getDescriptor(), diff --git a/apiserver/src/main/java/org/dependencytrack/notification/NotificationGroup.java b/apiserver/src/main/java/org/dependencytrack/notification/NotificationGroup.java index ef55aeb2e2..ffde78d4b5 100644 --- a/apiserver/src/main/java/org/dependencytrack/notification/NotificationGroup.java +++ b/apiserver/src/main/java/org/dependencytrack/notification/NotificationGroup.java @@ -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, diff --git a/apiserver/src/main/java/org/dependencytrack/notification/NotificationModelConverter.java b/apiserver/src/main/java/org/dependencytrack/notification/NotificationModelConverter.java index f73d372d2b..394c92d748 100644 --- a/apiserver/src/main/java/org/dependencytrack/notification/NotificationModelConverter.java +++ b/apiserver/src/main/java/org/dependencytrack/notification/NotificationModelConverter.java @@ -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; @@ -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; diff --git a/apiserver/src/main/java/org/dependencytrack/notification/NotificationRouter.java b/apiserver/src/main/java/org/dependencytrack/notification/NotificationRouter.java index c5b4c3caf3..8d4589726d 100644 --- a/apiserver/src/main/java/org/dependencytrack/notification/NotificationRouter.java +++ b/apiserver/src/main/java/org/dependencytrack/notification/NotificationRouter.java @@ -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; @@ -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; @@ -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); diff --git a/apiserver/src/main/java/org/dependencytrack/notification/NotificationSubjectDao.java b/apiserver/src/main/java/org/dependencytrack/notification/NotificationSubjectDao.java index db6d8b489f..ccf542ce4c 100644 --- a/apiserver/src/main/java/org/dependencytrack/notification/NotificationSubjectDao.java +++ b/apiserver/src/main/java/org/dependencytrack/notification/NotificationSubjectDao.java @@ -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; @@ -673,7 +674,27 @@ default Map getPolicyConditionsById(Collection ids) } default List getForNewPolicyViolations(Collection 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 getForPolicyViolationUpdates( + Collection violationIds, boolean includeActive, boolean includeReviewed) { + if (violationIds.isEmpty() || (!includeActive && !includeReviewed)) { return List.of(); } @@ -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) row -> { + .bind("includeActive", includeActive) + .bind("includeReviewed", includeReviewed) + .map((RowViewMapper) row -> { final Component component = row.getRow(Component.class); final Project project = row.getRow(Project.class); @@ -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(); } diff --git a/apiserver/src/main/java/org/dependencytrack/policy/cel/CelPolicyEngine.java b/apiserver/src/main/java/org/dependencytrack/policy/cel/CelPolicyEngine.java index 3f3a4c34a9..a1f63c8041 100644 --- a/apiserver/src/main/java/org/dependencytrack/policy/cel/CelPolicyEngine.java +++ b/apiserver/src/main/java/org/dependencytrack/policy/cel/CelPolicyEngine.java @@ -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; @@ -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; @@ -268,29 +271,75 @@ public void evaluateProject(UUID uuid) throws InterruptedException { violationsByComponentId); } - final Set 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 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) {} diff --git a/apiserver/src/main/java/org/dependencytrack/policy/cel/persistence/CelPolicyDao.java b/apiserver/src/main/java/org/dependencytrack/policy/cel/persistence/CelPolicyDao.java index d26862028b..881b352421 100644 --- a/apiserver/src/main/java/org/dependencytrack/policy/cel/persistence/CelPolicyDao.java +++ b/apiserver/src/main/java/org/dependencytrack/policy/cel/persistence/CelPolicyDao.java @@ -32,14 +32,17 @@ import org.dependencytrack.proto.policy.v1.Vulnerability; import org.jdbi.v3.core.Handle; import org.jdbi.v3.core.statement.StatementContext; +import org.jdbi.v3.core.transaction.TransactionIsolationLevel; import org.jspecify.annotations.NonNull; import org.jspecify.annotations.Nullable; import java.sql.ResultSet; import java.sql.Timestamp; +import java.time.Instant; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; +import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -268,6 +271,7 @@ AND EXISTS ( AND fa."DELETED_AT" IS NULL ) AND a."SUPPRESSED" IS NOT TRUE + ORDER BY cv."COMPONENT_ID", cv."VULNERABILITY_ID" """) .define( JdbiAttributes.ATTRIBUTE_QUERY_NAME, @@ -550,8 +554,54 @@ AND NOT EXISTS ( .toList(); } + /** Backwards-compatible entry point: report only newly inserted violation IDs. */ public Set reconcileViolations( long projectId, Map> reportedViolationsByComponentId) { + return reconcileViolationChanges(projectId, reportedViolationsByComponentId) + .createdIds(); + } + + /** A change in the evaluation message of an existing violation. */ + public record MessageChange( + UUID uuid, + @Nullable String previousMessage, + @Nullable String currentMessage, + Instant changedAt) {} + + /** Creation and update notifications are separate; existing behavior remains unchanged. */ + public record ViolationChanges(Set createdIds, Map updatedById) {} + + private record UpsertChange( + long id, + UUID uuid, + boolean created, + @Nullable String previousMessage, + @Nullable String currentMessage, + Instant changedAt) {} + + public ViolationChanges reconcileViolationChanges( + long projectId, Map> reportedViolationsByComponentId) { + if (!jdbiHandle.isInTransaction() + || jdbiHandle.getTransactionIsolationLevel() != TransactionIsolationLevel.READ_COMMITTED) { + throw new IllegalStateException("Violation reconciliation requires a READ COMMITTED transaction"); + } + + // Serialize reconciliation even when no violations exist yet. This must be a + // separate statement: after waiting for the lock, the next READ COMMITTED + // snapshot includes the previous writer's committed messages. A lock inside + // the upsert CTE would still use its earlier, potentially stale snapshot. + // NO KEY UPDATE is compatible with the KEY SHARE locks taken by foreign keys. + if (jdbiHandle + .createQuery(""" + SELECT "ID" FROM "PROJECT" WHERE "ID" = :projectId FOR NO KEY UPDATE + """) + .bind("projectId", projectId) + .mapTo(Long.class) + .findOne() + .isEmpty()) { + return new ViolationChanges(Set.of(), Map.of()); + } + if (reportedViolationsByComponentId.isEmpty()) { jdbiHandle.createUpdate(""" DELETE FROM "POLICYVIOLATION" @@ -563,7 +613,7 @@ public Set reconcileViolations( FOR UPDATE ) """).bind("projectId", projectId).execute(); - return Set.of(); + return new ViolationChanges(Set.of(), Map.of()); } int size = 0; @@ -591,9 +641,18 @@ public Set reconcileViolations( } } - return jdbiHandle + final List changes = jdbiHandle .createQuery(""" - WITH upserted AS ( + -- The project lock was acquired before this statement's snapshot. + WITH previous AS MATERIALIZED ( + SELECT pv."ID", pv."TEXT" + FROM "POLICYVIOLATION" AS pv + WHERE pv."PROJECT_ID" = :projectId + AND (pv."COMPONENT_ID", pv."POLICYCONDITION_ID") IN ( + SELECT * FROM UNNEST(:componentIds, :policyConditionIds) + ) + ), + upserted AS ( INSERT INTO "POLICYVIOLATION" ( "UUID" , "TIMESTAMP" @@ -615,7 +674,7 @@ ON CONFLICT ("COMPONENT_ID", "PROJECT_ID", "POLICYCONDITION_ID") DO UPDATE WHERE "POLICYVIOLATION"."TEXT" IS DISTINCT FROM EXCLUDED."TEXT" -- xmax is zero for rows created by this statement, -- and non-zero for existing rows that were updated. - RETURNING "ID", (xmax = 0) AS "CREATED" + RETURNING "ID", "UUID", "TEXT", (xmax = 0) AS "CREATED" ), deleted AS ( DELETE FROM "POLICYVIOLATION" @@ -630,7 +689,12 @@ deleted AS ( FOR UPDATE ) ) - SELECT "ID" FROM upserted WHERE "CREATED" + SELECT u."ID", u."UUID", u."CREATED" + , p."TEXT" AS "PREVIOUS_MESSAGE" + , u."TEXT" AS "CURRENT_MESSAGE" + , STATEMENT_TIMESTAMP() AS "CHANGED_AT" + FROM upserted AS u + LEFT JOIN previous AS p ON p."ID" = u."ID" """) .bind("timestamps", timestamps) .bind("componentIds", componentIds) @@ -639,8 +703,28 @@ deleted AS ( .bind("types", types) .bind("texts", texts) .bind("projectId", projectId) - .mapTo(Long.class) - .set(); + .map((rs, ctx) -> new UpsertChange( + rs.getLong("ID"), + rs.getObject("UUID", UUID.class), + rs.getBoolean("CREATED"), + rs.getString("PREVIOUS_MESSAGE"), + rs.getString("CURRENT_MESSAGE"), + rs.getTimestamp("CHANGED_AT").toInstant())) + .list(); + + final Set createdIds = new HashSet<>(); + final Map updatedById = new HashMap<>(); + for (final UpsertChange change : changes) { + if (change.created()) { + createdIds.add(change.id()); + } else { + updatedById.put( + change.id(), + new MessageChange( + change.uuid(), change.previousMessage(), change.currentMessage(), change.changedAt())); + } + } + return new ViolationChanges(Set.copyOf(createdIds), Map.copyOf(updatedById)); } public Project loadRequiredFields(long projectId, Map> requirements) { diff --git a/apiserver/src/test/java/org/dependencytrack/notification/NotificationGroupTest.java b/apiserver/src/test/java/org/dependencytrack/notification/NotificationGroupTest.java index d9d4fa1418..1efaaa42da 100644 --- a/apiserver/src/test/java/org/dependencytrack/notification/NotificationGroupTest.java +++ b/apiserver/src/test/java/org/dependencytrack/notification/NotificationGroupTest.java @@ -18,9 +18,12 @@ */ package org.dependencytrack.notification; +import org.dependencytrack.model.NotificationTriggerType; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import static org.assertj.core.api.Assertions.assertThat; + class NotificationGroupTest { @Test @@ -42,4 +45,23 @@ void testEnums() { Assertions.assertEquals("USER_CREATED", NotificationGroup.USER_CREATED.name()); Assertions.assertEquals("USER_DELETED", NotificationGroup.USER_DELETED.name()); } + + @Test + void updateGroupShouldBeIndependentlySelectableEvent() { + assertThat(NotificationGroup.valueOf("POLICY_VIOLATION_UPDATED")) + .isNotEqualTo(NotificationGroup.POLICY_VIOLATION); + assertThat(NotificationGroup.POLICY_VIOLATION_UPDATED.getSupportedTriggerType()) + .isEqualTo(NotificationTriggerType.EVENT); + assertThat(NotificationGroup.POLICY_VIOLATION.getSupportedTriggerType()) + .isEqualTo(NotificationTriggerType.EVENT); + } + + @Test + void reviewedUpdateGroupShouldRequireItsOwnEventSubscription() { + assertThat(NotificationGroup.valueOf("POLICY_VIOLATION_UPDATED_REVIEWED")) + .isNotEqualTo(NotificationGroup.POLICY_VIOLATION_UPDATED) + .isNotEqualTo(NotificationGroup.POLICY_VIOLATION); + assertThat(NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED.getSupportedTriggerType()) + .isEqualTo(NotificationTriggerType.EVENT); + } } diff --git a/apiserver/src/test/java/org/dependencytrack/notification/NotificationModelConverterTest.java b/apiserver/src/test/java/org/dependencytrack/notification/NotificationModelConverterTest.java index aff4ac5175..619b91c286 100644 --- a/apiserver/src/test/java/org/dependencytrack/notification/NotificationModelConverterTest.java +++ b/apiserver/src/test/java/org/dependencytrack/notification/NotificationModelConverterTest.java @@ -21,6 +21,7 @@ import org.dependencytrack.model.Project; import org.dependencytrack.model.Tag; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import java.util.Set; @@ -30,6 +31,13 @@ class NotificationModelConverterTest { + @ParameterizedTest + @EnumSource(NotificationGroup.class) + void shouldRoundTripEveryNotificationGroup(NotificationGroup group) { + assertThat(NotificationModelConverter.convert(NotificationModelConverter.convert(group))) + .isEqualTo(group); + } + @ParameterizedTest @ValueSource(booleans = {true, false}) void shouldConvertProject(boolean isLatest) { diff --git a/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java b/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java index 253e2f63e3..9da015377a 100644 --- a/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java +++ b/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java @@ -30,6 +30,7 @@ import org.dependencytrack.notification.proto.v1.Group; import org.dependencytrack.notification.proto.v1.Level; import org.dependencytrack.notification.proto.v1.Notification; +import org.dependencytrack.notification.proto.v1.PolicyViolationUpdatedSubject; import org.dependencytrack.notification.proto.v1.Scope; import org.jdbi.v3.core.Handle; import org.junit.jupiter.api.AfterEach; @@ -361,6 +362,164 @@ void routeShouldHandleAllNotificationTypes(final Notification notification) { } } + @Test + void shouldRequireIndependentUpdateSubscription() { + final var legacyRule = new NotificationRule(); + legacyRule.setName("creation-only"); + legacyRule.setTriggerType(NotificationTriggerType.EVENT); + legacyRule.setScope(NotificationScope.PORTFOLIO); + legacyRule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION)); + legacyRule.setNotificationLevel(NotificationLevel.INFORMATIONAL); + legacyRule.setEnabled(true); + qm.persist(legacyRule); + + final Notification updated = TestNotificationFactory.createPolicyViolationUpdatedTestNotification(); + assertThat(router.route(List.of(updated))).isEmpty(); + + final var updateRule = new NotificationRule(); + updateRule.setName("updates"); + updateRule.setTriggerType(NotificationTriggerType.EVENT); + updateRule.setScope(NotificationScope.PORTFOLIO); + updateRule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED)); + updateRule.setNotificationLevel(NotificationLevel.INFORMATIONAL); + updateRule.setEnabled(true); + updateRule.setFilterExpression("group == Group.GROUP_POLICY_VIOLATION_UPDATED" + + " && subject.previous_message == 'CVE-2021-44228'" + + " && subject.current_message.contains('CVE-2021-45046')"); + qm.persist(updateRule); + + final var filteredRule = new NotificationRule(); + filteredRule.setName("filtered-out"); + filteredRule.setTriggerType(NotificationTriggerType.EVENT); + filteredRule.setScope(NotificationScope.PORTFOLIO); + filteredRule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED)); + filteredRule.setNotificationLevel(NotificationLevel.INFORMATIONAL); + filteredRule.setEnabled(true); + filteredRule.setFilterExpression("subject.current_message == 'unmatched'"); + qm.persist(filteredRule); + + assertThat(router.route(List.of(updated))).satisfiesExactly(result -> { + assertThat(result.ruleNames()).containsOnly("updates"); + assertThat(result.notification()).isEqualTo(updated); + }); + } + + @Test + void shouldApplyProjectAndTagLimitsToUpdates() throws Exception { + final var tag = qm.persist(new Tag("selected")); + final var project = new Project(); + project.setName("selected-project"); + project.setTags(Set.of(tag)); + qm.persist(project); + final var otherProject = new Project(); + otherProject.setName("other-project"); + qm.persist(otherProject); + + final var allowed = new NotificationRule(); + allowed.setName("allowed"); + allowed.setTriggerType(NotificationTriggerType.EVENT); + allowed.setScope(NotificationScope.PORTFOLIO); + allowed.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED)); + allowed.setNotificationLevel(NotificationLevel.INFORMATIONAL); + allowed.setEnabled(true); + allowed.setProjects(List.of(project)); + allowed.setTags(Set.of(tag)); + qm.persist(allowed); + final var denied = new NotificationRule(); + denied.setName("other-project"); + denied.setTriggerType(NotificationTriggerType.EVENT); + denied.setScope(NotificationScope.PORTFOLIO); + denied.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED)); + denied.setNotificationLevel(NotificationLevel.INFORMATIONAL); + denied.setEnabled(true); + denied.setProjects(List.of(otherProject)); + qm.persist(denied); + + final var builder = TestNotificationFactory.createPolicyViolationUpdatedTestNotification().toBuilder(); + final var subject = builder.getSubject().unpack(PolicyViolationUpdatedSubject.class).toBuilder() + .setProject(convert(project)) + .build(); + final Notification updated = builder.setSubject(Any.pack(subject)).build(); + + assertThat(router.route(List.of(updated))).satisfiesExactly(result -> { + assertThat(result.ruleNames()).containsOnly("allowed"); + }); + } + + @Test + void shouldRequireExplicitReviewedSubscriptionEvenWhenOrdinaryFilterFailsOpen() { + final var ordinary = new NotificationRule(); + ordinary.setName("ordinary-updates"); + ordinary.setTriggerType(NotificationTriggerType.EVENT); + ordinary.setScope(NotificationScope.PORTFOLIO); + ordinary.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED)); + ordinary.setNotificationLevel(NotificationLevel.INFORMATIONAL); + ordinary.setEnabled(true); + ordinary.setFilterExpression("this is not valid CEL"); + qm.persist(ordinary); + final Notification reviewed = TestNotificationFactory.createReviewedPolicyViolationUpdatedTestNotification(); + assertThat(router.route(List.of(reviewed))).isEmpty(); + + final var optIn = new NotificationRule(); + optIn.setName("reviewed-opt-in"); + optIn.setTriggerType(NotificationTriggerType.EVENT); + optIn.setScope(NotificationScope.PORTFOLIO); + optIn.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + optIn.setNotificationLevel(NotificationLevel.INFORMATIONAL); + optIn.setEnabled(true); + optIn.setFilterExpression("group == Group.GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" + + " && subject.analysis_state == 'APPROVED' && subject.suppressed" + + " && subject.current_message.contains('CVE-2021-45046')"); + qm.persist(optIn); + assertThat(router.route(List.of(reviewed))).satisfiesExactly(result -> { + assertThat(result.ruleNames()).containsOnly("reviewed-opt-in"); + assertThat(result.notification()).isEqualTo(reviewed); + }); + assertThat(router.route(List.of(TestNotificationFactory.createPolicyViolationUpdatedTestNotification()))) + .satisfiesExactly(result -> assertThat(result.ruleNames()).containsOnly("ordinary-updates")); + } + + @Test + void shouldApplyProjectAndTagLimitsToReviewedUpdates() throws Exception { + final var tag = qm.persist(new Tag("reviewed-selected")); + final var project = new Project(); + project.setName("reviewed-project"); + project.setTags(Set.of(tag)); + qm.persist(project); + final var other = new Project(); + other.setName("other-reviewed-project"); + qm.persist(other); + final var allowed = new NotificationRule(); + allowed.setName("reviewed-project-opt-in"); + allowed.setTriggerType(NotificationTriggerType.EVENT); + allowed.setScope(NotificationScope.PORTFOLIO); + allowed.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + allowed.setNotificationLevel(NotificationLevel.INFORMATIONAL); + allowed.setEnabled(true); + allowed.setProjects(List.of(project)); + allowed.setTags(Set.of(tag)); + qm.persist(allowed); + final var denied = new NotificationRule(); + denied.setName("other-reviewed-project-opt-in"); + denied.setTriggerType(NotificationTriggerType.EVENT); + denied.setScope(NotificationScope.PORTFOLIO); + denied.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + denied.setNotificationLevel(NotificationLevel.INFORMATIONAL); + denied.setEnabled(true); + denied.setProjects(List.of(other)); + qm.persist(denied); + final var builder = TestNotificationFactory.createReviewedPolicyViolationUpdatedTestNotification().toBuilder(); + final var subject = builder.getSubject().unpack(PolicyViolationUpdatedSubject.class).toBuilder() + .setProject(convert(project)) + .build(); + final Notification reviewed = builder.setSubject(Any.pack(subject)).build(); + assertThat(router.route(List.of(reviewed))) + .satisfiesExactly(result -> assertThat(result.ruleNames()).containsOnly("reviewed-project-opt-in")); + allowed.setEnabled(false); + qm.persist(allowed); + assertThat(router.route(List.of(reviewed))).isEmpty(); + } + @Nested class FilterExpressionTest { diff --git a/apiserver/src/test/java/org/dependencytrack/notification/NotificationSubjectDaoTest.java b/apiserver/src/test/java/org/dependencytrack/notification/NotificationSubjectDaoTest.java index 7be9faf7e6..30a4e1ba2e 100644 --- a/apiserver/src/test/java/org/dependencytrack/notification/NotificationSubjectDaoTest.java +++ b/apiserver/src/test/java/org/dependencytrack/notification/NotificationSubjectDaoTest.java @@ -43,14 +43,21 @@ import org.dependencytrack.persistence.command.MakeViolationAnalysisCommand; import org.dependencytrack.persistence.jdbi.KevDao; import org.dependencytrack.persistence.jdbi.VulnerabilityAliasDao; +import org.jdbi.v3.core.statement.SqlLogger; +import org.jdbi.v3.core.statement.SqlStatements; +import org.jdbi.v3.core.statement.StatementContext; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import java.math.BigDecimal; +import java.util.ArrayList; import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Set; +import java.util.concurrent.atomic.AtomicInteger; import static net.javacrumbs.jsonunit.assertj.JsonAssertions.assertThatJson; import static org.assertj.core.api.Assertions.assertThat; @@ -974,4 +981,171 @@ public void shouldReturnEmptyForNewPolicyViolationsWithEmptyInput() { assertThat(subjects).isEmpty(); } + + @ParameterizedTest + @ValueSource(strings = {"NONE", "REJECTED", "APPROVED"}) + void shouldIgnoreReviewRowsForOtherComponentsOrProjects(String state) { + final var project = new Project(); + project.setName("review-owner"); + qm.persist(project); + final var otherProject = new Project(); + otherProject.setName("other-review-owner"); + qm.persist(otherProject); + final var component = new Component(); + component.setProject(project); + component.setName("reviewed-component"); + qm.persist(component); + final var otherComponent = new Component(); + otherComponent.setProject(project); + otherComponent.setName("other-component"); + qm.persist(otherComponent); + final var policy = qm.createPolicy("review-owner", Policy.Operator.ANY, Policy.ViolationState.FAIL); + final var condition = qm.createPolicyCondition(policy, Subject.EXPRESSION, Operator.MATCHES, "true"); + final var violation = new PolicyViolation(); + violation.setComponent(component); + violation.setPolicyCondition(condition); + violation.setType(PolicyViolation.Type.SECURITY); + violation.setTimestamp(new Date()); + qm.persist(violation); + + final boolean reviewed = "APPROVED".equals(state); + if (!"NONE".equals(state)) { + qm.makeViolationAnalysis(new MakeViolationAnalysisCommand(component, violation) + .withState(ViolationAnalysisState.valueOf(state)) + .withSuppress(false) + .withOptions(Set.of(MakeViolationAnalysisCommand.Option.OMIT_NOTIFICATION))); + } + // The database's separate foreign keys permit inconsistent component/project tuples. + useJdbiTransaction(handle -> handle.createUpdate(""" + INSERT INTO "VIOLATIONANALYSIS" + ("PROJECT_ID", "COMPONENT_ID", "POLICYVIOLATION_ID", "STATE", "SUPPRESSED") + VALUES (:projectId, :otherComponentId, :violationId, :state, :suppressed), + (:otherProjectId, :componentId, :violationId, :state, :suppressed) + """) + .bind("projectId", project.getId()) + .bind("otherProjectId", otherProject.getId()) + .bind("componentId", component.getId()) + .bind("otherComponentId", otherComponent.getId()) + .bind("violationId", violation.getId()) + .bind("state", reviewed ? "REJECTED" : "APPROVED") + .bind("suppressed", !reviewed) + .execute()); + + withJdbiHandle(handle -> { + assertThat(handle.createQuery(""" + SELECT COUNT(*) FROM "VIOLATIONANALYSIS" WHERE "POLICYVIOLATION_ID" = :id + """) + .bind("id", violation.getId()) + .mapTo(Integer.class) + .one()) + .isEqualTo("NONE".equals(state) ? 2 : 3); + final var dao = handle.attach(NotificationSubjectDao.class); + final var ids = List.of(violation.getId()); + assertThat(dao.getForPolicyViolationUpdates(ids, true, true)) + .singleElement() + .satisfies(row -> { + assertThat(row.subject().getPolicyViolation().getUuid()) + .isEqualTo(violation.getUuid().toString()); + assertThat(row.analysisState()).isEqualTo("NONE".equals(state) ? null : state); + assertThat(row.suppressed()).isEqualTo("NONE".equals(state) ? null : Boolean.FALSE); + assertThat(row.isReviewed()).isEqualTo(reviewed); + }); + assertThat(dao.getForPolicyViolationUpdates(ids, true, false)).hasSize(reviewed ? 0 : 1); + assertThat(dao.getForPolicyViolationUpdates(ids, false, true)).hasSize(reviewed ? 1 : 0); + assertThat(dao.getForNewPolicyViolations(ids)).hasSize(reviewed ? 0 : 1); + return null; + }); + } + + @Test + void shouldPartitionUpdateSubjectsOnceWithCapturedNullableReviewMetadata() { + final var project = new Project(); + project.setName("partitioned-updates"); + qm.persist(project); + final var policy = qm.createPolicy("partitioned", Policy.Operator.ANY, Policy.ViolationState.FAIL); + final var condition = qm.createPolicyCondition(policy, Subject.EXPRESSION, Operator.MATCHES, "true"); + final var ids = new ArrayList(); + final var expectedStates = new HashMap(); + final var expectedSuppressed = new HashMap(); + final var reviewedUuids = new HashSet(); + final var activeUuids = new HashSet(); + + for (int index = 0; index < 7; index++) { + final var component = new Component(); + component.setProject(project); + component.setName("component-" + index); + qm.persist(component); + final var violation = new PolicyViolation(); + violation.setComponent(component); + violation.setPolicyCondition(condition); + violation.setType(PolicyViolation.Type.SECURITY); + violation.setTimestamp(new Date()); + violation.setText("CVE-A,CVE-B"); + qm.persist(violation); + ids.add(violation.getId()); + final String uuid = violation.getUuid().toString(); + if (index == 0) { + expectedStates.put(uuid, null); + expectedSuppressed.put(uuid, null); + activeUuids.add(uuid); + continue; + } + final var state = List.of( + ViolationAnalysisState.NOT_SET, + ViolationAnalysisState.REJECTED, + ViolationAnalysisState.APPROVED) + .get((index - 1) / 2); + final boolean suppressed = index % 2 == 0; + qm.makeViolationAnalysis(new MakeViolationAnalysisCommand(component, violation) + .withState(state) + .withSuppress(suppressed) + .withOptions(Set.of(MakeViolationAnalysisCommand.Option.OMIT_NOTIFICATION))); + expectedStates.put(uuid, state.name()); + expectedSuppressed.put(uuid, suppressed); + if (state == ViolationAnalysisState.APPROVED || suppressed) { + reviewedUuids.add(uuid); + } else { + activeUuids.add(uuid); + } + } + assertThat(activeUuids).hasSize(3); + assertThat(reviewedUuids).hasSize(4); + final var statements = new AtomicInteger(); + final var both = withJdbiHandle(handle -> { + handle.getConfig(SqlStatements.class).setSqlLogger(new SqlLogger() { + @Override + public void logAfterExecution(StatementContext context) { + statements.incrementAndGet(); + } + }); + return handle.attach(NotificationSubjectDao.class).getForPolicyViolationUpdates(ids, true, true); + }); + assertThat(statements.get()).isEqualTo(1); + assertThat(both).hasSize(7); + assertThat(both) + .extracting(row -> row.subject().getPolicyViolation().getUuid()) + .doesNotHaveDuplicates(); + both.forEach(row -> { + final String uuid = row.subject().getPolicyViolation().getUuid(); + assertThat(row.analysisState()).isEqualTo(expectedStates.get(uuid)); + assertThat(row.suppressed()).isEqualTo(expectedSuppressed.get(uuid)); + assertThat(row.isReviewed()).isEqualTo(reviewedUuids.contains(uuid)); + assertThat(row.subject().getPolicyViolation().getMessage()).isEqualTo("CVE-A,CVE-B"); + }); + withJdbiHandle(handle -> { + final var dao = handle.attach(NotificationSubjectDao.class); + assertThat(dao.getForPolicyViolationUpdates(ids, true, false)) + .extracting(row -> row.subject().getPolicyViolation().getUuid()) + .containsExactlyInAnyOrderElementsOf(activeUuids); + assertThat(dao.getForPolicyViolationUpdates(ids, false, true)) + .extracting(row -> row.subject().getPolicyViolation().getUuid()) + .containsExactlyInAnyOrderElementsOf(reviewedUuids); + assertThat(dao.getForNewPolicyViolations(ids)) + .extracting(row -> row.getPolicyViolation().getUuid()) + .containsExactlyInAnyOrderElementsOf(activeUuids); + assertThat(dao.getForPolicyViolationUpdates(ids, false, false)).isEmpty(); + assertThat(dao.getForPolicyViolationUpdates(List.of(), true, true)).isEmpty(); + return null; + }); + } } diff --git a/apiserver/src/test/java/org/dependencytrack/notification/PolicyViolationUpdatedIntegrationTest.java b/apiserver/src/test/java/org/dependencytrack/notification/PolicyViolationUpdatedIntegrationTest.java new file mode 100644 index 0000000000..aacdd65830 --- /dev/null +++ b/apiserver/src/test/java/org/dependencytrack/notification/PolicyViolationUpdatedIntegrationTest.java @@ -0,0 +1,806 @@ +/* + * This file is part of Dependency-Track. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * Copyright (c) OWASP Foundation. All Rights Reserved. + */ +package org.dependencytrack.notification; + +import com.google.protobuf.util.Timestamps; +import com.sun.net.httpserver.HttpServer; +import io.github.resilience4j.core.IntervalFunction; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import io.smallrye.config.SmallRyeConfigBuilder; +import org.dependencytrack.PersistenceCapableTest; +import org.dependencytrack.cache.api.NoopCacheManager; +import org.dependencytrack.common.datasource.DataSourceRegistry; +import org.dependencytrack.dex.activity.DeleteFilesActivity; +import org.dependencytrack.dex.engine.api.DexEngine; +import org.dependencytrack.dex.engine.api.TaskType; +import org.dependencytrack.dex.engine.api.TaskWorkerOptions; +import org.dependencytrack.dex.engine.api.WorkflowRunStatus; +import org.dependencytrack.dex.engine.api.request.CreateTaskQueueRequest; +import org.dependencytrack.dex.engine.api.request.ListWorkflowRunsRequest; +import org.dependencytrack.dex.testing.WorkflowTestExtension; +import org.dependencytrack.filestorage.api.FileStorage; +import org.dependencytrack.filestorage.memory.MemoryFileStorage; +import org.dependencytrack.kevdatasource.api.KevAssertion; +import org.dependencytrack.model.Component; +import org.dependencytrack.model.NotificationRule; +import org.dependencytrack.model.NotificationTriggerType; +import org.dependencytrack.model.Policy; +import org.dependencytrack.model.PolicyCondition; +import org.dependencytrack.model.PolicyViolation; +import org.dependencytrack.model.Project; +import org.dependencytrack.model.Severity; +import org.dependencytrack.model.ViolationAnalysisState; +import org.dependencytrack.model.Vulnerability; +import org.dependencytrack.model.VulnerabilityKey; +import org.dependencytrack.notification.api.publishing.NotificationPublisher; +import org.dependencytrack.notification.proto.v1.Group; +import org.dependencytrack.notification.proto.v1.Notification; +import org.dependencytrack.notification.proto.v1.PolicyViolationUpdatedSubject; +import org.dependencytrack.notification.publishing.DefaultNotificationPublishersPlugin; +import org.dependencytrack.notification.templating.pebble.PebbleNotificationTemplateRendererFactory; +import org.dependencytrack.persistence.command.MakeAnalysisCommand; +import org.dependencytrack.persistence.command.MakeViolationAnalysisCommand; +import org.dependencytrack.persistence.jdbi.JdbiFactory; +import org.dependencytrack.persistence.jdbi.KevDao; +import org.dependencytrack.plugin.runtime.PluginManager; +import org.dependencytrack.policy.cel.CelPolicyEngine; +import org.dependencytrack.proto.internal.workflow.v1.DeleteFilesArgument; +import org.dependencytrack.proto.internal.workflow.v1.PublishNotificationActivityArg; +import org.dependencytrack.proto.internal.workflow.v1.PublishNotificationWorkflowArg; +import org.dependencytrack.support.net.OutboundConnectionPolicy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +import java.net.InetSocketAddress; +import java.net.http.HttpClient; +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.awaitility.Awaitility.await; +import static org.dependencytrack.dex.api.payload.PayloadConverters.protoConverter; +import static org.dependencytrack.dex.api.payload.PayloadConverters.voidConverter; +import static org.dependencytrack.notification.NotificationTestUtil.getNotificationOutbox; +import static org.dependencytrack.persistence.jdbi.JdbiFactory.useJdbiTransaction; + +/** Exercises the production CEL, PostgreSQL outbox, router, workflow and HTTP publisher together. */ +class PolicyViolationUpdatedIntegrationTest extends PersistenceCapableTest { + + private static final String KEV_A = "CVE-2021-44228"; + private static final String KEV_B = "CVE-2021-45046"; + private static final String KEV_C = "CVE-2099-00001"; + private static final String EXPRESSION = """ + vulns.filter(v, v.is_kev).map(v, v.id).join(",") + """; + + @RegisterExtension + private final WorkflowTestExtension workflowTest = + new WorkflowTestExtension(DataSourceRegistry.getInstance().getDefault()); + + private final List received = new CopyOnWriteArrayList<>(); + private final AtomicInteger failuresRemaining = new AtomicInteger(); + private final AtomicInteger receiverStatus = new AtomicInteger(204); + private PluginManager pluginManager; + private FileStorage fileStorage; + private HttpServer receiver; + private Project project; + private Component component; + private PolicyCondition condition; + private NotificationRule rule; + + @BeforeEach + void setUpPipeline() throws Exception { + // Bind only to loopback. Every HTTP request in this test remains on this machine. + receiver = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + receiver.createContext("/notifications", exchange -> { + try (exchange) { + final Notification notification = Notification.parseFrom(exchange.getRequestBody()); + received.add(notification); + final int status = failuresRemaining.getAndUpdate(value -> Math.max(0, value - 1)) > 0 + ? 503 + : receiverStatus.get(); + exchange.sendResponseHeaders(status, -1); + } + }); + receiver.start(); + + pluginManager = new PluginManager( + new SmallRyeConfigBuilder().build(), + new NoopCacheManager(), + secretName -> null, + JdbiFactory.createJdbi(), + HttpClient.newHttpClient(), + OutboundConnectionPolicy.of(List.of("127.0.0.1")), + List.of(NotificationPublisher.class)); + pluginManager.loadPlugins(List.of(new DefaultNotificationPublishersPlugin())); + fileStorage = new MemoryFileStorage(); + + final DexEngine engine = workflowTest.getEngine(); + engine.registerWorkflow( + new PublishNotificationWorkflow(), + protoConverter(PublishNotificationWorkflowArg.class), + voidConverter(), + Duration.ofSeconds(30)); + engine.registerActivity( + new PublishNotificationActivity( + pluginManager, + fileStorage, + secretName -> null, + new PebbleNotificationTemplateRendererFactory(Collections.emptyMap())), + protoConverter(PublishNotificationActivityArg.class), + voidConverter()); + engine.registerActivity( + new DeleteFilesActivity(fileStorage), protoConverter(DeleteFilesArgument.class), voidConverter()); + engine.createTaskQueue(new CreateTaskQueueRequest(TaskType.WORKFLOW, "default", 1)); + engine.createTaskQueue(new CreateTaskQueueRequest(TaskType.ACTIVITY, "default", 1)); + engine.createTaskQueue(new CreateTaskQueueRequest(TaskType.ACTIVITY, "notifications", 1)); + engine.registerTaskWorker(new TaskWorkerOptions(TaskType.WORKFLOW, "workflow-worker", "default", 1) + .withMinPollInterval(Duration.ofMillis(25)) + .withPollBackoffFunction(IntervalFunction.of(25))); + engine.registerTaskWorker(new TaskWorkerOptions(TaskType.ACTIVITY, "activity-worker", "notifications", 1) + .withMinPollInterval(Duration.ofMillis(25)) + .withPollBackoffFunction(IntervalFunction.of(25))); + engine.start(); + + project = new Project(); + project.setName("isolated-kev-project"); + qm.persist(project); + component = new Component(); + component.setProject(project); + component.setName("log4j-core"); + component.setVersion("2.14.1"); + qm.persist(component); + for (final String id : List.of(KEV_A, KEV_B, KEV_C)) { + final var vulnerability = new Vulnerability(); + vulnerability.setSource(Vulnerability.Source.NVD); + vulnerability.setVulnId(id); + vulnerability.setSeverity(Severity.CRITICAL); + qm.persist(vulnerability); + qm.addVulnerability(vulnerability, component, "local-test"); + } + final Policy policy = qm.createPolicy("KEV policy", Policy.Operator.ANY, Policy.ViolationState.FAIL); + condition = qm.createPolicyCondition( + policy, + PolicyCondition.Subject.EXPRESSION, + PolicyCondition.Operator.MATCHES, + EXPRESSION, + PolicyViolation.Type.SECURITY); + final var publisher = new org.dependencytrack.model.NotificationPublisher(); + publisher.setName("Loopback webhook"); + publisher.setExtensionName("webhook"); + qm.persist(publisher); + rule = new NotificationRule(); + rule.setName("Local opt-in updates"); + rule.setEnabled(true); + rule.setTriggerType(NotificationTriggerType.EVENT); + rule.setScope(NotificationScope.PORTFOLIO); + rule.setNotificationLevel(NotificationLevel.INFORMATIONAL); + rule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION, NotificationGroup.POLICY_VIOLATION_UPDATED)); + rule.setPublisher(publisher); + rule.setPublisherConfig(""" + {"destinationUrl":"http://127.0.0.1:%d/notifications","publishProtobuf":true} + """.formatted(receiver.getAddress().getPort())); + qm.persist(rule); + } + + @AfterEach + void tearDownPipeline() throws Exception { + // Stop workers before closing their dependencies. + try { + workflowTest.getEngine().close(); + } finally { + try { + if (pluginManager != null) { + pluginManager.close(); + } + } finally { + if (receiver != null) { + receiver.stop(0); + } + } + } + } + + @Test + void shouldDeliverCreationAndExactlyOneUpdateForSecondKev() throws Exception { + setKevs(KEV_A); + evaluateAndDeliver(1); + final PolicyViolation initial = violation(); + final UUID violationUuid = initial.getUuid(); + assertThat(received).extracting(Notification::getGroup).containsExactly(Group.GROUP_POLICY_VIOLATION); + + evaluateAndDeliver(0); + assertThat(received).hasSize(1); + assertThat(violation().getUuid()).isEqualTo(violationUuid); + + setKevs(KEV_A, KEV_B); + final var beforeChange = java.time.Instant.now(); + evaluateAndDeliver(1); + assertThat(received).hasSize(2); + final Notification update = received.getLast(); + assertThat(update.getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + final PolicyViolationUpdatedSubject subject = update.getSubject().unpack(PolicyViolationUpdatedSubject.class); + assertThat(subject.getPreviousMessage()).isEqualTo(KEV_A); + assertThat(subject.getCurrentMessage()).isEqualTo(KEV_A + "," + KEV_B); + assertThat(subject.getPolicyViolation().getUuid()).isEqualTo(violationUuid.toString()); + assertThat(subject.getPolicyViolation().getMessage()).isEqualTo(subject.getCurrentMessage()); + assertThat(subject.getProject().getUuid()).isEqualTo(project.getUuid().toString()); + assertThat(subject.getComponent().getUuid()) + .isEqualTo(component.getUuid().toString()); + assertThat(Timestamps.toMillis(subject.getChangedAt())).isGreaterThanOrEqualTo(beforeChange.toEpochMilli()); + assertThat(violation().getUuid()).isEqualTo(violationUuid); + assertThat(violation().getText()).isEqualTo(subject.getCurrentMessage()); + + evaluateAndDeliver(0); + assertThat(received).hasSize(2); + // An analysis write which leaves the active KEV set unchanged must not create a new event. + qm.makeAnalysis(new MakeAnalysisCommand(component, qm.getVulnerabilityByVulnId(Vulnerability.Source.NVD, KEV_B)) + .withSuppress(false) + .withOptions(Set.of(MakeAnalysisCommand.Option.OMIT_NOTIFICATION))); + evaluateAndDeliver(0); + assertThat(received).hasSize(2); + } + + @Test + void shouldPublishNullSafeMessageTransitionsFromBooleanAndStringConditions() throws Exception { + setKevs(KEV_A); + condition.setValue("true"); + qm.persist(condition); + evaluateAndDeliver(1); + final UUID originalUuid = violation().getUuid(); + assertThat(violation().getText()).isNull(); + assertThat(received.getFirst() + .getSubject() + .unpack(org.dependencytrack.notification.proto.v1.PolicyViolationSubject.class) + .getPolicyViolation() + .hasMessage()) + .isFalse(); + evaluateAndDeliver(0); + + condition.setValue(EXPRESSION); + qm.persist(condition); + evaluateAndDeliver(1); + final var populated = received.getLast().getSubject().unpack(PolicyViolationUpdatedSubject.class); + assertThat(received.getLast().getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + assertThat(populated.getPolicyViolation().getUuid()).isEqualTo(originalUuid.toString()); + assertThat(populated.hasPreviousMessage()).isFalse(); + assertThat(populated.hasCurrentMessage()).isTrue(); + assertThat(populated.getCurrentMessage()).isEqualTo(KEV_A); + assertThat(populated.getPolicyViolation().hasMessage()).isTrue(); + assertThat(populated.getPolicyViolation().getMessage()).isEqualTo(populated.getCurrentMessage()); + assertThat(violation().getText()).isEqualTo(KEV_A); + evaluateAndDeliver(0); + + condition.setValue("true"); + qm.persist(condition); + evaluateAndDeliver(1); + final var cleared = received.getLast().getSubject().unpack(PolicyViolationUpdatedSubject.class); + assertThat(received.getLast().getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + assertThat(cleared.getPolicyViolation().getUuid()).isEqualTo(originalUuid.toString()); + assertThat(cleared.hasPreviousMessage()).isTrue(); + assertThat(cleared.getPreviousMessage()).isEqualTo(KEV_A); + assertThat(cleared.hasCurrentMessage()).isFalse(); + assertThat(cleared.getPolicyViolation().hasMessage()).isFalse(); + assertThat(violation().getUuid()).isEqualTo(originalUuid); + assertThat(violation().getText()).isNull(); + evaluateAndDeliver(0); + assertThat(received).hasSize(3); + } + + @Test + void shouldDetectRemovalAndEqualSizeMatchReplacementAndRecreation() throws Exception { + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(1); + final UUID originalUuid = violation().getUuid(); + setKevs(KEV_B); + evaluateAndDeliver(1); + assertUpdate(received.getLast(), KEV_A + "," + KEV_B, KEV_B, originalUuid); + setKevs(KEV_C); + evaluateAndDeliver(1); + assertUpdate(received.getLast(), KEV_B, KEV_C, originalUuid); + setKevs(); + evaluateAndDeliver(0); + assertThat(qm.getAllPolicyViolations(component)).isEmpty(); + setKevs(KEV_A); + evaluateAndDeliver(1); + assertThat(received.getLast().getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION); + assertThat(violation().getUuid()).isNotEqualTo(originalUuid); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void shouldRespectExistingApprovedAndSuppressedDecisions(boolean suppressed) throws Exception { + setKevs(KEV_A); + evaluateAndDeliver(1); + final PolicyViolation initial = violation(); + final var state = suppressed ? ViolationAnalysisState.REJECTED : ViolationAnalysisState.APPROVED; + qm.makeViolationAnalysis(new MakeViolationAnalysisCommand(component, initial) + .withState(state) + .withSuppress(suppressed) + .withOptions(Set.of(MakeViolationAnalysisCommand.Option.OMIT_NOTIFICATION))); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(0); + assertThat(received).hasSize(1); + final PolicyViolation updated = violation(); + assertThat(updated.getUuid()).isEqualTo(initial.getUuid()); + assertThat(updated.getText()).isEqualTo(KEV_A + "," + KEV_B); + final var analysis = qm.getViolationAnalysis(component, updated); + assertThat(analysis.getAnalysisState()).isEqualTo(state); + assertThat(analysis.isSuppressed()).isEqualTo(suppressed); + + // Clearing a decision is not a message transition; do not replay previously filtered updates. + qm.makeViolationAnalysis(new MakeViolationAnalysisCommand(component, updated) + .withState(ViolationAnalysisState.NOT_SET) + .withSuppress(false) + .withOptions(Set.of(MakeViolationAnalysisCommand.Option.OMIT_NOTIFICATION))); + evaluateAndDeliver(0); + assertThat(received).hasSize(1); + setKevs(KEV_C); + evaluateAndDeliver(1); + assertUpdate(received.getLast(), KEV_A + "," + KEV_B, KEV_C, initial.getUuid()); + assertThat(received).hasSize(2); + } + + private static Stream reviewedDecisions() { + return Stream.of( + Arguments.of(ViolationAnalysisState.APPROVED, false), + Arguments.of(ViolationAnalysisState.REJECTED, true), + Arguments.of(ViolationAnalysisState.APPROVED, true)); + } + + @ParameterizedTest + @MethodSource("reviewedDecisions") + void shouldDeliverReviewedChangesOnlyToExplicitSubscribersWithoutResettingDecisions( + ViolationAnalysisState state, boolean suppressed) throws Exception { + rule.setNotifyOn(Set.of( + NotificationGroup.POLICY_VIOLATION, + NotificationGroup.POLICY_VIOLATION_UPDATED, + NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + qm.persist(rule); + final List ordinaryUpdates = addOrdinaryUpdateReceiver(); + setKevs(KEV_A); + evaluateAndDeliver(1); + final UUID originalUuid = violation().getUuid(); + review(state, suppressed); + evaluateAndDeliver(0); // A review decision alone is not a message transition. + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(1); + assertThat(received).hasSize(2); + assertThat(ordinaryUpdates).isEmpty(); + assertReviewedUpdate(received.getLast(), KEV_A, KEV_A + "," + KEV_B, originalUuid, state, suppressed); + final var analysis = qm.getViolationAnalysis(component, violation()); + assertThat(analysis.getAnalysisState()).isEqualTo(state); + assertThat(analysis.isSuppressed()).isEqualTo(suppressed); + evaluateAndDeliver(0); + assertThat(received).hasSize(2); + + review(ViolationAnalysisState.NOT_SET, false); + evaluateAndDeliver(0); // Do not replay a reviewed transition after clearing the decision. + assertThat(received).hasSize(2); + setKevs(KEV_A, KEV_B, KEV_C); + evaluateAndDeliver(1); + assertThat(received).hasSize(3); + assertUpdate(received.getLast(), KEV_A + "," + KEV_B, KEV_A + "," + KEV_B + "," + KEV_C, originalUuid); + assertThat(ordinaryUpdates).containsExactly(received.getLast()); + assertThat(received).extracting(Notification::getId).doesNotHaveDuplicates(); + } + + @Test + void rejectedUnsuppressedDecisionShouldStillUseTheOrdinaryUpdateGroup() throws Exception { + rule.setNotifyOn(Set.of( + NotificationGroup.POLICY_VIOLATION, + NotificationGroup.POLICY_VIOLATION_UPDATED, + NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + qm.persist(rule); + setKevs(KEV_A); + evaluateAndDeliver(1); + final UUID originalUuid = violation().getUuid(); + review(ViolationAnalysisState.REJECTED, false); + evaluateAndDeliver(0); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(1); + assertThat(received).hasSize(2); + assertUpdate(received.getLast(), KEV_A, KEV_A + "," + KEV_B, originalUuid); + final var subject = received.getLast().getSubject().unpack(PolicyViolationUpdatedSubject.class); + // Ordinary subscribers retain the previous payload shape; review metadata is opt-in. + assertThat(subject.hasAnalysisState()).isFalse(); + assertThat(subject.hasSuppressed()).isFalse(); + final var analysis = qm.getViolationAnalysis(component, violation()); + assertThat(analysis.getAnalysisState()).isEqualTo(ViolationAnalysisState.REJECTED); + assertThat(analysis.isSuppressed()).isFalse(); + evaluateAndDeliver(0); + assertThat(received).hasSize(2); + } + + @Test + void reviewedOnlySubscriberShouldNotReceiveActiveChangesOrHistoricalTransitions() throws Exception { + rule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + qm.persist(rule); + setKevs(KEV_A); + evaluateAndDeliver(0); // No creation subscriber is configured. + final UUID originalUuid = violation().getUuid(); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(0); // Active updates remain in the ordinary group. + review(ViolationAnalysisState.APPROVED, false); + evaluateAndDeliver(0); // A decision change does not replay the previous active change. + rule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED)); + qm.persist(rule); + setKevs(KEV_B); + evaluateAndDeliver(0); // Without the reviewed opt-in, this reviewed transition is consumed quietly. + rule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + qm.persist(rule); + evaluateAndDeliver(0); // Enabling the opt-in does not replay that historical reviewed change. + setKevs(KEV_A, KEV_B, KEV_C); + evaluateAndDeliver(1); + assertThat(received).hasSize(1); + assertReviewedUpdate( + received.getFirst(), + KEV_B, + KEV_A + "," + KEV_B + "," + KEV_C, + originalUuid, + ViolationAnalysisState.APPROVED, + false); + evaluateAndDeliver(0); + assertThat(received).hasSize(1); + } + + @Test + void shouldRetryReviewedChangeWithTheSameEventAndCapturedDecision() throws Exception { + rule.setNotifyOn( + Set.of(NotificationGroup.POLICY_VIOLATION, NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + qm.persist(rule); + setKevs(KEV_A); + evaluateAndDeliver(1); + final UUID originalUuid = violation().getUuid(); + review(ViolationAnalysisState.APPROVED, true); + failuresRemaining.set(1); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(1); + assertThat(received).hasSize(3); + assertThat(received.get(1)).isEqualTo(received.get(2)); + assertReviewedUpdate( + received.getLast(), KEV_A, KEV_A + "," + KEV_B, originalUuid, ViolationAnalysisState.APPROVED, true); + evaluateAndDeliver(0); + assertThat(received).hasSize(3); + } + + @Test + void shouldNotPublishUpdatesToCreationOnlySubscriber() throws Exception { + rule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION)); + qm.persist(rule); + setKevs(KEV_A); + evaluateAndDeliver(1); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(0); + assertThat(received).hasSize(1); + assertThat(violation().getText()).isEqualTo(KEV_A + "," + KEV_B); + } + + @Test + void shouldApplyProjectAndExpressionFiltersToUpdateSubject() throws Exception { + setKevs(KEV_A); + evaluateAndDeliver(1); + final var unrelatedProject = new Project(); + unrelatedProject.setName("unrelated-project"); + qm.persist(unrelatedProject); + rule.setProjects(List.of(unrelatedProject)); + qm.persist(rule); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(1, false); + assertThat(received).hasSize(1); + + rule.setProjects(List.of(project)); + rule.setFilterExpression("subject.current_message == '" + KEV_C + "'"); + qm.persist(rule); + setKevs(KEV_C); + evaluateAndDeliver(1); + assertThat(received).hasSize(2); + assertThat(received.getLast().getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + } + + @Test + void shouldRetryTransientWebhookFailureWithSameEventIdentity() throws Exception { + setKevs(KEV_A); + evaluateAndDeliver(1); + failuresRemaining.set(1); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(1); + assertThat(received).hasSize(3); + assertThat(received.get(1).getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + assertThat(received.get(1)).isEqualTo(received.get(2)); + // Retries redeliver the same durable event, rather than inventing another policy transition. + evaluateAndDeliver(0); + assertThat(received).hasSize(3); + } + + @Test + void shouldPersistPermanentWebhookFailureWithoutRegeneratingTheEvent() throws Exception { + setKevs(KEV_A); + evaluateAndDeliver(1); + receiverStatus.set(400); + setKevs(KEV_A, KEV_B); + final List events = evaluateAndDeliver(1, true, WorkflowRunStatus.FAILED); + assertThat(received).hasSize(2); + assertThat(received.getLast()).isEqualTo(events.getFirst()); + final var metadata = workflowTest + .getEngine() + .listRuns(new ListWorkflowRunsRequest() + .withWorkflowInstanceId( + "publish-notification:" + events.getFirst().getId())) + .items() + .getFirst(); + final var run = workflowTest.getEngine().getRunById(metadata.id()); + assertThat(run).isNotNull(); + assertThat(run.status()).isEqualTo(WorkflowRunStatus.FAILED); + assertThat(run.failure()).isNotNull(); + assertThat(run.failure().getMessage()).isEqualTo("Publishing failed for all applicable rules"); + assertThat(run.eventHistory()).anySatisfy(event -> { + assertThat(event.hasActivityTaskFailed()).isTrue(); + assertThat(event.getActivityTaskFailed().getFailure().getCause().getMessage()) + .contains("unexpected response code: 400"); + }); + assertThat(getNotificationOutbox()).isEmpty(); + evaluateAndDeliver(0); + assertThat(received).hasSize(2); + } + + @Test + void shouldDeliverIndependentUpdatesForMultipleComponentsAndConditions() throws Exception { + final var secondComponent = new Component(); + secondComponent.setProject(project); + secondComponent.setName("second-library"); + qm.persist(secondComponent); + for (final String id : List.of(KEV_A, KEV_B, KEV_C)) { + qm.addVulnerability( + qm.getVulnerabilityByVulnId(Vulnerability.Source.NVD, id), secondComponent, "local-test"); + } + final Policy secondPolicy = + qm.createPolicy("Second KEV policy", Policy.Operator.ANY, Policy.ViolationState.FAIL); + qm.createPolicyCondition( + secondPolicy, + PolicyCondition.Subject.EXPRESSION, + PolicyCondition.Operator.MATCHES, + EXPRESSION, + PolicyViolation.Type.SECURITY); + // There are two policy conditions for each of the two components. + setKevs(KEV_A); + evaluateAndDeliver(4); + final Set originalViolationUuids = received.stream() + .map(notification -> { + try { + return notification + .getSubject() + .unpack(org.dependencytrack.notification.proto.v1.PolicyViolationSubject.class) + .getPolicyViolation() + .getUuid(); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw new IllegalStateException(e); + } + }) + .collect(java.util.stream.Collectors.toSet()); + assertThat(originalViolationUuids).hasSize(4); + setKevs(KEV_A, KEV_B); + evaluateAndDeliver(4); + assertThat(received).hasSize(8); + for (final Notification update : received.subList(4, 8)) { + final var subject = update.getSubject().unpack(PolicyViolationUpdatedSubject.class); + assertThat(update.getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + assertThat(subject.getPolicyViolation().getUuid()).isIn(originalViolationUuids); + assertThat(subject.getPreviousMessage()).isEqualTo(KEV_A); + assertThat(subject.getCurrentMessage()).isEqualTo(KEV_A + "," + KEV_B); + } + evaluateAndDeliver(0); + assertThat(received).hasSize(8); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void shouldRollBackViolationAndOutboxTogetherWhenEmissionFails(boolean reviewed) throws Exception { + setKevs(KEV_A); + evaluateAndDeliver(1); + final UUID initialUuid = violation().getUuid(); + if (reviewed) { + rule.setNotifyOn( + Set.of(NotificationGroup.POLICY_VIOLATION, NotificationGroup.POLICY_VIOLATION_UPDATED_REVIEWED)); + qm.persist(rule); + review(ViolationAnalysisState.APPROVED, true); + } + setKevs(KEV_A, KEV_B); + useJdbiTransaction(handle -> { + handle.execute(""" + CREATE FUNCTION issue7649_test_reject_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + RAISE EXCEPTION 'issue7649 injected outbox failure'; + END; + $$ + """); + handle.execute(""" + CREATE TRIGGER issue7649_test_reject_outbox + BEFORE INSERT ON "NOTIFICATION_OUTBOX" + FOR EACH ROW EXECUTE FUNCTION issue7649_test_reject_outbox() + """); + }); + try { + assertThatThrownBy(() -> new CelPolicyEngine().evaluateProject(project.getUuid())) + .hasStackTraceContaining("issue7649 injected outbox failure"); + assertThat(violation().getText()).isEqualTo(KEV_A); + assertThat(violation().getUuid()).isEqualTo(initialUuid); + assertThat(getNotificationOutbox()).isEmpty(); + assertThat(received).hasSize(1); + } finally { + useJdbiTransaction(handle -> { + handle.execute("DROP TRIGGER issue7649_test_reject_outbox ON \"NOTIFICATION_OUTBOX\""); + handle.execute("DROP FUNCTION issue7649_test_reject_outbox()"); + }); + } + evaluateAndDeliver(1); + if (reviewed) { + assertReviewedUpdate( + received.getLast(), KEV_A, KEV_A + "," + KEV_B, initialUuid, ViolationAnalysisState.APPROVED, true); + final var analysis = qm.getViolationAnalysis(component, violation()); + assertThat(analysis.getAnalysisState()).isEqualTo(ViolationAnalysisState.APPROVED); + assertThat(analysis.isSuppressed()).isTrue(); + } else { + assertUpdate(received.getLast(), KEV_A, KEV_A + "," + KEV_B, initialUuid); + } + evaluateAndDeliver(0); + assertThat(received).hasSize(2); + } + + private void review(ViolationAnalysisState state, boolean suppressed) { + qm.makeViolationAnalysis(new MakeViolationAnalysisCommand(component, violation()) + .withState(state) + .withSuppress(suppressed) + .withOptions(Set.of(MakeViolationAnalysisCommand.Option.OMIT_NOTIFICATION))); + } + + private List addOrdinaryUpdateReceiver() { + final List notifications = new CopyOnWriteArrayList<>(); + receiver.createContext("/ordinary-updates", exchange -> { + try (exchange) { + notifications.add(Notification.parseFrom(exchange.getRequestBody())); + exchange.sendResponseHeaders(204, -1); + } + }); + final var ordinaryRule = new NotificationRule(); + ordinaryRule.setName("Ordinary updates only"); + ordinaryRule.setEnabled(true); + ordinaryRule.setTriggerType(NotificationTriggerType.EVENT); + ordinaryRule.setScope(NotificationScope.PORTFOLIO); + ordinaryRule.setNotificationLevel(NotificationLevel.INFORMATIONAL); + ordinaryRule.setNotifyOn(Set.of(NotificationGroup.POLICY_VIOLATION_UPDATED)); + ordinaryRule.setPublisher(rule.getPublisher()); + ordinaryRule.setPublisherConfig(""" + {"destinationUrl":"http://127.0.0.1:%d/ordinary-updates","publishProtobuf":true} + """.formatted(receiver.getAddress().getPort())); + qm.persist(ordinaryRule); + return notifications; + } + + private void assertReviewedUpdate( + Notification notification, + String previous, + String current, + UUID uuid, + ViolationAnalysisState state, + boolean suppressed) + throws Exception { + assertThat(notification.getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED_REVIEWED); + final var subject = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class); + assertThat(subject.getPolicyViolation().getUuid()).isEqualTo(uuid.toString()); + assertThat(subject.getPreviousMessage()).isEqualTo(previous); + assertThat(subject.getCurrentMessage()).isEqualTo(current); + assertThat(subject.getPolicyViolation().getMessage()).isEqualTo(current); + assertThat(subject.hasAnalysisState()).isTrue(); + assertThat(subject.getAnalysisState()).isEqualTo(state.name()); + assertThat(subject.hasSuppressed()).isTrue(); + assertThat(subject.getSuppressed()).isEqualTo(suppressed); + } + + private void setKevs(String... ids) { + useJdbiTransaction(handle -> { + final var dao = handle.attach(KevDao.class); + dao.upsertBatch( + "local-test", + java.util.Arrays.stream(ids) + .map(id -> new KevAssertion("NVD", id, null, null, null, null, null)) + .toList()); + dao.deleteStale( + "local-test", + java.util.Arrays.stream(ids) + .map(id -> new VulnerabilityKey(id, Vulnerability.Source.NVD)) + .toList()); + }); + } + + private PolicyViolation violation() { + qm.getPersistenceManager().evictAll(); + assertThat(qm.getAllPolicyViolations(component)).hasSize(1); + return qm.getAllPolicyViolations(component).getFirst(); + } + + private void assertUpdate(Notification notification, String previous, String current, UUID uuid) throws Exception { + assertThat(notification.getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + final var subject = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class); + assertThat(subject.getPreviousMessage()).isEqualTo(previous); + assertThat(subject.getCurrentMessage()).isEqualTo(current); + assertThat(subject.getPolicyViolation().getUuid()).isEqualTo(uuid.toString()); + } + + private List evaluateAndDeliver(int expectedEvents) throws Exception { + return evaluateAndDeliver(expectedEvents, true); + } + + private List evaluateAndDeliver(int expectedEvents, boolean expectedRoute) throws Exception { + return evaluateAndDeliver(expectedEvents, expectedRoute, WorkflowRunStatus.COMPLETED); + } + + private List evaluateAndDeliver( + int expectedEvents, boolean expectedRoute, WorkflowRunStatus expectedStatus) throws Exception { + new CelPolicyEngine().evaluateProject(project.getUuid()); + final List outbox = getNotificationOutbox(); + assertThat(outbox).hasSize(expectedEvents); + if (outbox.isEmpty()) { + return outbox; + } + final var engine = workflowTest.getEngine(); + final var registry = new SimpleMeterRegistry(); + try (var relay = new NotificationOutboxRelay( + engine, + fileStorage, + handle -> new NotificationRouter(handle, registry), + registry, + 10, + 10, + 128 * 1024)) { + relay.start(); + await().atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> assertThat(getNotificationOutbox()).isEmpty()); + for (final Notification notification : outbox) { + final var request = new ListWorkflowRunsRequest() + .withWorkflowInstanceId("publish-notification:" + notification.getId()); + if (!expectedRoute) { + assertThat(engine.listRuns(request).items()).isEmpty(); + continue; + } + await().atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(engine.listRuns(request).items()).hasSize(1)); + final UUID runId = engine.listRuns(request).items().getFirst().id(); + workflowTest.awaitRunStatus(runId, expectedStatus); + } + } finally { + registry.close(); + } + return outbox; + } +} diff --git a/apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyDaoTest.java b/apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyDaoTest.java index 9bf0f59655..443e2e13f1 100644 --- a/apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyDaoTest.java +++ b/apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyDaoTest.java @@ -446,6 +446,73 @@ public void testReconcileViolationsWithMessage() { assertThat(getViolationText(violationId)).isNull(); } + @Test + public void testReconcileViolationChangesReturnsPreviousAndCurrentMessages() { + final var project = new Project(); + project.setName("projectName"); + qm.persist(project); + + final var component = new Component(); + component.setProject(project); + component.setName("componentName"); + qm.persist(component); + + final Policy policy = qm.createPolicy("policy", Policy.Operator.ANY, Policy.ViolationState.FAIL); + final PolicyCondition condition = qm.createPolicyCondition( + policy, + PolicyCondition.Subject.EXPRESSION, + PolicyCondition.Operator.MATCHES, + "true", + PolicyViolation.Type.OPERATIONAL); + + final var violation = new PolicyViolation(); + violation.setType(PolicyViolation.Type.OPERATIONAL); + violation.setPolicyCondition(condition); + violation.setTimestamp(new Date()); + violation.setText("CVE-2021-44228"); + final var reported = Map.of(component.getId(), List.of(violation)); + + final var first = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(project.getId(), reported)); + assertThat(first.createdIds()).hasSize(1); + assertThat(first.updatedById()).isEmpty(); + final long violationId = first.createdIds().iterator().next(); + + final var same = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(project.getId(), reported)); + assertThat(same.createdIds()).isEmpty(); + assertThat(same.updatedById()).isEmpty(); + + violation.setText("CVE-2021-44228,CVE-2021-45046"); + final var updated = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(project.getId(), reported)); + assertThat(updated.createdIds()).isEmpty(); + assertThat(updated.updatedById()).containsOnlyKeys(violationId); + final var change = updated.updatedById().get(violationId); + assertThat(change.uuid()).isNotNull(); + assertThat(change.previousMessage()).isEqualTo("CVE-2021-44228"); + assertThat(change.currentMessage()).isEqualTo("CVE-2021-44228,CVE-2021-45046"); + assertThat(getViolationText(violationId)).isEqualTo(change.currentMessage()); + + violation.setText(null); + final var cleared = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(project.getId(), reported)); + assertThat(cleared.updatedById()).containsOnlyKeys(violationId); + assertThat(cleared.updatedById().get(violationId).previousMessage()).isEqualTo("CVE-2021-44228,CVE-2021-45046"); + assertThat(cleared.updatedById().get(violationId).currentMessage()).isNull(); + + final var stillNull = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(project.getId(), reported)); + assertThat(stillNull.updatedById()).isEmpty(); + + violation.setText("CVE-2021-45046"); + final var restored = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(project.getId(), reported)); + assertThat(restored.updatedById()).containsOnlyKeys(violationId); + assertThat(restored.updatedById().get(violationId).previousMessage()).isNull(); + assertThat(restored.updatedById().get(violationId).currentMessage()).isEqualTo("CVE-2021-45046"); + } + private static String getViolationText(long violationId) { return withJdbiHandle(handle -> handle.createQuery(""" SELECT "TEXT" FROM "POLICYVIOLATION" WHERE "ID" = :id diff --git a/apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyViolationChangesTest.java b/apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyViolationChangesTest.java new file mode 100644 index 0000000000..08680b9a78 --- /dev/null +++ b/apiserver/src/test/java/org/dependencytrack/policy/cel/persistence/CelPolicyViolationChangesTest.java @@ -0,0 +1,399 @@ +/* + * This file is part of Dependency-Track. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * Copyright (c) OWASP Foundation. All Rights Reserved. + */ +package org.dependencytrack.policy.cel.persistence; + +import org.dependencytrack.PersistenceCapableTest; +import org.dependencytrack.model.Component; +import org.dependencytrack.model.Policy; +import org.dependencytrack.model.PolicyCondition; +import org.dependencytrack.model.PolicyViolation; +import org.dependencytrack.model.Project; +import org.dependencytrack.notification.JdbiNotificationEmitter; +import org.dependencytrack.notification.NotificationScope; +import org.dependencytrack.policy.cel.persistence.CelPolicyDao.ViolationChanges; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.transaction.TransactionIsolationLevel; +import org.junit.jupiter.api.Test; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.awaitility.Awaitility.await; +import static org.dependencytrack.notification.NotificationTestUtil.createCatchAllNotificationRule; +import static org.dependencytrack.notification.NotificationTestUtil.getNotificationOutbox; +import static org.dependencytrack.notification.api.TestNotificationFactory.createPolicyViolationUpdatedTestNotification; +import static org.dependencytrack.persistence.jdbi.JdbiFactory.inJdbiTransaction; +import static org.dependencytrack.persistence.jdbi.JdbiFactory.openJdbiHandle; +import static org.dependencytrack.persistence.jdbi.JdbiFactory.withJdbiHandle; + +class CelPolicyViolationChangesTest extends PersistenceCapableTest { + + private record Fixture(long projectId, long componentId, PolicyCondition condition) {} + + private record Contention(ViolationChanges first, ViolationChanges second) {} + + @Test + void shouldDeleteAndRecreateWithNewIdentity() { + final var fixture = fixture("one"); + final var first = reconcile(fixture, "A"); + final long originalId = first.createdIds().iterator().next(); + final var removed = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(fixture.projectId(), Map.of())); + assertThat(removed.createdIds()).isEmpty(); + assertThat(removed.updatedById()).isEmpty(); + assertThat(countViolations(fixture.projectId())).isZero(); + final var restored = reconcile(fixture, "B"); + assertThat(restored.createdIds()).hasSize(1).doesNotContain(originalId); + assertThat(restored.updatedById()).isEmpty(); + } + + @Test + void shouldReconcileMultipleComponentsAndPoliciesWithoutTouchingAnotherProject() { + final var first = fixture("first"); + final var other = fixture("other"); + final var secondComponent = new Component(); + secondComponent.setProject(qm.getObjectById(Project.class, first.projectId())); + secondComponent.setName("second"); + qm.persist(secondComponent); + final var secondPolicy = qm.createPolicy("second", Policy.Operator.ANY, Policy.ViolationState.FAIL); + final var secondCondition = condition(secondPolicy); + final var samePolicyCondition = condition(first.condition().getPolicy()); + final var reports = Map.of( + first.componentId(), + List.of( + violation(first.condition(), "A"), + violation(secondCondition, "A"), + violation(samePolicyCondition, "A")), + secondComponent.getId(), List.of(violation(first.condition(), "A"))); + assertThat(reconcile(other, "untouched").createdIds()).hasSize(1); + assertThat(inJdbiTransaction(handle -> + new CelPolicyDao(handle).reconcileViolationChanges(first.projectId(), reports)) + .createdIds()) + .hasSize(4); + reports.values().forEach(violations -> violations.forEach(violation -> violation.setText("A,B"))); + final var changed = inJdbiTransaction( + handle -> new CelPolicyDao(handle).reconcileViolationChanges(first.projectId(), reports)); + assertThat(changed.createdIds()).isEmpty(); + assertThat(changed.updatedById()).hasSize(4); + assertThat(changed.updatedById().values()).allSatisfy(change -> { + assertThat(change.previousMessage()).isEqualTo("A"); + assertThat(change.currentMessage()).isEqualTo("A,B"); + assertThat(change.uuid()).isNotNull(); + assertThat(change.changedAt()).isNotNull(); + }); + assertThat(reconcile(other, "untouched").updatedById()).isEmpty(); + assertThat(countViolations(other.projectId())).isEqualTo(1); + } + + @Test + void shouldSerializeConcurrentIdenticalInitialReports() throws Exception { + final var fixture = fixture("initial"); + final var changes = contend(fixture, reports(fixture, "A"), reports(fixture, "A")); + assertThat(changes.first().createdIds()).hasSize(1); + assertThat(changes.second().createdIds()).isEmpty(); + assertThat(changes.second().updatedById()).isEmpty(); + assertThat(countViolations(fixture.projectId())).isEqualTo(1); + } + + @Test + void shouldSerializeConcurrentIdenticalUpdates() throws Exception { + final var fixture = fixture("same-update"); + final long id = reconcile(fixture, "A").createdIds().iterator().next(); + final var changes = contend(fixture, reports(fixture, "A,B"), reports(fixture, "A,B")); + assertThat(changes.first().updatedById()).containsOnlyKeys(id); + assertThat(changes.second().createdIds()).isEmpty(); + assertThat(changes.second().updatedById()).isEmpty(); + assertThat(message(id)).isEqualTo("A,B"); + } + + @Test + void shouldReadCommittedPredecessorAfterConcurrentUpdate() throws Exception { + final var fixture = fixture("different-update"); + final long id = reconcile(fixture, "A").createdIds().iterator().next(); + final var changes = contend(fixture, reports(fixture, "A,B"), reports(fixture, "A,B,C")); + assertThat(changes.first().updatedById().get(id).previousMessage()).isEqualTo("A"); + final var second = changes.second().updatedById().get(id); + assertThat(second.previousMessage()).isEqualTo("A,B"); + assertThat(second.currentMessage()).isEqualTo("A,B,C"); + assertThat(second.uuid()) + .isEqualTo(changes.first().updatedById().get(id).uuid()); + assertThat(message(id)).isEqualTo("A,B,C"); + } + + @Test + void shouldReadCommittedPredecessorAfterConcurrentInsert() throws Exception { + final var fixture = fixture("concurrent-insert"); + final var changes = contend(fixture, reports(fixture, "A,B"), reports(fixture, "A,B,C")); + final long id = changes.first().createdIds().iterator().next(); + assertThat(changes.second().createdIds()).isEmpty(); + assertThat(changes.second().updatedById()).containsOnlyKeys(id); + assertThat(changes.second().updatedById().get(id).previousMessage()).isEqualTo("A,B"); + assertThat(changes.second().updatedById().get(id).currentMessage()).isEqualTo("A,B,C"); + } + + @Test + void shouldSerializeDeletionAndConcurrentReappearance() throws Exception { + final var fixture = fixture("delete-update"); + final long originalId = reconcile(fixture, "A").createdIds().iterator().next(); + final var changes = contend(fixture, Map.of(), reports(fixture, "B")); + assertThat(changes.second().createdIds()).hasSize(1).doesNotContain(originalId); + assertThat(changes.second().updatedById()).isEmpty(); + assertThat(countViolations(fixture.projectId())).isEqualTo(1); + } + + @Test + void shouldAllowDifferentProjectsToReconcileConcurrently() throws Exception { + final var first = fixture("parallel-one"); + final var second = fixture("parallel-two"); + try (final var executor = Executors.newSingleThreadExecutor(); + final var handle = openJdbiHandle()) { + handle.begin(); + try { + new CelPolicyDao(handle).reconcileViolationChanges(first.projectId(), reports(first, "A")); + final var future = executor.submit(() -> reconcile(second, "B")); + assertThat(future.get(5, TimeUnit.SECONDS).createdIds()).hasSize(1); + handle.commit(); + } finally { + if (handle.isInTransaction()) { + handle.rollback(); + } + } + } + assertThat(countViolations(first.projectId())).isEqualTo(1); + assertThat(countViolations(second.projectId())).isEqualTo(1); + } + + @Test + void shouldDeleteWhenComponentHasNoReportedConditions() { + final var fixture = fixture("empty-conditions"); + reconcile(fixture, "A"); + final var changes = inJdbiTransaction(handle -> new CelPolicyDao(handle) + .reconcileViolationChanges(fixture.projectId(), Map.of(fixture.componentId(), List.of()))); + assertThat(changes.createdIds()).isEmpty(); + assertThat(changes.updatedById()).isEmpty(); + assertThat(countViolations(fixture.projectId())).isZero(); + } + + @Test + void shouldRollBackMessageAndDurableNotificationTogether() { + final var fixture = fixture("rollback"); + final long id = reconcile(fixture, "A").createdIds().iterator().next(); + createCatchAllNotificationRule(qm, NotificationScope.PORTFOLIO); + assertThatThrownBy(() -> inJdbiTransaction(handle -> { + final var changes = new CelPolicyDao(handle) + .reconcileViolationChanges(fixture.projectId(), reports(fixture, "A,B")); + assertThat(changes.updatedById()).containsOnlyKeys(id); + new JdbiNotificationEmitter(handle).emit(createPolicyViolationUpdatedTestNotification()); + assertThat(handle.createQuery("SELECT COUNT(*) FROM \"NOTIFICATION_OUTBOX\"") + .mapTo(Integer.class) + .one()) + .isEqualTo(1); + throw new IllegalStateException("controlled rollback"); + })) + .isInstanceOf(IllegalStateException.class) + .hasMessage("controlled rollback"); + assertThat(message(id)).isEqualTo("A"); + assertThat(getNotificationOutbox()).isEmpty(); + assertThat(reconcile(fixture, "A,B").updatedById().get(id).previousMessage()) + .isEqualTo("A"); + } + + @Test + void shouldRollBackDuplicateIdentityConflict() { + final var fixture = fixture("conflict"); + final long id = reconcile(fixture, "A").createdIds().iterator().next(); + assertThatThrownBy(() -> inJdbiTransaction(handle -> new CelPolicyDao(handle) + .reconcileViolationChanges( + fixture.projectId(), + Map.of( + fixture.componentId(), + List.of( + violation(fixture.condition(), "B"), + violation(fixture.condition(), "C")))))) + .isInstanceOf(org.jdbi.v3.core.statement.UnableToExecuteStatementException.class); + assertThat(message(id)).isEqualTo("A"); + assertThat(countViolations(fixture.projectId())).isEqualTo(1); + } + + @Test + void shouldRejectMissingTransactionAndUnsupportedIsolation() { + final var fixture = fixture("isolation"); + try (final var handle = openJdbiHandle()) { + assertThatThrownBy(() -> new CelPolicyDao(handle) + .reconcileViolationChanges(fixture.projectId(), reports(fixture, "A"))) + .isInstanceOf(IllegalStateException.class); + handle.setTransactionIsolation(TransactionIsolationLevel.REPEATABLE_READ); + handle.begin(); + try { + assertThatThrownBy(() -> new CelPolicyDao(handle) + .reconcileViolationChanges(fixture.projectId(), reports(fixture, "A"))) + .isInstanceOf(IllegalStateException.class); + } finally { + handle.rollback(); + } + } + assertThat(countViolations(fixture.projectId())).isZero(); + } + + @Test + void shouldMeasureActualBulkDaoAtOneAndTenThousandComponents() { + for (final int size : List.of(1_000, 10_000)) { + final var fixture = fixture("benchmark-" + size); + final List componentIds = inJdbiTransaction(handle -> handle.createQuery(""" + INSERT INTO "COMPONENT" ("PROJECT_ID", "NAME", "UUID") + SELECT :projectId, 'benchmark-' || i, gen_random_uuid() + FROM generate_series(1, :size) i RETURNING "ID" + """) + .bind("projectId", fixture.projectId()) + .bind("size", size) + .mapTo(Long.class) + .list()); + final var input = new HashMap>(); + componentIds.forEach(id -> input.put(id, List.of(violation(fixture.condition(), "A")))); + final var inserted = measured(fixture.projectId(), size, "insert", input); + assertThat(inserted.createdIds()).hasSize(size); + assertThat(inserted.updatedById()).isEmpty(); + for (int iteration = 1; iteration <= 3; iteration++) { + final var unchanged = measured(fixture.projectId(), size, "unchanged-" + iteration, input); + assertThat(unchanged.createdIds()).isEmpty(); + assertThat(unchanged.updatedById()).isEmpty(); + } + input.values().forEach(violations -> violations.getFirst().setText("A,B")); + final var changed = measured(fixture.projectId(), size, "changed", input); + assertThat(changed.createdIds()).isEmpty(); + assertThat(changed.updatedById()).hasSize(size); + assertThat(changed.updatedById().values()).allSatisfy(change -> { + assertThat(change.previousMessage()).isEqualTo("A"); + assertThat(change.currentMessage()).isEqualTo("A,B"); + }); + assertThat(countViolations(fixture.projectId())).isEqualTo(size); + } + } + + private ViolationChanges measured(long projectId, int size, String phase, Map> input) { + final long start = System.nanoTime(); + final var changes = + inJdbiTransaction(handle -> new CelPolicyDao(handle).reconcileViolationChanges(projectId, input)); + System.out.printf( + "DAO_BENCHMARK rows=%d phase=%s elapsed_ms=%.3f created=%d updated=%d%n", + size, + phase, + (System.nanoTime() - start) / 1_000_000.0, + changes.createdIds().size(), + changes.updatedById().size()); + return changes; + } + + private Contention contend( + Fixture fixture, Map> firstInput, Map> secondInput) + throws Exception { + try (final var executor = Executors.newSingleThreadExecutor(); + final Handle firstHandle = openJdbiHandle()) { + firstHandle.begin(); + try { + final var first = + new CelPolicyDao(firstHandle).reconcileViolationChanges(fixture.projectId(), firstInput); + final var secondPid = new CompletableFuture(); + final var secondFuture = executor.submit(() -> inJdbiTransaction(handle -> { + handle.execute("SET LOCAL lock_timeout = '10s'"); + secondPid.complete(handle.createQuery("SELECT pg_backend_pid()") + .mapTo(Integer.class) + .one()); + return new CelPolicyDao(handle).reconcileViolationChanges(fixture.projectId(), secondInput); + })); + final int pid = secondPid.get(5, TimeUnit.SECONDS); + // Observe an actual PostgreSQL lock wait; no timing-only sleep or mock synchronization. + await("second reconciliation waits on the first project's row lock") + .atMost(5, TimeUnit.SECONDS) + .until(() -> firstHandle + .createQuery("SELECT cardinality(pg_blocking_pids(:pid)) > 0") + .bind("pid", pid) + .mapTo(Boolean.class) + .one()); + firstHandle.commit(); + return new Contention(first, secondFuture.get(10, TimeUnit.SECONDS)); + } finally { + if (firstHandle.isInTransaction()) { + firstHandle.rollback(); + } + } + } + } + + private Fixture fixture(String name) { + final var project = new Project(); + project.setName(name); + qm.persist(project); + final var component = new Component(); + component.setName(name); + component.setProject(project); + qm.persist(component); + final var policy = qm.createPolicy(name, Policy.Operator.ANY, Policy.ViolationState.FAIL); + return new Fixture(project.getId(), component.getId(), condition(policy)); + } + + private PolicyCondition condition(Policy policy) { + return qm.createPolicyCondition( + policy, + PolicyCondition.Subject.EXPRESSION, + PolicyCondition.Operator.MATCHES, + "true", + PolicyViolation.Type.SECURITY); + } + + private static PolicyViolation violation(PolicyCondition condition, String text) { + final var violation = new PolicyViolation(); + violation.setPolicyCondition(condition); + violation.setType(PolicyViolation.Type.SECURITY); + violation.setTimestamp(new Date()); + violation.setText(text); + return violation; + } + + private static Map> reports(Fixture fixture, String message) { + return Map.of(fixture.componentId(), List.of(violation(fixture.condition(), message))); + } + + private static ViolationChanges reconcile(Fixture fixture, String message) { + return inJdbiTransaction(handle -> + new CelPolicyDao(handle).reconcileViolationChanges(fixture.projectId(), reports(fixture, message))); + } + + private static String message(long id) { + return withJdbiHandle(handle -> handle.createQuery("SELECT \"TEXT\" FROM \"POLICYVIOLATION\" WHERE \"ID\"=:id") + .bind("id", id) + .mapTo(String.class) + .one()); + } + + private static long countViolations(long projectId) { + return withJdbiHandle( + handle -> handle.createQuery("SELECT COUNT(*) FROM \"POLICYVIOLATION\" WHERE \"PROJECT_ID\"=:projectId") + .bind("projectId", projectId) + .mapTo(Long.class) + .one()); + } +} diff --git a/apiserver/src/test/java/org/dependencytrack/resources/v1/NotificationRuleResourceTest.java b/apiserver/src/test/java/org/dependencytrack/resources/v1/NotificationRuleResourceTest.java index 807520f106..163129f6c4 100644 --- a/apiserver/src/test/java/org/dependencytrack/resources/v1/NotificationRuleResourceTest.java +++ b/apiserver/src/test/java/org/dependencytrack/resources/v1/NotificationRuleResourceTest.java @@ -184,6 +184,40 @@ void createNotificationRuleTest() { """); } + @Test + void shouldCreateIndependentlySubscribedPolicyViolationUpdatedRule() { + initializeWithPermissions(Permissions.SYSTEM_CONFIGURATION_CREATE); + final Response response = jersey.target(V1_NOTIFICATION_RULE) + .request() + .header(X_API_KEY, apiKey) + .put(Entity.json(/* language=JSON */ """ + { + "name": "Policy message changes only", + "notificationLevel": "INFORMATIONAL", + "scope": "PORTFOLIO", + "publisher": { + "uuid": "%s" + }, + "notifyOn": ["POLICY_VIOLATION_UPDATED"], + "filterExpression": "subject.current_message.contains('CVE-2021-45046')" + } + """.formatted(publisher.getUuid()))); + assertThat(response.getStatus()).isEqualTo(201); + final JsonObject responseJson = parseJsonObject(response); + assertThat(responseJson.getString("triggerType")).isEqualTo("EVENT"); + assertThat(responseJson.getJsonArray("notifyOn")).hasSize(1); + assertThat(responseJson.getJsonArray("notifyOn").getString(0)).isEqualTo("POLICY_VIOLATION_UPDATED"); + assertThat(responseJson.getString("filterExpression")) + .isEqualTo("subject.current_message.contains('CVE-2021-45046')"); + + qm.getPersistenceManager().evictAll(); + final NotificationRule rule = qm.getObjectByUuid(NotificationRule.class, responseJson.getString("uuid")); + assertThat(rule).isNotNull(); + assertThat(rule.getTriggerType()).isEqualTo(NotificationTriggerType.EVENT); + assertThat(rule.getNotifyOn()).containsOnly(NotificationGroup.POLICY_VIOLATION_UPDATED); + assertThat(rule.getFilterExpression()).isEqualTo("subject.current_message.contains('CVE-2021-45046')"); + } + @Test void createNotificationRuleInvalidPublisherTest() { initializeWithPermissions(Permissions.SYSTEM_CONFIGURATION_CREATE); diff --git a/docs/POLICY_VIOLATION_UPDATES.md b/docs/POLICY_VIOLATION_UPDATES.md new file mode 100644 index 0000000000..217ecb4cdc --- /dev/null +++ b/docs/POLICY_VIOLATION_UPDATES.md @@ -0,0 +1,64 @@ +# Policy violation update notifications + +`POLICY_VIOLATION` reports a newly created violation. Subscribe separately to +`POLICY_VIOLATION_UPDATED` to receive changes to the message of an existing violation. +The rule must be enabled and use the event trigger. Its existing project, tag, level, and +CEL filters still apply. Approved or suppressed violations stay excluded from this ordinary +update group. To receive message changes while a violation is approved or suppressed, explicitly +subscribe to `POLICY_VIOLATION_UPDATED_REVIEWED` instead, or subscribe to both update groups +to cover both classes. Neither group clears review decisions or extends the scheduled summary +groups. Existing rules are not subscribed to the reviewed group automatically. + +A reviewed violation has analysis state `APPROVED` or suppression `true`. A `REJECTED`, +unsuppressed violation still belongs to the ordinary update group. Each message transition +chooses exactly one group, so a rule subscribing to both gets one event. These are message +change events, including removals and wording changes, not a claim that risk always increased. +Changing a decision alone, adding a subscription or clearing suppression does not replay an +older message change. A later message change is evaluated with the review context then observed. + +For a component policy with subject `EXPRESSION`, a basic KEV message is: + +```cel +vulns.filter(v, v.is_kev).map(v, v.id).join(",") +``` + +A non-empty string means a match and is saved as the message. No active KEVs produces +an empty string, so the violation disappears. Vulnerabilities enter this expression in stable +database identity order. A Boolean expression such as `vulns.exists(v, v.is_kev)` can still be +used, but has no message to change when a second KEV appears. Do not include `now` or +random data in messages used as change signals. Messages retain the existing 1024-character +limit. Equal stored messages cannot distinguish different underlying sets. + +The new subject type is +`org.dependencytrack.notification.v1.PolicyViolationUpdatedSubject`. Its fields are: + +- `project`, `component`, and `policy_violation`, including the original violation UUID and + policy condition. `policy_violation.message` holds the current message when non-null. +- Optional `previous_message` and `current_message`. An absent field means null, while a + present empty string is empty text. Protobuf JSON uses `previousMessage` and `currentMessage`. +- `changed_at`, the time of the reconciliation statement on the database server. +- Optional `analysis_state` and `suppressed`, captured together from one SQL snapshot during + subject assembly for reviewed-group events. Present `false` means explicitly unsuppressed. + An absent field means no captured value; ordinary-group events retain their original shape + and omit review metadata. Decisions may change later without altering this historical event. + +An example notification filter is `subject.current_message.contains('CVE-2021-45046')`. +An arbitrary text change is not proof of a new KEV. Added and removed identifiers are not +parsed from policy text. Set a filter appropriate to the policy and destination. Existing +JSON webhook templates serialize the structured subject. Default human-readable templates +show previous and current text. Custom templates should add an explicit update-group branch. + +A repeated evaluation with unchanged text creates no update event. A removed violation +that reappears gets a new UUID and the ordinary creation event. Message changes and their +outbox event commit atomically. HTTP delivery happens later through the normal notification +workflow. Transient failures can retry the same notification ID. Receivers should deduplicate +that ID; this is not an exactly-once HTTP guarantee. Check failed workflows after permanent +failures according to the existing operational procedures. + +This implementation needs no schema migration. Existing group numbers and configured +subscriptions stay unchanged. Older consumers should continue processing the original group; +consumers newly subscribing to updates need support for the new group and subject. The reviewed +update group uses Protobuf value 26 and the same subject type with additive optional fields. +A rule can use `subject.analysis_state == 'APPROVED'` or `subject.suppressed` to narrow the +reviewed events it receives. Normal project, tag and group subscriptions still apply; a CEL +filter cannot turn an ordinary-group subscription into a reviewed-group subscription. diff --git a/docs/adr/044-policy-violation-update-notifications.md b/docs/adr/044-policy-violation-update-notifications.md new file mode 100644 index 0000000000..d2343dbf23 --- /dev/null +++ b/docs/adr/044-policy-violation-update-notifications.md @@ -0,0 +1,79 @@ +| Status | Date | Author(s) | +|:---------|:-----------|:----------| +| Proposed | 2026-11-07 | [WenFeng Gao (@007xf)](https://github.com/007xf) | + +## Context + +A violation identifies a component and policy condition in a project. It can stay open while +another known exploited vulnerability starts matching the same condition. [ADR 043] lets a +condition return the identifiers in its message. Reconciliation updates that message, but only +new violations produce notifications. [Issue 7649] describes the missing change alert. + +The old notification group has creation semantics. Reusing it for updates would change existing +automations. Reading old messages before an upsert also needs care. PostgreSQL can resolve an +upsert conflict with a row that was not visible in that statement's snapshot. + +## Decision + +Add an event group named `POLICY_VIOLATION_UPDATED`. Existing rules do not subscribe to it +automatically. Keep `POLICY_VIOLATION` for creation and keep summary notifications unchanged. +A null-safe change to the stored message produces an update event. The event has a distinct +subject with the project, component, stable violation UUID, policy and condition, optional previous +and current messages, and the database statement time. Absent message fields mean null. + +Use a short READ COMMITTED transaction for reconciliation and the notification outbox write. +Acquire the project row lock in a separate statement before reading old messages. This serializes +reconciliation even when the project has no violations yet. The next statement sees the preceding +committed transition. Preserve the bulk upsert and deletion, and do not issue per-violation reads. +Require an active READ COMMITTED transaction so callers cannot silently release the lock early +or reuse a stale transaction snapshot. Use a non-key-changing row lock so foreign-key checks +can continue. Normal project analysis workflows already serialize their full evaluation by project. + +Retain existing approval and suppression filters for `POLICY_VIOLATION_UPDATED`. Add a +separate explicit opt-in group, `POLICY_VIOLATION_UPDATED_REVIEWED`, for changed messages +when the analysis state is APPROVED or suppression is true. Existing rules gain no subscription +automatically. This group reports changed content despite a retained review decision. It does +not approve, unapprove, suppress or unsuppress the violation. + +Fetch update subjects and their analysis state and suppression in one bulk SQL statement. +Classify each transition once from that statement's snapshot, sending either the ordinary or +reviewed update group. Do not query the two classes separately, since a concurrent review +could otherwise move a record between those queries and cause duplicate or missing events. +Include optional analysis state and suppression in reviewed-update subjects. A present false +is an explicit unsuppressed state. Ordinary updates retain their original payload shape and +omit these fields. Absence means no captured value. The metadata is +an observation during subject assembly, not a claim that review cannot change before delivery. +Review-only changes, new subscriptions and clearing a decision do not replay prior transitions. + +Order vulnerability inputs by their stable database identity. A message that joins the same input +set then stays stable across query plans. Do not parse arbitrary policy messages as KEV lists or +infer whether a change increases risk. A removal, replacement, or wording change also counts as +a message change. Notification filter expressions can narrow the events sent to a destination. + +## Consequences + +A second KEV can produce an opt-in update alert while the violation keeps its identity and review +history. Existing subscribers keep creation semantics. The outbox and violation change commit +or roll back together. Delivery uses the existing durable notification workflow and retry policy. +A retry may deliver the same event more than once. Receivers can deduplicate by notification ID. +Permanent delivery failures still follow the existing failed-workflow behavior. + +Boolean conditions have no message and cannot describe changes to a matching set. Users must +return a stable message containing the relevant identities. The existing 1024-character message +limit still applies. Changes that produce identical stored text, including changes past that limit, +cannot be distinguished. Conditions that include time or other unstable values can produce an +alert on each analysis. No semantic risk classifier or unbounded history is added. + +The project lock adds one round trip per reconciliation. Different projects can reconcile in +parallel. Same-project writers wait for the short reconciliation and outbox transaction. Policy +compilation, evaluation and HTTP delivery stay outside it. Direct callers that bypass the project +workflow must not race stale evaluations. The reconciliation lock serializes writes, not input reads. + +Protobuf gains a new enum value and message without changing existing numbers or fields. +Rules store group names in a text array, so no schema migration or automatic subscription update +is required. Consumers opting into reviewed updates must understand group 26 and the optional review context. +New-event consumers must understand the new subject. Existing event payloads keep +their schema. Custom templates may need an explicit branch for the new group. + +[ADR 043]: ./043-policy-condition-message-expression.md +[Issue 7649]: https://github.com/DependencyTrack/dependency-track/issues/7649 diff --git a/e2e/src/test/java/org/dependencytrack/e2e/PolicyViolationUpdatedReviewedE2ET.java b/e2e/src/test/java/org/dependencytrack/e2e/PolicyViolationUpdatedReviewedE2ET.java new file mode 100644 index 0000000000..27a9207e20 --- /dev/null +++ b/e2e/src/test/java/org/dependencytrack/e2e/PolicyViolationUpdatedReviewedE2ET.java @@ -0,0 +1,392 @@ +/* + * This file is part of Dependency-Track. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * Copyright (c) OWASP Foundation. All Rights Reserved. + */ +package org.dependencytrack.e2e; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.github.tomakehurst.wiremock.junit5.WireMockExtension; +import feign.Feign; +import feign.jackson.JacksonDecoder; +import feign.jackson.JacksonEncoder; +import feign.jaxrs3.JAXRS3Contract; +import org.dependencytrack.e2e.api.model.CreateNotificationRuleRequest; +import org.dependencytrack.e2e.api.model.EventTokenResponse; +import org.dependencytrack.e2e.api.model.NotificationPublisher; +import org.dependencytrack.e2e.api.model.NotificationRule; +import org.dependencytrack.e2e.api.model.UpdateNotificationRuleRequest; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.testcontainers.Testcontainers; +import org.testcontainers.containers.GenericContainer; + +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; +import static com.github.tomakehurst.wiremock.client.WireMock.post; +import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; +import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +/** Verifies the public analysis API through a real server and local webhook delivery. */ +class PolicyViolationUpdatedReviewedE2ET extends AbstractE2ET { + + private static final String KEV_A = "CVE-2021-44228"; + private static final String KEV_B = "CVE-2021-45046"; + private static final String KEV_C = "CVE-2099-00001"; + private static final String UPDATED = "GROUP_POLICY_VIOLATION_UPDATED"; + private static final String REVIEWED = "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED"; + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @RegisterExtension + static WireMockExtension wireMock = WireMockExtension.newInstance() + .options(wireMockConfig().bindAddress("127.0.0.1").dynamicPort()) + .build(); + + @Override + @BeforeEach + void beforeEach() throws Exception { + Testcontainers.exposeHostPorts(wireMock.getRuntimeInfo().getHttpPort()); + super.beforeEach(); + } + + @Override + protected void customizeApiServerContainer(GenericContainer container) { + // Only the host-side fixture can receive HTTP requests from this isolated server. + container.withEnv("DT_OUTBOUND_ALLOWED_DESTINATIONS", "host.testcontainers.internal"); + } + + @ParameterizedTest + @CsvSource({"APPROVED,false", "REJECTED,true", "APPROVED,true"}) + void shouldOptInToReviewedChangesThroughPublicAnalysisApi(String state, boolean suppressed) throws Exception { + final String adminToken = apiV1Client.login("admin", "admin123"); + final var api = Feign.builder() + .contract(new JAXRS3Contract()) + .encoder(new JacksonEncoder()) + .decoder(new JacksonDecoder()) + .requestInterceptor(request -> request.header("Authorization", "Bearer " + adminToken)) + .target(PolicyApi.class, "http://localhost:" + apiServerContainer.getFirstMappedPort()); + + final UUID project = uuid(api.createProject(Map.of("name", "isolated-reviewed-kev", "version", "1"))); + final UUID component = uuid(api.createComponent( + project, Map.of("name", "isolated-library", "version", "1", "classifier", "LIBRARY"))); + final UUID policy = + uuid(api.createPolicy(Map.of("name", "KEV message", "operator", "ANY", "violationState", "FAIL"))); + api.createCondition( + policy, + Map.of( + "subject", + "EXPRESSION", + "operator", + "MATCHES", + "value", + "vulns.filter(v, v.is_kev).map(v, v.id).join(\",\")", + "violationType", + "SECURITY")); + seedFindings(component); + + final NotificationPublisher publisher = apiV1Client.getAllNotificationPublishers().stream() + .filter(candidate -> candidate.extensionName().equals("webhook")) + .findFirst() + .orElseThrow(); + createRule(publisher, "ordinary", Set.of("POLICY_VIOLATION", "POLICY_VIOLATION_UPDATED"), "/ordinary"); + wireMock.stubFor( + post(urlPathEqualTo("/ordinary")).willReturn(aResponse().withStatus(204))); + wireMock.stubFor( + post(urlPathEqualTo("/reviewed")).willReturn(aResponse().withStatus(204))); + + setKevs(KEV_A); + analyzeAndDrain(api, project); + assertCounts(1, 0); + final UUID violation = UUID.fromString(sql("SELECT \"UUID\" FROM \"POLICYVIOLATION\"")); + assertThat(notifications("/ordinary").getFirst().path("group").asText()).isEqualTo("GROUP_POLICY_VIOLATION"); + analyzeAndDrain(api, project); + assertCounts(1, 0); + + // The default update subscription must retain its review/suppression exclusion. + decide(api, component, violation, state, suppressed); + setKevs(KEV_A, KEV_B); + analyzeAndDrain(api, project); + assertCounts(1, 0); + assertDecision(state, suppressed); + assertThat(sql("SELECT \"TEXT\" FROM \"POLICYVIOLATION\"")).isEqualTo(KEV_A + "," + KEV_B); + + // Explicit REST subscription does not replay the already-recorded transition. + final NotificationRule reviewedRule = + createRule(publisher, "reviewed", Set.of("POLICY_VIOLATION_UPDATED_REVIEWED"), "/reviewed"); + analyzeAndDrain(api, project); + assertCounts(1, 0); + + setKevs(KEV_A, KEV_B, KEV_C); + analyzeAndDrain(api, project); + assertCounts(1, 1); + assertUpdated( + "/reviewed", + REVIEWED, + KEV_A + "," + KEV_B, + KEV_A + "," + KEV_B + "," + KEV_C, + violation, + state, + suppressed); + assertDecision(state, suppressed); + analyzeAndDrain(api, project); + assertCounts(1, 1); + + // Subscribing to both event groups still classifies the same transition once. + updateRule(reviewedRule, Set.of("POLICY_VIOLATION_UPDATED", "POLICY_VIOLATION_UPDATED_REVIEWED"), "/reviewed"); + setKevs(KEV_B, KEV_C); + analyzeAndDrain(api, project); + assertCounts(1, 2); + assertUpdated( + "/reviewed", + REVIEWED, + KEV_A + "," + KEV_B + "," + KEV_C, + KEV_B + "," + KEV_C, + violation, + state, + suppressed); + assertDecision(state, suppressed); + + // Changing only a review decision is not a message-change event. + decide(api, component, violation, "APPROVED", true); + analyzeAndDrain(api, project); + assertCounts(1, 2); + decide(api, component, violation, "NOT_SET", false); + analyzeAndDrain(api, project); + assertCounts(1, 2); + assertDecision("NOT_SET", false); + + setKevs(KEV_A, KEV_B, KEV_C); + analyzeAndDrain(api, project); + assertCounts(2, 3); + final JsonNode ordinary = assertUpdated( + "/ordinary", + UPDATED, + KEV_B + "," + KEV_C, + KEV_A + "," + KEV_B + "," + KEV_C, + violation, + "NOT_SET", + false); + final JsonNode optedIn = assertUpdated( + "/reviewed", + UPDATED, + KEV_B + "," + KEV_C, + KEV_A + "," + KEV_B + "," + KEV_C, + violation, + "NOT_SET", + false); + assertThat(ordinary.path("id").asText()).isEqualTo(optedIn.path("id").asText()); + assertThat(sql("SELECT \"UUID\" FROM \"POLICYVIOLATION\"")).isEqualTo(violation.toString()); + analyzeAndDrain(api, project); + assertCounts(2, 3); + } + + private NotificationRule createRule(NotificationPublisher publisher, String name, Set groups, String path) { + final var rule = apiV1Client.createNotificationRule(new CreateNotificationRuleRequest( + name, "PORTFOLIO", "INFORMATIONAL", new CreateNotificationRuleRequest.Publisher(publisher.uuid()))); + updateRule(rule, groups, path); + return rule; + } + + private void updateRule(NotificationRule rule, Set groups, String path) { + apiV1Client.updateNotificationRule(new UpdateNotificationRuleRequest( + rule.uuid(), + rule.name(), + true, + "PORTFOLIO", + "INFORMATIONAL", + groups, + "{\"destinationUrl\":\"http://host.testcontainers.internal:%d%s\"}" + .formatted(wireMock.getPort(), path))); + } + + private void decide(PolicyApi api, UUID component, UUID violation, String state, boolean suppressed) { + api.decide(Map.of( + "component", + component.toString(), + "policyViolation", + violation.toString(), + "analysisState", + state, + "isSuppressed", + suppressed)); + } + + private void seedFindings(UUID component) throws Exception { + sql(""" + INSERT INTO "VULNERABILITY" ("UUID", "VULNID", "SOURCE", "SEVERITY") + VALUES (gen_random_uuid(), 'CVE-2021-44228', 'NVD', 'CRITICAL'), + (gen_random_uuid(), 'CVE-2021-45046', 'NVD', 'CRITICAL'), + (gen_random_uuid(), 'CVE-2099-00001', 'NVD', 'CRITICAL'); + INSERT INTO "COMPONENTS_VULNERABILITIES" ("COMPONENT_ID", "VULNERABILITY_ID") + SELECT c."ID", v."ID" FROM "COMPONENT" c CROSS JOIN "VULNERABILITY" v + WHERE c."UUID" = '%s'; + INSERT INTO "FINDINGATTRIBUTION" ( + "ANALYZERIDENTITY", "ATTRIBUTED_ON", "PROJECT_ID", "COMPONENT_ID", "VULNERABILITY_ID") + SELECT 'none', now(), c."PROJECT_ID", c."ID", v."ID" + FROM "COMPONENT" c CROSS JOIN "VULNERABILITY" v + WHERE c."UUID" = '%s'; + """.formatted(component, component)); + assertThat(sql("SELECT COUNT(*) FROM \"FINDINGATTRIBUTION\"")).isEqualTo("3"); + } + + private void setKevs(String... ids) throws Exception { + final String values = java.util.Arrays.stream(ids) + .map(id -> "('local-test', 'NVD', '" + id + "')") + .collect(java.util.stream.Collectors.joining(",")); + sql("DELETE FROM \"KEV_ASSERTION\" WHERE \"ASSERTER\" = 'local-test';" + + "INSERT INTO \"KEV_ASSERTION\" (\"ASSERTER\", \"VULN_SOURCE\", \"VULN_ID\") VALUES " + values); + } + + private void analyzeAndDrain(PolicyApi api, UUID project) throws Exception { + final UUID run = UUID.fromString(api.analyze(project).token()); + await("real public analysis workflow completes") + .atMost(Duration.ofSeconds(30)) + .untilAsserted(() -> assertThat(sql("SELECT status FROM dex_workflow_run WHERE id = '" + run + "'")) + .isEqualTo("COMPLETED")); + // Outbox deletion and workflow creation share a transaction, so this has no relay gap. + await("all durable webhook publishes complete") + .atMost(Duration.ofSeconds(30)) + .untilAsserted(() -> assertThat(sql(""" + SELECT NOT EXISTS (SELECT 1 FROM "NOTIFICATION_OUTBOX") + AND NOT EXISTS (SELECT 1 FROM dex_workflow_run + WHERE workflow_name = 'publish-notification' + AND status NOT IN ('COMPLETED', 'FAILED', 'CANCELLED')) + """)).isEqualTo("t")); + assertThat(sql("SELECT COUNT(*) FROM dex_workflow_run WHERE workflow_name = 'publish-notification'" + + " AND status IN ('FAILED', 'CANCELLED')")) + .isEqualTo("0"); + } + + private void assertDecision(String state, boolean suppressed) throws Exception { + assertThat(sql("SELECT \"STATE\" || ':' || \"SUPPRESSED\"::text FROM \"VIOLATIONANALYSIS\"")) + .isEqualTo(state + ":" + suppressed); + } + + private void assertCounts(int ordinary, int reviewed) throws IOException { + assertThat(notifications("/ordinary")).hasSize(ordinary); + assertThat(notifications("/reviewed")).hasSize(reviewed); + } + + private JsonNode assertUpdated( + String path, + String group, + String previous, + String current, + UUID violation, + String state, + boolean suppressed) + throws IOException { + final List matching = notifications(path).stream() + .filter(n -> n.path("group").asText().equals(group) + && n.path("subject").path("previousMessage").asText().equals(previous) + && n.path("subject").path("currentMessage").asText().equals(current)) + .toList(); + assertThat(matching).hasSize(1); + final JsonNode notification = matching.getFirst(); + final JsonNode subject = notification.path("subject"); + assertThat(subject.path("policyViolation").path("uuid").asText()).isEqualTo(violation.toString()); + assertThat(subject.path("policyViolation").path("message").asText()).isEqualTo(current); + assertThat(subject.path("changedAt").asText()).isNotBlank(); + if (group.equals(REVIEWED)) { + assertThat(subject.path("analysisState").asText()).isEqualTo(state); + assertThat(subject.path("suppressed").asBoolean()).isEqualTo(suppressed); + assertThat(subject.has("suppressed")).isTrue(); + } else { + assertThat(subject.has("analysisState")).isFalse(); + assertThat(subject.has("suppressed")).isFalse(); + } + return notification; + } + + private List notifications(String path) throws IOException { + final var result = new ArrayList(); + for (final var request : wireMock.findAll(postRequestedFor(urlPathEqualTo(path)))) { + result.add(MAPPER.readTree(request.getBodyAsString()).path("notification")); + } + return result; + } + + private String sql(String statement) throws Exception { + final var result = postgresContainer.execInContainer( + "psql", "-X", "-A", "-t", "-v", "ON_ERROR_STOP=1", "-U", "dtrack", "-d", "dtrack", "-c", statement); + assertThat(result.getExitCode()).withFailMessage(result.getStderr()).isZero(); + return result.getStdout().strip(); + } + + private static UUID uuid(Map object) { + return UUID.fromString(String.valueOf(object.get("uuid"))); + } + + @Path("/api/v1") + public interface PolicyApi { + @PUT + @Path("/project") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Map createProject(Map request); + + @PUT + @Path("/component/project/{uuid}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Map createComponent(@PathParam("uuid") UUID project, Map request); + + @PUT + @Path("/policy") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Map createPolicy(Map request); + + @PUT + @Path("/policy/{uuid}/condition") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Map createCondition(@PathParam("uuid") UUID policy, Map request); + + @PUT + @Path("/violation/analysis") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + Map decide(Map request); + + @POST + @Path("/finding/project/{uuid}/analyze") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + EventTokenResponse analyze(@PathParam("uuid") UUID project); + } +} diff --git a/notification/api/src/main/java/org/dependencytrack/notification/api/NotificationFactory.java b/notification/api/src/main/java/org/dependencytrack/notification/api/NotificationFactory.java index 5aed5242d4..b1b7272679 100644 --- a/notification/api/src/main/java/org/dependencytrack/notification/api/NotificationFactory.java +++ b/notification/api/src/main/java/org/dependencytrack/notification/api/NotificationFactory.java @@ -22,6 +22,7 @@ import com.fasterxml.uuid.impl.TimeBasedEpochRandomGenerator; import com.google.protobuf.Any; import com.google.protobuf.ByteString; +import com.google.protobuf.Timestamp; import com.google.protobuf.util.Timestamps; import org.dependencytrack.notification.proto.v1.AnalysisTrigger; import org.dependencytrack.notification.proto.v1.BackReference; @@ -41,6 +42,7 @@ import org.dependencytrack.notification.proto.v1.PolicyViolationAnalysis; 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.Scope; import org.dependencytrack.notification.proto.v1.UserSubject; @@ -67,6 +69,8 @@ import static org.dependencytrack.notification.proto.v1.Group.GROUP_NEW_VULNERABILITY; import static org.dependencytrack.notification.proto.v1.Group.GROUP_NEW_VULNERABLE_DEPENDENCY; import static org.dependencytrack.notification.proto.v1.Group.GROUP_POLICY_VIOLATION; +import static org.dependencytrack.notification.proto.v1.Group.GROUP_POLICY_VIOLATION_UPDATED; +import static org.dependencytrack.notification.proto.v1.Group.GROUP_POLICY_VIOLATION_UPDATED_REVIEWED; import static org.dependencytrack.notification.proto.v1.Group.GROUP_PROJECT_AUDIT_CHANGE; import static org.dependencytrack.notification.proto.v1.Group.GROUP_PROJECT_CREATED; import static org.dependencytrack.notification.proto.v1.Group.GROUP_UNSPECIFIED; @@ -404,6 +408,79 @@ public static Notification createPolicyViolationNotification( .build(); } + public static Notification createPolicyViolationUpdatedNotification( + Project project, + Component component, + PolicyViolation violation, + @Nullable String previousMessage, + @Nullable String currentMessage, + Timestamp changedAt) { + return createPolicyViolationUpdatedNotification( + project, component, violation, previousMessage, currentMessage, changedAt, null, null); + } + + /** + * Creates one update event using the review metadata captured by subject assembly. + * Approved or suppressed violations use a separately subscribed group. This does + * not change or clear the recorded review decision. + */ + public static Notification createPolicyViolationUpdatedNotification( + Project project, + Component component, + PolicyViolation violation, + @Nullable String previousMessage, + @Nullable String currentMessage, + Timestamp changedAt, + @Nullable String analysisState, + @Nullable Boolean suppressed) { + requireNonNull(project, "project must not be null"); + requireNonNull(component, "component must not be null"); + requireNonNull(violation, "violation must not be null"); + requireNonNull(changedAt, "changedAt must not be null"); + + final var violationBuilder = violation.toBuilder().clearMessage(); + final var subjectBuilder = PolicyViolationUpdatedSubject.newBuilder() + .setProject(project) + .setComponent(component) + .setChangedAt(changedAt); + if (previousMessage != null) { + subjectBuilder.setPreviousMessage(previousMessage); + } + if (currentMessage != null) { + subjectBuilder.setCurrentMessage(currentMessage); + violationBuilder.setMessage(currentMessage); + } + if (analysisState != null) { + subjectBuilder.setAnalysisState(analysisState); + } + if (suppressed != null) { + subjectBuilder.setSuppressed(suppressed); + } + subjectBuilder.setPolicyViolation(violationBuilder); + + final boolean reviewed = "APPROVED".equals(analysisState) || Boolean.TRUE.equals(suppressed); + final Group group = reviewed ? GROUP_POLICY_VIOLATION_UPDATED_REVIEWED : GROUP_POLICY_VIOLATION_UPDATED; + var title = (reviewed + ? "Reviewed Policy Violation Updated on Project: [" + : "Policy Violation Updated on Project: [") + + project.getName(); + if (project.hasVersion()) { + title += " : " + project.getVersion(); + } + title += "]"; + + final String content = reviewed + ? "The message of an approved or suppressed %s policy violation changed; the review decision is retained" + .formatted(violation.getType().toLowerCase(Locale.ROOT)) + : "The message of an existing %s policy violation changed" + .formatted(violation.getType().toLowerCase(Locale.ROOT)); + return newNotificationBuilder(SCOPE_PORTFOLIO, group, LEVEL_INFORMATIONAL) + .setTitle(title) + .setContent(content) + .setSubject(Any.pack(subjectBuilder.build())) + .build(); + } + public static Notification createProjectCreatedNotification(Project project) { requireNonNull(project, "project must not be null"); diff --git a/notification/api/src/main/java/org/dependencytrack/notification/api/TestNotificationFactory.java b/notification/api/src/main/java/org/dependencytrack/notification/api/TestNotificationFactory.java index ce3597792a..a881480613 100644 --- a/notification/api/src/main/java/org/dependencytrack/notification/api/TestNotificationFactory.java +++ b/notification/api/src/main/java/org/dependencytrack/notification/api/TestNotificationFactory.java @@ -54,6 +54,7 @@ import static org.dependencytrack.notification.api.NotificationFactory.createNewVulnerableDependencyNotification; import static org.dependencytrack.notification.api.NotificationFactory.createPolicyViolationAnalysisDecisionChangeNotification; import static org.dependencytrack.notification.api.NotificationFactory.createPolicyViolationNotification; +import static org.dependencytrack.notification.api.NotificationFactory.createPolicyViolationUpdatedNotification; import static org.dependencytrack.notification.api.NotificationFactory.createProjectCreatedNotification; import static org.dependencytrack.notification.api.NotificationFactory.createUserCreatedNotification; import static org.dependencytrack.notification.api.NotificationFactory.createUserDeletedNotification; @@ -74,6 +75,8 @@ import static org.dependencytrack.notification.proto.v1.Group.GROUP_NEW_VULNERABILITY; import static org.dependencytrack.notification.proto.v1.Group.GROUP_NEW_VULNERABLE_DEPENDENCY; import static org.dependencytrack.notification.proto.v1.Group.GROUP_POLICY_VIOLATION; +import static org.dependencytrack.notification.proto.v1.Group.GROUP_POLICY_VIOLATION_UPDATED; +import static org.dependencytrack.notification.proto.v1.Group.GROUP_POLICY_VIOLATION_UPDATED_REVIEWED; import static org.dependencytrack.notification.proto.v1.Group.GROUP_PROJECT_AUDIT_CHANGE; import static org.dependencytrack.notification.proto.v1.Group.GROUP_PROJECT_CREATED; import static org.dependencytrack.notification.proto.v1.Group.GROUP_USER_CREATED; @@ -127,6 +130,13 @@ private record SupplierMatrixKey(Scope scope, Group group, Level level) { Map.entry( new SupplierMatrixKey(SCOPE_PORTFOLIO, GROUP_POLICY_VIOLATION, LEVEL_INFORMATIONAL), TestNotificationFactory::createPolicyViolationTestNotification), + Map.entry( + new SupplierMatrixKey(SCOPE_PORTFOLIO, GROUP_POLICY_VIOLATION_UPDATED, LEVEL_INFORMATIONAL), + TestNotificationFactory::createPolicyViolationUpdatedTestNotification), + Map.entry( + new SupplierMatrixKey( + SCOPE_PORTFOLIO, GROUP_POLICY_VIOLATION_UPDATED_REVIEWED, LEVEL_INFORMATIONAL), + TestNotificationFactory::createReviewedPolicyViolationUpdatedTestNotification), Map.entry( new SupplierMatrixKey(SCOPE_PORTFOLIO, GROUP_PROJECT_AUDIT_CHANGE, LEVEL_INFORMATIONAL), TestNotificationFactory::createProjectAuditChangeTestNotification), @@ -227,6 +237,28 @@ public static Notification createPolicyViolationTestNotification() { createProject(), createComponent(), createPolicyViolation(createPolicyCondition(createPolicy()))); } + public static Notification createPolicyViolationUpdatedTestNotification() { + return createPolicyViolationUpdatedNotification( + createProject(), + createComponent(), + createPolicyViolation(createPolicyCondition(createPolicy())), + "CVE-2021-44228", + "CVE-2021-44228, CVE-2021-45046", + Timestamps.fromMillis(1149573966666L)); + } + + public static Notification createReviewedPolicyViolationUpdatedTestNotification() { + return createPolicyViolationUpdatedNotification( + createProject(), + createComponent(), + createPolicyViolation(createPolicyCondition(createPolicy())), + "CVE-2021-44228", + "CVE-2021-44228, CVE-2021-45046", + Timestamps.fromMillis(1149573966666L), + "APPROVED", + true); + } + public static Notification createProjectAuditChangeTestNotification() { return createVulnerabilityAnalysisDecisionChangeNotification( createProject(), diff --git a/notification/api/src/main/proto/org/dependencytrack/notification/v1/notification.proto b/notification/api/src/main/proto/org/dependencytrack/notification/v1/notification.proto index 827193f7a9..05227f220f 100644 --- a/notification/api/src/main/proto/org/dependencytrack/notification/v1/notification.proto +++ b/notification/api/src/main/proto/org/dependencytrack/notification/v1/notification.proto @@ -66,6 +66,13 @@ enum Group { // Scheduled summary of new policy violations across projects. GROUP_NEW_POLICY_VIOLATIONS_SUMMARY = 24; + // The message of an existing policy violation changed. + GROUP_POLICY_VIOLATION_UPDATED = 25; + + // The message of an approved or suppressed violation changed. + // Subscribing explicitly opts in to updates excluded from the ordinary group. + GROUP_POLICY_VIOLATION_UPDATED_REVIEWED = 26; + // Indexing service has been removed as of // https://github.com/DependencyTrack/hyades/issues/661 reserved 5; @@ -141,6 +148,22 @@ message PolicyViolationSubject { PolicyViolation policy_violation = 3; } +// Subject for ordinary and explicitly opted-in reviewed violation updates. +message PolicyViolationUpdatedSubject { + Component component = 1; + Project project = 2; + PolicyViolation policy_violation = 3; + // Absent means the previous message was null. + optional string previous_message = 4; + // Absent means the current message is null. + optional string current_message = 5; + google.protobuf.Timestamp changed_at = 6; + // Review metadata observed in the subject assembly statement snapshot. + // Absent means no state or suppression value was recorded, not false. + optional string analysis_state = 7; + optional bool suppressed = 8; +} + message VexConsumedOrProcessedSubject { Project project = 1; bytes vex = 2; diff --git a/notification/api/src/test/java/org/dependencytrack/notification/api/PolicyViolationUpdatedNotificationTest.java b/notification/api/src/test/java/org/dependencytrack/notification/api/PolicyViolationUpdatedNotificationTest.java new file mode 100644 index 0000000000..7706797b38 --- /dev/null +++ b/notification/api/src/test/java/org/dependencytrack/notification/api/PolicyViolationUpdatedNotificationTest.java @@ -0,0 +1,233 @@ +/* + * This file is part of Dependency-Track. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * Copyright (c) OWASP Foundation. All Rights Reserved. + */ +package org.dependencytrack.notification.api; + +import com.google.protobuf.DescriptorProtos; +import com.google.protobuf.Descriptors; +import com.google.protobuf.DynamicMessage; +import com.google.protobuf.util.Timestamps; +import org.dependencytrack.notification.proto.v1.Component; +import org.dependencytrack.notification.proto.v1.Group; +import org.dependencytrack.notification.proto.v1.Notification; +import org.dependencytrack.notification.proto.v1.PolicyViolation; +import org.dependencytrack.notification.proto.v1.PolicyViolationSubject; +import org.dependencytrack.notification.proto.v1.PolicyViolationUpdatedSubject; +import org.dependencytrack.notification.proto.v1.Project; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.dependencytrack.notification.api.NotificationFactory.createPolicyViolationNotification; +import static org.dependencytrack.notification.api.NotificationFactory.createPolicyViolationUpdatedNotification; + +class PolicyViolationUpdatedNotificationTest { + + private static Stream messageChanges() { + return Stream.of( + Arguments.of("CVE-A", "CVE-A,CVE-B"), + Arguments.of(null, "CVE-B"), + Arguments.of("CVE-A", null), + Arguments.of("", "CVE-B")); + } + + @ParameterizedTest + @MethodSource("messageChanges") + void shouldRoundTripStructuredChangesAndNullPresence(String previous, String current) throws Exception { + final var project = + Project.newBuilder().setUuid("project-id").setName("app").build(); + final var component = + Component.newBuilder().setUuid("component-id").setName("lib").build(); + final var violation = PolicyViolation.newBuilder() + .setUuid("stable-violation-id") + .setType("SECURITY") + .setMessage("stale hydration must not override the captured change") + .build(); + final var changedAt = Timestamps.fromMillis(1149573966666L); + + final Notification notification = + createPolicyViolationUpdatedNotification(project, component, violation, previous, current, changedAt); + final var subject = Notification.parseFrom(notification.toByteArray()) + .getSubject() + .unpack(PolicyViolationUpdatedSubject.class); + + assertThat(notification.getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION_UPDATED); + assertThat(notification.getId()).isNotBlank(); + assertThat(notification.hasTimestamp()).isTrue(); + assertThat(subject.getProject()).isEqualTo(project); + assertThat(subject.getComponent()).isEqualTo(component); + assertThat(subject.getPolicyViolation().getUuid()).isEqualTo(violation.getUuid()); + assertThat(subject.getChangedAt()).isEqualTo(changedAt); + assertThat(subject.hasAnalysisState()).isFalse(); + assertThat(subject.hasSuppressed()).isFalse(); + assertThat(subject.hasPreviousMessage()).isEqualTo(previous != null); + assertThat(subject.hasCurrentMessage()).isEqualTo(current != null); + assertThat(subject.getPreviousMessage()).isEqualTo(previous == null ? "" : previous); + assertThat(subject.getCurrentMessage()).isEqualTo(current == null ? "" : current); + assertThat(subject.getPolicyViolation().hasMessage()).isEqualTo(current != null); + assertThat(subject.getPolicyViolation().getMessage()).isEqualTo(current == null ? "" : current); + } + + @Test + void shouldPreserveCreationEventContract() throws Exception { + final var violation = PolicyViolation.newBuilder() + .setType("SECURITY") + .setMessage("CVE-A") + .build(); + final Notification created = createPolicyViolationNotification( + Project.newBuilder().setName("app").build(), Component.getDefaultInstance(), violation); + + assertThat(Group.GROUP_POLICY_VIOLATION.getNumber()).isEqualTo(15); + assertThat(created.getGroup()).isEqualTo(Group.GROUP_POLICY_VIOLATION); + assertThat(created.getSubject().unpack(PolicyViolationSubject.class).getPolicyViolation()) + .isEqualTo(violation); + assertThat(Group.GROUP_POLICY_VIOLATION_UPDATED.getNumber()).isEqualTo(25); + } + + @Test + void shouldBeReadableAndPreservedByPreviousProtobufSchema() throws Exception { + final var descriptor = Notification.getDescriptor().getFile(); + final var oldSchema = descriptor.toProto().toBuilder().clearEnumType().clearMessageType(); + for (final var enumType : descriptor.toProto().getEnumTypeList()) { + final var oldEnum = enumType.toBuilder().clearValue(); + for (final var value : enumType.getValueList()) { + if (!value.getName().startsWith("GROUP_POLICY_VIOLATION_UPDATED")) { + oldEnum.addValue(value); + } + } + oldSchema.addEnumType(oldEnum); + } + for (final DescriptorProtos.DescriptorProto message : + descriptor.toProto().getMessageTypeList()) { + if (!message.getName().equals("PolicyViolationUpdatedSubject")) { + oldSchema.addMessageType(message); + } + } + final var oldDescriptor = Descriptors.FileDescriptor.buildFrom( + oldSchema.build(), descriptor.getDependencies().toArray(Descriptors.FileDescriptor[]::new)); + final var oldNotificationDescriptor = oldDescriptor.findMessageTypeByName("Notification"); + final Notification updated = TestNotificationFactory.createPolicyViolationUpdatedTestNotification(); + + final DynamicMessage oldConsumer = DynamicMessage.parseFrom(oldNotificationDescriptor, updated.toByteArray()); + final var group = (Descriptors.EnumValueDescriptor) + oldConsumer.getField(oldNotificationDescriptor.findFieldByName("group")); + assertThat(group.getNumber()).isEqualTo(25); + assertThat(Notification.parseFrom(oldConsumer.toByteArray())).isEqualTo(updated); + } + + private static Stream reviewContexts() { + return Stream.of( + Arguments.of(null, null, false), + Arguments.of(null, false, false), + Arguments.of("NOT_SET", false, false), + Arguments.of("REJECTED", false, false), + Arguments.of("APPROVED", null, true), + Arguments.of("APPROVED", false, true), + Arguments.of(null, true, true), + Arguments.of("REJECTED", true, true), + Arguments.of("APPROVED", true, true)); + } + + @ParameterizedTest + @MethodSource("reviewContexts") + void shouldSelectExactlyOneGroupAndPreserveReviewMetadata( + @Nullable String state, @Nullable Boolean suppressed, boolean reviewed) throws Exception { + final var violation = PolicyViolation.newBuilder() + .setType("SECURITY") + .setUuid("stable-id") + .build(); + final Notification notification = createPolicyViolationUpdatedNotification( + Project.newBuilder().setName("app").build(), + Component.getDefaultInstance(), + violation, + "CVE-A", + "CVE-A,CVE-B", + Timestamps.fromMillis(1149573966666L), + state, + suppressed); + final var subject = Notification.parseFrom(notification.toByteArray()) + .getSubject() + .unpack(PolicyViolationUpdatedSubject.class); + + assertThat(notification.getGroup()) + .isEqualTo( + reviewed + ? Group.GROUP_POLICY_VIOLATION_UPDATED_REVIEWED + : Group.GROUP_POLICY_VIOLATION_UPDATED); + assertThat(subject.hasAnalysisState()).isEqualTo(state != null); + assertThat(subject.hasSuppressed()).isEqualTo(suppressed != null); + assertThat(subject.getAnalysisState()).isEqualTo(state == null ? "" : state); + assertThat(subject.getSuppressed()).isEqualTo(Boolean.TRUE.equals(suppressed)); + assertThat(subject.getPolicyViolation().getUuid()).isEqualTo("stable-id"); + assertThat(subject.getPolicyViolation().getMessage()).isEqualTo("CVE-A,CVE-B"); + if (reviewed) { + assertThat(notification.getTitle()).contains("Reviewed Policy Violation Updated"); + assertThat(notification.getContent()).contains("review decision is retained"); + } + } + + @Test + void shouldPreserveReviewedMetadataWithPreviousUpdateSchema() throws Exception { + final var descriptor = Notification.getDescriptor().getFile(); + final var oldSchema = descriptor.toProto().toBuilder().clearEnumType().clearMessageType(); + for (final var enumType : descriptor.toProto().getEnumTypeList()) { + final var oldEnum = enumType.toBuilder().clearValue(); + for (final var value : enumType.getValueList()) { + if (!value.getName().equals("GROUP_POLICY_VIOLATION_UPDATED_REVIEWED")) { + oldEnum.addValue(value); + } + } + oldSchema.addEnumType(oldEnum); + } + for (final var message : descriptor.toProto().getMessageTypeList()) { + if (!message.getName().equals("PolicyViolationUpdatedSubject")) { + oldSchema.addMessageType(message); + continue; + } + final var oldSubject = message.toBuilder().clearField().clearOneofDecl(); + message.getFieldList().stream() + .filter(field -> field.getNumber() <= 6) + .forEach(oldSubject::addField); + message.getOneofDeclList().stream() + .filter(oneof -> !oneof.getName().equals("_analysis_state") + && !oneof.getName().equals("_suppressed")) + .forEach(oldSubject::addOneofDecl); + oldSchema.addMessageType(oldSubject); + } + final var oldDescriptor = Descriptors.FileDescriptor.buildFrom( + oldSchema.build(), descriptor.getDependencies().toArray(Descriptors.FileDescriptor[]::new)); + final var reviewed = TestNotificationFactory.createReviewedPolicyViolationUpdatedTestNotification(); + final var subject = reviewed.getSubject().unpack(PolicyViolationUpdatedSubject.class); + final var oldSubject = DynamicMessage.parseFrom( + oldDescriptor.findMessageTypeByName("PolicyViolationUpdatedSubject"), subject.toByteArray()); + assertThat(oldSubject.getUnknownFields().asMap()).containsKeys(7, 8); + assertThat(PolicyViolationUpdatedSubject.parseFrom(oldSubject.toByteArray())) + .isEqualTo(subject); + final var oldNotificationDescriptor = oldDescriptor.findMessageTypeByName("Notification"); + final var oldNotification = DynamicMessage.parseFrom(oldNotificationDescriptor, reviewed.toByteArray()); + final var group = (Descriptors.EnumValueDescriptor) + oldNotification.getField(oldNotificationDescriptor.findFieldByName("group")); + assertThat(group.getNumber()).isEqualTo(26); + assertThat(Notification.parseFrom(oldNotification.toByteArray())).isEqualTo(reviewed); + } +} diff --git a/notification/publishing/src/main/java/org/dependencytrack/notification/publishing/kafka/KafkaNotificationPublisher.java b/notification/publishing/src/main/java/org/dependencytrack/notification/publishing/kafka/KafkaNotificationPublisher.java index 46593d2f41..92db4019e4 100644 --- a/notification/publishing/src/main/java/org/dependencytrack/notification/publishing/kafka/KafkaNotificationPublisher.java +++ b/notification/publishing/src/main/java/org/dependencytrack/notification/publishing/kafka/KafkaNotificationPublisher.java @@ -36,6 +36,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; @@ -159,6 +160,11 @@ public void publish(NotificationPublishContext ctx, Notification notification) { final var subject = notification.getSubject().unpack(PolicyViolationSubject.class); yield subject.getProject().getUuid(); } + case GROUP_POLICY_VIOLATION_UPDATED, GROUP_POLICY_VIOLATION_UPDATED_REVIEWED -> { + requireSubjectOfTypeAnyOf(notification, List.of(PolicyViolationUpdatedSubject.class)); + final var subject = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class); + yield subject.getProject().getUuid(); + } case GROUP_PROJECT_AUDIT_CHANGE -> { final Class matchingSubject = requireSubjectOfTypeAnyOf( notification, diff --git a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/console/default-template.peb b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/console/default-template.peb index 6effc17c5d..c2e97ad78c 100644 --- a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/console/default-template.peb +++ b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/console/default-template.peb @@ -8,3 +8,14 @@ Notification -- group: {{ notification.group }} -- title: {{ notification.title }} -- content: {{ notification.content }} +{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" -%} + -- violation: {{ subject.policyViolation.uuid }} + -- previous: {{ subject.previousMessage }} + -- current: {{ subject.currentMessage }} + -- changedAt: {{ subject.changedAt | formatTimestamp }} +{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" -%} + -- analysisState: {{ subject.analysisState }} + -- suppressed: {% if subject.hasSuppressed() %}{{ subject.suppressed }}{% else %}not recorded{% endif %} + -- review decision retained +{% endif -%} +{% endif -%} diff --git a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/email/default-template.peb b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/email/default-template.peb index a2aa576f62..064fc91487 100644 --- a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/email/default-template.peb +++ b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/email/default-template.peb @@ -97,7 +97,7 @@ Project: {{ subject.project.name }} Version: {{ subject.project.version }} Description: {{ subject.project.description }} Project URL: {{ baseUrl }}/projects/{{ subject.project.uuid }} -{% elseif notification.group == "GROUP_POLICY_VIOLATION" %} +{% elseif notification.group == "GROUP_POLICY_VIOLATION" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %} Project: {{ subject.project.name }} Version: {{ subject.project.version }} Description: {{ subject.project.description }} @@ -108,6 +108,17 @@ Component Version: {{ subject.component.version }} Component URL: {{ baseUrl }}/components/{{ subject.component.uuid }} Violated Policy: {{ subject.policyViolation.condition.policy.name }} +{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" -%} +Violation UUID: {{ subject.policyViolation.uuid }} +Previous Message: {{ subject.previousMessage }} +Current Message: {{ subject.currentMessage }} +Changed At: {{ subject.changedAt | formatTimestamp }} +{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" -%} +Analysis State: {{ subject.analysisState }} +Suppressed: {% if subject.hasSuppressed() %}{{ subject.suppressed }}{% else %}not recorded{% endif %} +Review Decision: Retained +{% endif -%} +{% endif -%} {% if subject.policyViolation.message is not empty -%} Message: {{ subject.policyViolation.message }} {% endif -%} diff --git a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/jira/default-template.peb b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/jira/default-template.peb index 9042b66a78..ba158aff9e 100644 --- a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/jira/default-template.peb +++ b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/jira/default-template.peb @@ -11,6 +11,8 @@ "description": "A new vulnerability has been identified on your project(s).\n\\\\\n\\\\\n*Vulnerability description*\n{code:none|bgColor=white|borderStyle=none}{{ subject.vulnerability.description | escape(strategy="json") }}{code}\n\n*VulnID*\n{{ subject.vulnerability.vulnId }}\n\n*Severity*\n{{ subject.vulnerability.severity | lower | capitalize }}\n\n*Component*\n[{{ subject.component | summarize | escape(strategy="json") }}|{{ baseUrl }}/components/{{ subject.component.uuid }}]\n\n*Affected project(s)*\n{% for project in subject.affectedProjectsList %}- [{{ project.name | escape(strategy="json") }} ({{ project.version | escape(strategy="json") }})|{{ baseUrl }}/projects/{{ project.uuid }}]\n{% endfor %}" {% elseif notification.group == "GROUP_NEW_VULNERABLE_DEPENDENCY" %} "description": "A component which contains one or more vulnerabilities has been added to your project.\n\\\\\n\\\\\n*Project*\n[{{ subject.project | summarize | escape(strategy="json") }}|{{ baseUrl }}/projects/{{ subject.project.uuid }}]\n\n*Component*\n[{{ subject.component | summarize | escape(strategy="json") }}|{{ baseUrl }}/components/{{ subject.component.uuid }}]\n\n*Vulnerabilities*\n{% for vulnerability in subject.vulnerabilitiesList %}- {{ vulnerability.vulnId }} ({{ vulnerability.severity | lower | capitalize }})\n{% endfor %}" + {% elseif notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %} + "description": "{{ notification.content | escape(strategy="json") }}\n\nProject: {{ subject.project | summarize | escape(strategy="json") }}\nComponent: {{ subject.component | summarize | escape(strategy="json") }}\nPolicy: {{ subject.policyViolation.condition.policy.name | escape(strategy="json") }}\nViolation UUID: {{ subject.policyViolation.uuid | escape(strategy="json") }}\nPrevious Message: {{ subject.previousMessage | escape(strategy="json") }}\nCurrent Message: {{ subject.currentMessage | escape(strategy="json") }}\nChanged At: {{ subject.changedAt | formatTimestamp | escape(strategy="json") }}{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}\nAnalysis State: {{ subject.analysisState | escape(strategy="json") }}\nSuppressed: {% if subject.hasSuppressed() %}{{ subject.suppressed }}{% else %}not recorded{% endif %}\nReview decision retained{% endif %}" {% else %} "description": "{{ notification.content | escape(strategy="json") }}\n\\\\\n\\\\\n*Level*\n{{ notification.level }}\n\n" {% endif %} diff --git a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/mattermost/default-template.peb b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/mattermost/default-template.peb index e35ffa6ada..1dfe9821a5 100644 --- a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/mattermost/default-template.peb +++ b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/mattermost/default-template.peb @@ -1,5 +1,5 @@ { "username": "Dependency Track", "icon_url": "https://raw.githubusercontent.com/DependencyTrack/branding/master/dt-logo-symbol-blue-background.png", - "text": "#### {{ notification.title | escape(strategy="json") }}\n{{ notification.content | escape(strategy="json") }}\n{% if notification.group == "GROUP_NEW_VULNERABILITY" %}**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n**Vulnerability**: {{ subject.vulnerability.vulnId | escape(strategy="json") }}, {{ subject.vulnerability.severity | escape(strategy="json") }}\n[View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}) - [View Vulnerability]({{ baseUrl }}/vulnerabilities/{{ subject.vulnerability.source | escape(strategy="json") }}/{{ subject.vulnerability.vulnId | escape(strategy="json") }}){% elseif notification.group == "GROUP_NEW_VULNERABLE_DEPENDENCY" %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}) - [View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}){% elseif notification.group == "GROUP_PROJECT_AUDIT_CHANGE" %}{% set isViolationAnalysis = subject.policyViolation is defined %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n{% if isViolationAnalysis %}**Policy**: {{ subject.policyViolation.condition.policy.name | escape(strategy="json") }}, {{ subject.policyViolation.condition.subject | escape(strategy="json") }} {{ subject.policyViolation.condition.operator | escape(strategy="json") }} {{ subject.policyViolation.condition.value | escape(strategy="json") }}{% else %}**Vulnerability**: {{ subject.vulnerability.vulnId | escape(strategy="json") }}, {{ subject.vulnerability.severity | escape(strategy="json") }}{% endif %}\n**Analysis**: {{ subject.analysis.state | escape(strategy="json") }}, suppressed: {{ subject.analysis.suppressed | escape(strategy="json") }}\n[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}) - [View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}){% if not isViolationAnalysis %} - [View Vulnerability]({{ baseUrl }}/vulnerabilities/{{ subject.vulnerability.source | escape(strategy="json") }}/{{ subject.vulnerability.vulnId | escape(strategy="json") }}){% endif %}{% elseif notification.group == "GROUP_BOM_CONSUMED" or notification.group == "GROUP_BOM_PROCESSED" %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}){% elseif notification.group == "GROUP_POLICY_VIOLATION" %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n**Policy**: {{ subject.policyViolation.condition.policy.violationState | escape(strategy="json") }}, {{ subject.policyViolation.condition.policy.name | escape(strategy="json") }}\n{% if subject.policyViolation.message is not empty %}**Message**: {{ subject.policyViolation.message | escape(strategy="json") }}\n{% endif %}[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}) - [View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}){% endif %}" + "text": "#### {{ notification.title | escape(strategy="json") }}\n{{ notification.content | escape(strategy="json") }}\n{% if notification.group == "GROUP_NEW_VULNERABILITY" %}**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n**Vulnerability**: {{ subject.vulnerability.vulnId | escape(strategy="json") }}, {{ subject.vulnerability.severity | escape(strategy="json") }}\n[View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}) - [View Vulnerability]({{ baseUrl }}/vulnerabilities/{{ subject.vulnerability.source | escape(strategy="json") }}/{{ subject.vulnerability.vulnId | escape(strategy="json") }}){% elseif notification.group == "GROUP_NEW_VULNERABLE_DEPENDENCY" %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}) - [View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}){% elseif notification.group == "GROUP_PROJECT_AUDIT_CHANGE" %}{% set isViolationAnalysis = subject.policyViolation is defined %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n{% if isViolationAnalysis %}**Policy**: {{ subject.policyViolation.condition.policy.name | escape(strategy="json") }}, {{ subject.policyViolation.condition.subject | escape(strategy="json") }} {{ subject.policyViolation.condition.operator | escape(strategy="json") }} {{ subject.policyViolation.condition.value | escape(strategy="json") }}{% else %}**Vulnerability**: {{ subject.vulnerability.vulnId | escape(strategy="json") }}, {{ subject.vulnerability.severity | escape(strategy="json") }}{% endif %}\n**Analysis**: {{ subject.analysis.state | escape(strategy="json") }}, suppressed: {{ subject.analysis.suppressed | escape(strategy="json") }}\n[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}) - [View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}){% if not isViolationAnalysis %} - [View Vulnerability]({{ baseUrl }}/vulnerabilities/{{ subject.vulnerability.source | escape(strategy="json") }}/{{ subject.vulnerability.vulnId | escape(strategy="json") }}){% endif %}{% elseif notification.group == "GROUP_BOM_CONSUMED" or notification.group == "GROUP_BOM_PROCESSED" %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}){% elseif notification.group == "GROUP_POLICY_VIOLATION" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}**Project**: {{ subject.project | summarize | escape(strategy="json") }}\n**Component**: {{ subject.component | summarize | escape(strategy="json") }}\n**Policy**: {{ subject.policyViolation.condition.policy.violationState | escape(strategy="json") }}, {{ subject.policyViolation.condition.policy.name | escape(strategy="json") }}\n{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}**Previous Message**: {{ subject.previousMessage | escape(strategy="json") }}\n**Current Message**: {{ subject.currentMessage | escape(strategy="json") }}\n**Changed At**: {{ subject.changedAt | formatTimestamp | escape(strategy="json") }}\n**Violation UUID**: {{ subject.policyViolation.uuid | escape(strategy="json") }}\n{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}**Analysis State**: {{ subject.analysisState | escape(strategy="json") }}\n**Suppressed**: {% if subject.hasSuppressed() %}{{ subject.suppressed }}{% else %}not recorded{% endif %}\nReview decision retained\n{% endif %}{% endif %}{% if subject.policyViolation.message is not empty %}**Message**: {{ subject.policyViolation.message | escape(strategy="json") }}\n{% endif %}[View Project]({{ baseUrl }}/projects/{{ subject.project.uuid | escape(strategy="json") }}) - [View Component]({{ baseUrl }}/components/{{ subject.component.uuid | escape(strategy="json") }}){% endif %}" } \ No newline at end of file diff --git a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/msteams/default-template.peb b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/msteams/default-template.peb index 1dc0b90949..2c46a52a6f 100644 --- a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/msteams/default-template.peb +++ b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/msteams/default-template.peb @@ -92,7 +92,7 @@ "value": "{{ subject.project | summarize | escape(strategy="json") }}" } ], - {% elseif notification.group == "GROUP_POLICY_VIOLATION" %} + {% elseif notification.group == "GROUP_POLICY_VIOLATION" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %} "facts": [ { "name": "Subject", @@ -113,7 +113,35 @@ { "name": "Project", "value": "{{ subject.project | summarize | escape(strategy="json") }}" - }{% if subject.policyViolation.message is not empty %}, + }{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}, + { + "name": "Previous Message", + "value": "{{ subject.previousMessage | escape(strategy="json") }}" + }, + { + "name": "Current Message", + "value": "{{ subject.currentMessage | escape(strategy="json") }}" + }, + { + "name": "Changed At", + "value": "{{ subject.changedAt | formatTimestamp | escape(strategy="json") }}" + }, + { + "name": "Violation UUID", + "value": "{{ subject.policyViolation.uuid | escape(strategy="json") }}" + }{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}, + { + "name": "Analysis State", + "value": "{{ subject.analysisState | escape(strategy="json") }}" + }, + { + "name": "Suppressed", + "value": "{% if subject.hasSuppressed() %}{{ subject.suppressed }}{% else %}not recorded{% endif %}" + }, + { + "name": "Review Decision", + "value": "Retained" + }{% endif %}{% endif %}{% if subject.policyViolation.message is not empty %}, { "name": "Message", "value": "{{ subject.policyViolation.message | escape(strategy="json") }}" diff --git a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/slack/default-template.peb b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/slack/default-template.peb index 69ca8e103f..033f57ad66 100644 --- a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/slack/default-template.peb +++ b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/slack/default-template.peb @@ -325,14 +325,14 @@ {% endif %} ] } -{% elseif notification.group == "GROUP_POLICY_VIOLATION" %} +{% elseif notification.group == "GROUP_POLICY_VIOLATION" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %} { "blocks": [ { "type": "header", "text": { "type": "plain_text", - "text": "Policy Violation" + "text": "{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}Reviewed Policy Violation Updated{% elseif notification.group == "GROUP_POLICY_VIOLATION_UPDATED" %}Policy Violation Updated{% else %}Policy Violation{% endif %}" } }, { @@ -350,7 +350,7 @@ { "type": "section", "text": { - "text": "OWASP Dependency-Track detected a policy violation. Details of the violation follow.", + "text": "{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}The message of an approved or suppressed policy violation changed. The review decision is retained.{% elseif notification.group == "GROUP_POLICY_VIOLATION_UPDATED" %}The message of an existing policy violation changed.{% else %}OWASP Dependency-Track detected a policy violation. Details of the violation follow.{% endif %}", "type": "plain_text" }, "fields": [ @@ -397,7 +397,14 @@ "text": "{{ subject.project.toString | escape(strategy="json") }}" } ] - }{% if subject.policyViolation.message is not empty %}, + }{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}, + { + "type": "section", + "text": { + "type": "plain_text", + "text": "Previous Message: {{ subject.previousMessage | escape(strategy="json") }}\nCurrent Message: {{ subject.currentMessage | escape(strategy="json") }}\nChanged At: {{ subject.changedAt | formatTimestamp | escape(strategy="json") }}\nViolation UUID: {{ subject.policyViolation.uuid | escape(strategy="json") }}{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}\nAnalysis State: {{ subject.analysisState | escape(strategy="json") }}\nSuppressed: {% if subject.hasSuppressed() %}{{ subject.suppressed }}{% else %}not recorded{% endif %}\nReview decision retained{% endif %}" + } + }{% endif %}{% if subject.policyViolation.message is not empty %}, { "type": "section", "text": { diff --git a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/webex/default-template.peb b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/webex/default-template.peb index 7a9dba5000..08e3a5c312 100644 --- a/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/webex/default-template.peb +++ b/notification/publishing/src/main/resources/org/dependencytrack/notification/publishing/webex/default-template.peb @@ -1 +1 @@ -{"markdown":"**{{ notification.title | escape(strategy="json") }}**{% if notification.group == "GROUP_NEW_VULNERABILITY" %}\n**VulnID:** {{ subject.vulnerability.vulnId | escape(strategy="json") }}\n**Severity:** {{ subject.vulnerability.severity | escape(strategy="json") }}\n**Source:** {{ subject.vulnerability.source | escape(strategy="json") }}\n**Component:** {{ subject.component | summarize | escape(strategy="json") }}\n**Actions:**\n[View Vulnerability]({{ baseUrl }}/vulnerability/?source={{ subject.vulnerability.source | escape(strategy="json") }}&vulnId={{ subject.vulnerability.vulnId | escape(strategy="json") }}){% elseif notification.group == "GROUP_NEW_VULNERABLE_DEPENDENCY" %}\n**Project:** {{ subject.project | summarize | escape(strategy="json") }}\n**Component:** {{ subject.component | summarize | escape(strategy="json") }}\n**Actions:**\n[View Project]({{ baseUrl }}/projects/?uuid={{ subject.project.uuid | escape(strategy="json") }}){% endif %}{% if subject.component is defined %}\n[View Component]({{ baseUrl }}/component/?uuid={{ subject.component.uuid | escape(strategy="json") }}){% endif %}\n**Description:** {{ notification.content | escape(strategy="json") }}"} \ No newline at end of file +{"markdown":"**{{ notification.title | escape(strategy="json") }}**{% if notification.group == "GROUP_NEW_VULNERABILITY" %}\n**VulnID:** {{ subject.vulnerability.vulnId | escape(strategy="json") }}\n**Severity:** {{ subject.vulnerability.severity | escape(strategy="json") }}\n**Source:** {{ subject.vulnerability.source | escape(strategy="json") }}\n**Component:** {{ subject.component | summarize | escape(strategy="json") }}\n**Actions:**\n[View Vulnerability]({{ baseUrl }}/vulnerability/?source={{ subject.vulnerability.source | escape(strategy="json") }}&vulnId={{ subject.vulnerability.vulnId | escape(strategy="json") }}){% elseif notification.group == "GROUP_NEW_VULNERABLE_DEPENDENCY" %}\n**Project:** {{ subject.project | summarize | escape(strategy="json") }}\n**Component:** {{ subject.component | summarize | escape(strategy="json") }}\n**Actions:**\n[View Project]({{ baseUrl }}/projects/?uuid={{ subject.project.uuid | escape(strategy="json") }}){% elseif notification.group == "GROUP_POLICY_VIOLATION_UPDATED" or notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}\n**Project:** {{ subject.project | summarize | escape(strategy="json") }}\n**Policy:** {{ subject.policyViolation.condition.policy.name | escape(strategy="json") }}\n**Previous Message:** {{ subject.previousMessage | escape(strategy="json") }}\n**Current Message:** {{ subject.currentMessage | escape(strategy="json") }}\n**Changed At:** {{ subject.changedAt | formatTimestamp | escape(strategy="json") }}\n**Violation UUID:** {{ subject.policyViolation.uuid | escape(strategy="json") }}{% if notification.group == "GROUP_POLICY_VIOLATION_UPDATED_REVIEWED" %}\n**Analysis State:** {{ subject.analysisState | escape(strategy="json") }}\n**Suppressed:** {% if subject.hasSuppressed() %}{{ subject.suppressed }}{% else %}not recorded{% endif %}\nReview decision retained{% endif %}{% endif %}{% if subject.component is defined %}\n[View Component]({{ baseUrl }}/component/?uuid={{ subject.component.uuid | escape(strategy="json") }}){% endif %}\n**Description:** {{ notification.content | escape(strategy="json") }}"} \ No newline at end of file diff --git a/notification/publishing/src/test/java/org/dependencytrack/notification/publishing/PolicyViolationUpdatedTemplateTest.java b/notification/publishing/src/test/java/org/dependencytrack/notification/publishing/PolicyViolationUpdatedTemplateTest.java new file mode 100644 index 0000000000..b10db5bf10 --- /dev/null +++ b/notification/publishing/src/test/java/org/dependencytrack/notification/publishing/PolicyViolationUpdatedTemplateTest.java @@ -0,0 +1,157 @@ +/* + * This file is part of Dependency-Track. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + * Copyright (c) OWASP Foundation. All Rights Reserved. + */ +package org.dependencytrack.notification.publishing; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.protobuf.Any; +import org.dependencytrack.notification.api.TestNotificationFactory; +import org.dependencytrack.notification.api.publishing.NotificationPublisherFactory; +import org.dependencytrack.notification.api.templating.NotificationTemplateVariables; +import org.dependencytrack.notification.proto.v1.PolicyViolationUpdatedSubject; +import org.dependencytrack.notification.publishing.console.ConsoleNotificationPublisherFactory; +import org.dependencytrack.notification.publishing.email.EmailNotificationPublisherFactory; +import org.dependencytrack.notification.publishing.jira.JiraNotificationPublisherFactory; +import org.dependencytrack.notification.publishing.mattermost.MattermostNotificationPublisherFactory; +import org.dependencytrack.notification.publishing.msteams.MsTeamsNotificationPublisherFactory; +import org.dependencytrack.notification.publishing.slack.SlackNotificationPublisherFactory; +import org.dependencytrack.notification.publishing.webex.WebexNotificationPublisherFactory; +import org.dependencytrack.notification.publishing.webhook.WebhookNotificationPublisherFactory; +import org.dependencytrack.notification.templating.pebble.PebbleNotificationTemplateRendererFactory; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import java.util.Map; +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; + +class PolicyViolationUpdatedTemplateTest { + + private static Stream publisherFactories() { + return Stream.of( + new ConsoleNotificationPublisherFactory(), + new EmailNotificationPublisherFactory(), + new JiraNotificationPublisherFactory(), + new MattermostNotificationPublisherFactory(), + new MsTeamsNotificationPublisherFactory(), + new SlackNotificationPublisherFactory(), + new WebexNotificationPublisherFactory(), + new WebhookNotificationPublisherFactory()); + } + + @ParameterizedTest + @MethodSource("publisherFactories") + void shouldRenderOldAndNewMessagesAndEscapeJson(NotificationPublisherFactory factory) throws Exception { + final var notification = TestNotificationFactory.createPolicyViolationUpdatedTestNotification(); + final var subject = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class).toBuilder() + .setPreviousMessage("CVE-A \"quoted\"\nline\t\\") + .setCurrentMessage("CVE-B \"quoted\"\nline\t\\") + .build(); + final var renderer = new PebbleNotificationTemplateRendererFactory( + Map.of(NotificationTemplateVariables.BASE_URL, () -> "https://example.com"), true) + .createRenderer(factory.defaultTemplate()); + final var rendered = renderer.render( + notification.toBuilder().setSubject(Any.pack(subject)).build(), + Map.of("jiraProjectKey", "TEST", "jiraTicketType", "Task")); + + assertThat(rendered).isNotNull(); + assertThat(rendered.content()) + .contains("CVE-A", "CVE-B", subject.getPolicyViolation().getUuid(), "2006-06-06T06:06:06"); + if (rendered.mimeType().equals("application/json")) { + assertThat(new ObjectMapper().readTree(rendered.content()).isObject()) + .isTrue(); + } + } + + @Test + void webhookShouldPreserveNullPresenceAndExactMessages() throws Exception { + final var notification = TestNotificationFactory.createPolicyViolationUpdatedTestNotification(); + final var subject = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class).toBuilder() + .clearCurrentMessage() + .setPreviousMessage("CVE-A \"quoted\"\nline") + .build(); + final var renderer = new PebbleNotificationTemplateRendererFactory(Map.of(), true) + .createRenderer(new WebhookNotificationPublisherFactory().defaultTemplate()); + final var rendered = renderer.render( + notification.toBuilder().setSubject(Any.pack(subject)).build()); + assertThat(rendered).isNotNull(); + final var jsonSubject = new ObjectMapper() + .readTree(rendered.content()) + .path("notification") + .path("subject"); + assertThat(jsonSubject.path("previousMessage").asText()).isEqualTo(subject.getPreviousMessage()); + assertThat(jsonSubject.has("currentMessage")).isFalse(); + assertThat(jsonSubject.path("changedAt").asText()).isEqualTo("2006-06-06T06:06:06.666Z"); + } + + private static Stream reviewedContexts() { + return publisherFactories() + .flatMap(factory -> Stream.of( + Arguments.of(factory, null), Arguments.of(factory, false), Arguments.of(factory, true))); + } + + @ParameterizedTest + @MethodSource("reviewedContexts") + void shouldRenderReviewedContextAndPreserveUnknownSuppression( + NotificationPublisherFactory factory, @Nullable Boolean suppressed) throws Exception { + final var notification = TestNotificationFactory.createReviewedPolicyViolationUpdatedTestNotification(); + final var subjectBuilder = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class).toBuilder() + .clearSuppressed(); + if (suppressed != null) { + subjectBuilder.setSuppressed(suppressed); + } + final var subject = subjectBuilder.build(); + final var renderer = new PebbleNotificationTemplateRendererFactory( + Map.of(NotificationTemplateVariables.BASE_URL, () -> "https://example.com"), true) + .createRenderer(factory.defaultTemplate()); + final var rendered = renderer.render( + notification.toBuilder().setSubject(Any.pack(subject)).build(), + Map.of("jiraProjectKey", "TEST", "jiraTicketType", "Task")); + assertThat(rendered).isNotNull(); + assertThat(rendered.content()) + .contains( + "APPROVED", + subject.getPolicyViolation().getUuid(), + subject.getPreviousMessage(), + subject.getCurrentMessage()); + assertThat(rendered.content()).containsIgnoringCase("review"); + if (rendered.mimeType().equals("application/json")) { + assertThat(new ObjectMapper().readTree(rendered.content()).isObject()) + .isTrue(); + } + if (factory instanceof WebhookNotificationPublisherFactory) { + final var jsonSubject = new ObjectMapper() + .readTree(rendered.content()) + .path("notification") + .path("subject"); + assertThat(jsonSubject.path("analysisState").asText()).isEqualTo("APPROVED"); + assertThat(jsonSubject.has("suppressed")).isEqualTo(suppressed != null); + if (suppressed != null) { + assertThat(jsonSubject.path("suppressed").asBoolean()).isEqualTo(suppressed); + } + } else if (suppressed == null) { + assertThat(rendered.content()).contains("not recorded"); + } else { + assertThat(rendered.content()).contains(suppressed.toString()); + } + } +} diff --git a/notification/templating/src/main/java/org/dependencytrack/notification/templating/pebble/PebbleNotificationTemplateRenderer.java b/notification/templating/src/main/java/org/dependencytrack/notification/templating/pebble/PebbleNotificationTemplateRenderer.java index f9062016ab..1a909cac1a 100644 --- a/notification/templating/src/main/java/org/dependencytrack/notification/templating/pebble/PebbleNotificationTemplateRenderer.java +++ b/notification/templating/src/main/java/org/dependencytrack/notification/templating/pebble/PebbleNotificationTemplateRenderer.java @@ -38,6 +38,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; @@ -188,6 +189,8 @@ private static String format(Timestamp protoTimestamp) { return subject.unpack(VexConsumedOrProcessedSubject.class); } else if (subject.is(PolicyViolationSubject.class)) { return subject.unpack(PolicyViolationSubject.class); + } else if (subject.is(PolicyViolationUpdatedSubject.class)) { + return subject.unpack(PolicyViolationUpdatedSubject.class); } else if (subject.is(UserSubject.class)) { return subject.unpack(UserSubject.class); } else if (subject.is(NewVulnerabilitiesSummarySubject.class)) { From 479104ef1e93e29d99dfe190e64074cfffd6b7a0 Mon Sep 17 00:00:00 2001 From: WenFeng Gao Date: Sat, 7 Nov 2026 18:52:46 +0800 Subject: [PATCH 2/2] Validate optional fields in policy update filters Make the documented notification filters explicit about optional message and review fields. Verify that absent values and a recorded false suppression flag do not match the corresponding filters in the real notification router. Signed-off-by: WenFeng Gao --- .../notification/NotificationRouterTest.java | 46 +++++++++++++++++++ docs/POLICY_VIOLATION_UPDATES.md | 9 ++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java b/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java index 9da015377a..d9ed99a88b 100644 --- a/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java +++ b/apiserver/src/test/java/org/dependencytrack/notification/NotificationRouterTest.java @@ -404,6 +404,52 @@ void shouldRequireIndependentUpdateSubscription() { }); } + @ParameterizedTest + @ValueSource(booleans = {false, true}) + void shouldApplyDocumentedOptionalFieldFiltersWithoutMatchingAbsentValues(boolean reviewed) throws Exception { + final Notification notification = reviewed + ? TestNotificationFactory.createReviewedPolicyViolationUpdatedTestNotification() + : TestNotificationFactory.createPolicyViolationUpdatedTestNotification(); + final var expressions = List.of( + "has(subject.current_message) && subject.current_message.contains('CVE-2021-45046')", + "has(subject.analysis_state) && subject.analysis_state == 'APPROVED'", + "has(subject.suppressed) && subject.suppressed"); + final var names = List.of("current-message", "approved", "suppressed"); + for (int index = 0; index < expressions.size(); index++) { + final var rule = new NotificationRule(); + rule.setName(names.get(index)); + rule.setTriggerType(NotificationTriggerType.EVENT); + rule.setScope(NotificationScope.PORTFOLIO); + rule.setNotifyOn(Set.of(convert(notification.getGroup()))); + rule.setNotificationLevel(NotificationLevel.INFORMATIONAL); + rule.setEnabled(true); + rule.setFilterExpression(expressions.get(index)); + qm.persist(rule); + } + assertThat(router.route(List.of(notification))) + .satisfiesExactly(result -> assertThat(result.ruleNames()) + .containsExactlyInAnyOrderElementsOf(reviewed ? names : List.of("current-message"))); + + final var absent = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class).toBuilder() + .clearCurrentMessage() + .clearAnalysisState() + .clearSuppressed() + .build(); + assertThat(router.route(List.of( + notification.toBuilder().setSubject(Any.pack(absent)).build()))) + .isEmpty(); + if (reviewed) { + final var unsuppressed = notification.getSubject().unpack(PolicyViolationUpdatedSubject.class).toBuilder() + .setSuppressed(false) + .build(); + assertThat(router.route(List.of(notification.toBuilder() + .setSubject(Any.pack(unsuppressed)) + .build()))) + .satisfiesExactly(result -> + assertThat(result.ruleNames()).containsExactlyInAnyOrder("current-message", "approved")); + } + } + @Test void shouldApplyProjectAndTagLimitsToUpdates() throws Exception { final var tag = qm.persist(new Tag("selected")); diff --git a/docs/POLICY_VIOLATION_UPDATES.md b/docs/POLICY_VIOLATION_UPDATES.md index 217ecb4cdc..d43ad0b0ac 100644 --- a/docs/POLICY_VIOLATION_UPDATES.md +++ b/docs/POLICY_VIOLATION_UPDATES.md @@ -42,7 +42,8 @@ The new subject type is An absent field means no captured value; ordinary-group events retain their original shape and omit review metadata. Decisions may change later without altering this historical event. -An example notification filter is `subject.current_message.contains('CVE-2021-45046')`. +An example notification filter is +`has(subject.current_message) && subject.current_message.contains('CVE-2021-45046')`. An arbitrary text change is not proof of a new KEV. Added and removed identifiers are not parsed from policy text. Set a filter appropriate to the policy and destination. Existing JSON webhook templates serialize the structured subject. Default human-readable templates @@ -59,6 +60,8 @@ This implementation needs no schema migration. Existing group numbers and config subscriptions stay unchanged. Older consumers should continue processing the original group; consumers newly subscribing to updates need support for the new group and subject. The reviewed update group uses Protobuf value 26 and the same subject type with additive optional fields. -A rule can use `subject.analysis_state == 'APPROVED'` or `subject.suppressed` to narrow the -reviewed events it receives. Normal project, tag and group subscriptions still apply; a CEL +A rule can use `has(subject.analysis_state) && subject.analysis_state == 'APPROVED'` or +`has(subject.suppressed) && subject.suppressed` to narrow the reviewed events it receives. +Presence checks distinguish an absent value from a recorded value. Normal project, tag and +group subscriptions still apply; a CEL filter cannot turn an ordinary-group subscription into a reviewed-group subscription.