diff --git a/Claude.md b/Claude.md index 93e928be..da3e7984 100644 --- a/Claude.md +++ b/Claude.md @@ -108,7 +108,7 @@ ast-eclipse-plugin/ | IDE Framework | Eclipse OSGi / RCP | 4.11+ | | UI Toolkit | SWT / JFace | Bundled with Eclipse | | Build System | Maven + Eclipse Tycho | Tycho 4.0.11 | -| Platform API | ast-cli-java-wrapper | 2.4.23 | +| Platform API | ast-cli-java-wrapper | dev (built from the wrapper `main` branch; has the severity-threshold overloads) | | Event Bus | Google Guava | Bundled with Eclipse | | Git Integration | JGit | Bundled with Eclipse | | JSON | Jackson | 2.21.1 | diff --git a/ast-cli-java-wrapper.version b/ast-cli-java-wrapper.version index bd7d9225..38f8e886 100644 --- a/ast-cli-java-wrapper.version +++ b/ast-cli-java-wrapper.version @@ -1 +1 @@ -2.4.33 +dev diff --git a/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/devassist/backend/SeverityThresholdRescannerTest.java b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/devassist/backend/SeverityThresholdRescannerTest.java new file mode 100644 index 00000000..8730f8c3 --- /dev/null +++ b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/devassist/backend/SeverityThresholdRescannerTest.java @@ -0,0 +1,166 @@ +package checkmarx.ast.eclipse.plugin.tests.unit.devassist.backend; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import com.checkmarx.eclipse.common.preferences.SeverityThreshold; +import com.checkmarx.eclipse.devassist.backend.SeverityThresholdRescanner; +import com.checkmarx.eclipse.devassist.model.ScanIssue; + +/** + * Tests the pure decisions of the severity threshold change: which files are remembered for the rescan + * (taken BEFORE everything is cleared) and which earlier findings are put back when a rescan fails. + */ +class SeverityThresholdRescannerTest { + + private static ScanIssue issue(String id, String severity) { + ScanIssue issue = new ScanIssue(); + issue.setScanIssueId(id); + issue.setSeverity(severity); + return issue; + } + + private static List ids(List issues) { + List ids = new ArrayList<>(); + for (ScanIssue issue : issues) { + ids.add(issue.getScanIssueId()); + } + return ids; + } + + // ---- snapshotOfFilesWithFindings ---- + + @Test + void snapshotKeepsOnlyFilesThatHaveFindings() { + Map> all = new LinkedHashMap<>(); + all.put("a.java", List.of(issue("1", "HIGH"))); + all.put("empty.java", new ArrayList<>()); + all.put("null.java", null); + all.put(null, List.of(issue("2", "HIGH"))); + + Map> snapshot = SeverityThresholdRescanner.snapshotOfFilesWithFindings(all); + + assertEquals(List.of("a.java"), new ArrayList<>(snapshot.keySet())); + assertEquals(List.of("1"), ids(snapshot.get("a.java"))); + } + + @Test + void snapshotOfNullOrEmptyIsEmpty() { + assertTrue(SeverityThresholdRescanner.snapshotOfFilesWithFindings(null).isEmpty()); + assertTrue(SeverityThresholdRescanner.snapshotOfFilesWithFindings(new LinkedHashMap<>()).isEmpty()); + } + + @Test + void snapshotIsNotAffectedWhenTheSourceIsClearedAfterwards() { + // The rescan list must survive clearing the results store. + List source = new ArrayList<>(List.of(issue("1", "HIGH"), issue("2", "LOW"))); + Map> all = new LinkedHashMap<>(); + all.put("a.java", source); + + Map> snapshot = SeverityThresholdRescanner.snapshotOfFilesWithFindings(all); + source.clear(); + all.clear(); + + assertEquals(List.of("a.java"), new ArrayList<>(snapshot.keySet())); + assertEquals(List.of("1", "2"), ids(snapshot.get("a.java"))); + assertNotSame(source, snapshot.get("a.java")); + } + + @Test + void snapshotKeepsFileOrder() { + Map> all = new LinkedHashMap<>(); + all.put("c.java", List.of(issue("3", "HIGH"))); + all.put("a.java", List.of(issue("1", "HIGH"))); + all.put("b.java", List.of(issue("2", "HIGH"))); + + assertEquals(Arrays.asList("c.java", "a.java", "b.java"), + new ArrayList<>(SeverityThresholdRescanner.snapshotOfFilesWithFindings(all).keySet())); + } + + // ---- findingsStillShownAt ---- + + @Test + void highThresholdKeepsCriticalAndHighOnly() { + List previous = List.of(issue("c", "CRITICAL"), issue("h", "HIGH"), issue("m", "MEDIUM"), + issue("l", "LOW")); + + assertEquals(List.of("c", "h"), ids(SeverityThresholdRescanner.findingsStillShownAt(previous, + SeverityThreshold.HIGH))); + } + + @Test + void criticalThresholdKeepsCriticalOnly() { + List previous = List.of(issue("c", "CRITICAL"), issue("h", "HIGH")); + + assertEquals(List.of("c"), ids(SeverityThresholdRescanner.findingsStillShownAt(previous, + SeverityThreshold.CRITICAL))); + } + + @Test + void lowThresholdKeepsEverythingExceptInfo() { + List previous = List.of(issue("c", "CRITICAL"), issue("l", "LOW"), issue("i", "INFO")); + + assertEquals(List.of("c", "l"), ids(SeverityThresholdRescanner.findingsStillShownAt(previous, + SeverityThreshold.LOW))); + } + + @Test + void maliciousOkAndUnknownAreAlwaysKept() { + List previous = List.of(issue("m", "MALICIOUS"), issue("o", "OK"), issue("u", "UNKNOWN"), + issue("l", "LOW")); + + assertEquals(List.of("m", "o", "u"), ids(SeverityThresholdRescanner.findingsStillShownAt(previous, + SeverityThreshold.CRITICAL))); + } + + @Test + void severityMatchIsCaseInsensitive() { + List previous = List.of(issue("h", "high"), issue("m", "Medium")); + + assertEquals(List.of("h"), ids(SeverityThresholdRescanner.findingsStillShownAt(previous, + SeverityThreshold.HIGH))); + } + + @Test + void missingSeverityIsKept() { + List previous = List.of(issue("n", null), issue("b", " ")); + + assertEquals(List.of("n", "b"), ids(SeverityThresholdRescanner.findingsStillShownAt(previous, + SeverityThreshold.CRITICAL))); + } + + @Test + void nullInputsGiveNothing() { + assertTrue(SeverityThresholdRescanner.findingsStillShownAt(null, SeverityThreshold.HIGH).isEmpty()); + assertTrue(SeverityThresholdRescanner.findingsStillShownAt(List.of(issue("h", "HIGH")), null).isEmpty()); + } + + @Test + void nullEntriesAreSkipped() { + List previous = new ArrayList<>(); + previous.add(null); + previous.add(issue("h", "HIGH")); + + assertEquals(List.of("h"), ids(SeverityThresholdRescanner.findingsStillShownAt(previous, + SeverityThreshold.HIGH))); + } + + @Test + void resultIsACopy() { + List previous = new ArrayList<>(List.of(issue("h", "HIGH"))); + + List kept = SeverityThresholdRescanner.findingsStillShownAt(previous, SeverityThreshold.HIGH); + previous.clear(); + + assertEquals(List.of("h"), ids(kept)); + } +} diff --git a/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/properties/SeverityThresholdTest.java b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/properties/SeverityThresholdTest.java new file mode 100644 index 00000000..e32db646 --- /dev/null +++ b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/properties/SeverityThresholdTest.java @@ -0,0 +1,108 @@ +package checkmarx.ast.eclipse.plugin.tests.unit.properties; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; + +import com.checkmarx.eclipse.common.preferences.SeverityThreshold; + +class SeverityThresholdTest { + + @Test + void defaultIsHigh() { + assertSame(SeverityThreshold.HIGH, SeverityThreshold.DEFAULT); + } + + @Test + void levelsAreOrderedFromCriticalToLow() { + assertEquals(List.of(SeverityThreshold.CRITICAL, SeverityThreshold.HIGH, SeverityThreshold.MEDIUM, + SeverityThreshold.LOW), List.of(SeverityThreshold.values())); + } + + @Test + void cliValueIsLowerCase() { + assertEquals("critical", SeverityThreshold.CRITICAL.getCliValue()); + assertEquals("high", SeverityThreshold.HIGH.getCliValue()); + assertEquals("medium", SeverityThreshold.MEDIUM.getCliValue()); + assertEquals("low", SeverityThreshold.LOW.getCliValue()); + } + + @Test + void labelsAreDisplayNames() { + assertEquals("Critical", SeverityThreshold.CRITICAL.getLabel()); + assertEquals("High", SeverityThreshold.HIGH.toString()); + } + + @Test + void fromValueIsCaseInsensitiveAndTrims() { + assertSame(SeverityThreshold.MEDIUM, SeverityThreshold.fromValue("medium")); + assertSame(SeverityThreshold.MEDIUM, SeverityThreshold.fromValue("MEDIUM")); + assertSame(SeverityThreshold.LOW, SeverityThreshold.fromValue(" Low ")); + } + + @Test + void fromValueFallsBackToDefaultForMissingOrInvalid() { + assertSame(SeverityThreshold.DEFAULT, SeverityThreshold.fromValue(null)); + assertSame(SeverityThreshold.DEFAULT, SeverityThreshold.fromValue("")); + assertSame(SeverityThreshold.DEFAULT, SeverityThreshold.fromValue(" ")); + assertSame(SeverityThreshold.DEFAULT, SeverityThreshold.fromValue("not-a-level")); + assertSame(SeverityThreshold.DEFAULT, SeverityThreshold.fromValue("malicious")); + } + + @Test + void fromLabelMatchesDropDownEntries() { + for (SeverityThreshold level : SeverityThreshold.values()) { + assertSame(level, SeverityThreshold.fromLabel(level.getLabel())); + } + assertSame(SeverityThreshold.DEFAULT, SeverityThreshold.fromLabel("")); + } + + @Test + void includedLabelsListThisLevelAndEverythingMoreSevere() { + assertEquals(List.of("Critical"), SeverityThreshold.CRITICAL.getIncludedLabels()); + assertEquals(List.of("Critical", "High"), SeverityThreshold.HIGH.getIncludedLabels()); + assertEquals(List.of("Critical", "High", "Medium", "Low"), SeverityThreshold.LOW.getIncludedLabels()); + } + + @Test + void highReportsCriticalAndHighOnly() { + SeverityThreshold high = SeverityThreshold.HIGH; + assertTrue(high.includes("CRITICAL")); + assertTrue(high.includes("High")); + assertFalse(high.includes("medium")); + assertFalse(high.includes("LOW")); + assertFalse(high.includes("Info")); + } + + @Test + void lowReportsEverythingExceptInfo() { + for (String severity : new String[] { "critical", "high", "medium", "low" }) { + assertTrue(SeverityThreshold.LOW.includes(severity), severity); + } + assertFalse(SeverityThreshold.LOW.includes("info")); + } + + @Test + void criticalReportsOnlyCritical() { + assertTrue(SeverityThreshold.CRITICAL.includes("critical")); + assertFalse(SeverityThreshold.CRITICAL.includes("high")); + } + + @Test + void missingOrUnrecognisedSeverityIsAlwaysIncluded() { + // Malicious, OK and Unknown are not threshold levels, so the threshold never hides them. + for (SeverityThreshold level : SeverityThreshold.values()) { + assertTrue(level.includes(null), level + " null"); + assertTrue(level.includes(""), level + " empty"); + assertTrue(level.includes(" "), level + " blank"); + assertTrue(level.includes("MALICIOUS"), level + " malicious"); + assertTrue(level.includes("OK"), level + " ok"); + assertTrue(level.includes("UNKNOWN"), level + " unknown"); + } + } +} diff --git a/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/wrapper/WrapperProviderTest.java b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/wrapper/WrapperProviderTest.java index 263f1ab9..ef93aab4 100644 --- a/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/wrapper/WrapperProviderTest.java +++ b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/wrapper/WrapperProviderTest.java @@ -8,7 +8,12 @@ import org.junit.jupiter.api.Test; import org.mockito.MockedConstruction; +import com.checkmarx.ast.asca.ScanResult; +import com.checkmarx.ast.containersrealtime.ContainersRealtimeResults; +import com.checkmarx.ast.iacrealtime.IacRealtimeResults; +import com.checkmarx.ast.ossrealtime.OssRealtimeResults; import com.checkmarx.ast.project.Project; +import com.checkmarx.ast.secretsrealtime.SecretsRealtimeResults; import com.checkmarx.ast.wrapper.CxWrapper; import com.checkmarx.eclipse.common.wrapper.WrapperProvider; @@ -60,4 +65,71 @@ void testTriageGetStates_propagatesExceptionFromWrapper() throws Exception { assertThrows(RuntimeException.class, () -> wrapperProvider.triageGetStates(false)); } } + + // ---- Severity threshold overloads: the threshold must reach the CxWrapper call -------------- + + @Test + void testOssRealtimeScan_withThreshold_forwardsThresholdToWrapper() throws Exception { + OssRealtimeResults expected = mock(OssRealtimeResults.class); + try (MockedConstruction mocked = mockConstruction(CxWrapper.class, + (mock, context) -> when(mock.ossRealtimeScan("pom.xml", "ignore.json", "high")).thenReturn(expected))) { + + assertSame(expected, wrapperProvider.ossRealtimeScan("pom.xml", "ignore.json", "high")); + } + } + + @Test + void testSecretsRealtimeScan_withThreshold_forwardsThresholdToWrapper() throws Exception { + SecretsRealtimeResults expected = mock(SecretsRealtimeResults.class); + try (MockedConstruction mocked = mockConstruction(CxWrapper.class, + (mock, context) -> when(mock.secretsRealtimeScan("a.txt", "ignore.json", "medium")).thenReturn(expected))) { + + assertSame(expected, wrapperProvider.secretsRealtimeScan("a.txt", "ignore.json", "medium")); + } + } + + @Test + void testContainersRealtimeScan_withThreshold_forwardsThresholdToWrapper() throws Exception { + ContainersRealtimeResults expected = mock(ContainersRealtimeResults.class); + try (MockedConstruction mocked = mockConstruction(CxWrapper.class, + (mock, context) -> when(mock.containersRealtimeScan("Dockerfile", "ignore.json", "low")).thenReturn(expected))) { + + assertSame(expected, wrapperProvider.containersRealtimeScan("Dockerfile", "ignore.json", "low")); + } + } + + @Test + void testIacRealtimeScan_withThreshold_forwardsThresholdToWrapper() throws Exception { + IacRealtimeResults expected = mock(IacRealtimeResults.class); + try (MockedConstruction mocked = mockConstruction(CxWrapper.class, + (mock, context) -> when(mock.iacRealtimeScan("main.tf", "docker", "ignore.json", "info")).thenReturn(expected))) { + + assertSame(expected, wrapperProvider.iacRealtimeScan("main.tf", "docker", "ignore.json", "info")); + } + } + + @Test + void testScanAsca_withThreshold_forwardsThresholdToWrapper() throws Exception { + ScanResult expected = mock(ScanResult.class); + try (MockedConstruction mocked = mockConstruction(CxWrapper.class, + (mock, context) -> when(mock.ScanAsca("A.java", true, "Eclipse", null, "critical")).thenReturn(expected))) { + + assertSame(expected, wrapperProvider.scanAsca("A.java", true, "Eclipse", null, "critical")); + } + } + + @Test + void testRealtimeScans_withoutThreshold_keepCallingTheOriginalWrapperMethods() throws Exception { + // Existing callers (for example the ignore-upkeep scans) must keep using the unfiltered methods. + OssRealtimeResults oss = mock(OssRealtimeResults.class); + ScanResult asca = mock(ScanResult.class); + try (MockedConstruction mocked = mockConstruction(CxWrapper.class, (mock, context) -> { + when(mock.ossRealtimeScan("pom.xml", "")).thenReturn(oss); + when(mock.ScanAsca("A.java", true, "Eclipse", null)).thenReturn(asca); + })) { + + assertSame(oss, wrapperProvider.ossRealtimeScan("pom.xml", "")); + assertSame(asca, wrapperProvider.scanAsca("A.java", true, "Eclipse", null)); + } + } } diff --git a/checkmarx-ast-eclipse-plugin/.classpath b/checkmarx-ast-eclipse-plugin/.classpath index 440b7d5f..78b90b4f 100644 --- a/checkmarx-ast-eclipse-plugin/.classpath +++ b/checkmarx-ast-eclipse-plugin/.classpath @@ -13,7 +13,7 @@ - + diff --git a/common-lib/.classpath b/common-lib/.classpath index f14be91d..3e275d4c 100644 --- a/common-lib/.classpath +++ b/common-lib/.classpath @@ -7,7 +7,7 @@ - + diff --git a/common-lib/META-INF/MANIFEST.MF b/common-lib/META-INF/MANIFEST.MF index 9319e109..0e2ab4a6 100644 --- a/common-lib/META-INF/MANIFEST.MF +++ b/common-lib/META-INF/MANIFEST.MF @@ -5,7 +5,7 @@ Bundle-SymbolicName: com.checkmarx.eclipse.common Bundle-Version: 1.0.0.qualifier Bundle-Vendor: Checkmarx Bundle-ClassPath: ., - lib/ast-cli-java-wrapper-2.4.33.jar, + lib/ast-cli-java-wrapper-dev.jar, lib/jackson-core-2.22.3.jar, lib/jackson-databind-2.22.3.jar, lib/jackson-annotations-2.21.jar, diff --git a/common-lib/build.properties b/common-lib/build.properties index b0672d7f..6ef727a8 100644 --- a/common-lib/build.properties +++ b/common-lib/build.properties @@ -1,6 +1,6 @@ output.. = bin/ bin.includes = META-INF/,\ - lib/ast-cli-java-wrapper-2.4.33.jar,\ + lib/ast-cli-java-wrapper-dev.jar,\ lib/jackson-core-2.22.3.jar,\ lib/jackson-databind-2.22.3.jar,\ lib/jackson-annotations-2.21.jar,\ diff --git a/common-lib/lib/ast-cli-java-wrapper-2.4.33.jar b/common-lib/lib/ast-cli-java-wrapper-2.4.33.jar deleted file mode 100644 index e47ab86d..00000000 --- a/common-lib/lib/ast-cli-java-wrapper-2.4.33.jar +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f333465404282a4c0e6a7f34c5198c51b68ca53b0746b9dec19b943c9e7e8fe7 -size 141718814 diff --git a/common-lib/lib/ast-cli-java-wrapper-dev.jar b/common-lib/lib/ast-cli-java-wrapper-dev.jar new file mode 100644 index 00000000..7325b1a1 --- /dev/null +++ b/common-lib/lib/ast-cli-java-wrapper-dev.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dfa3d83a25847b0da4aab6126356d50063d3a254bce5f7fa263881f8e75bd60 +size 167346742 diff --git a/common-lib/src/com/checkmarx/eclipse/common/preferences/CheckmarxPreferencePage.java b/common-lib/src/com/checkmarx/eclipse/common/preferences/CheckmarxPreferencePage.java index 7440bb3d..0eab164b 100644 --- a/common-lib/src/com/checkmarx/eclipse/common/preferences/CheckmarxPreferencePage.java +++ b/common-lib/src/com/checkmarx/eclipse/common/preferences/CheckmarxPreferencePage.java @@ -12,6 +12,10 @@ import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.FontData; +import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; @@ -45,6 +49,8 @@ public class CheckmarxPreferencePage extends PreferencePage implements IWorkbenc private Button containersCheckbox; private Button iacCheckbox; private Combo containersToolCombo; + private Combo severityThresholdCombo; + private Label severityThresholdHint; private Label mcpStatusLabel; private boolean loggedIn; @@ -139,6 +145,63 @@ protected Control createContents(Composite parent) { containersToolCombo.setItems(PluginConstants.CONTAINERS_TOOLS); containersToolCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); + // --- Severity Threshold Section (directly below the Containers Management Tool) --- + createSectionHeader(mainPanel, PluginConstants.DEVASSIST_PLUGIN_REALTIME_SCANNERS_SEVERITY_THRESHOLD_TITLE); + Composite severityThresholdComp = createIndentComposite(mainPanel); + Label severityThresholdDesc = new Label(severityThresholdComp, SWT.WRAP); + severityThresholdDesc.setText(PluginConstants.SEVERITY_THRESHOLD_DESCRIPTION); + severityThresholdDesc.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + severityThresholdCombo = new Combo(severityThresholdComp, SWT.READ_ONLY); + for (SeverityThreshold level : SeverityThreshold.values()) { + severityThresholdCombo.add(level.getLabel()); + } + severityThresholdCombo.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false)); + + // Info hint box: a blue info glyph plus the hint text, on a faint gray background with a light gray border. + // Both grays are blended from the page colours, so they also work in the dark theme. + Composite hintRow = new Composite(severityThresholdComp, SWT.NONE); + GridLayout hintRowLayout = new GridLayout(2, false); + hintRowLayout.marginWidth = 8; + hintRowLayout.marginHeight = 5; + hintRow.setLayout(hintRowLayout); + hintRow.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false)); // box width follows the text + Color pageBg = severityThresholdComp.getBackground(); + Color pageFg = severityThresholdComp.getForeground(); + Color hintFill = blend(pageBg, pageFg, 0.03); + Color hintBorder = blend(pageBg, pageFg, 0.12); + hintRow.setBackground(hintFill); + hintRow.setBackgroundMode(SWT.INHERIT_FORCE); + hintRow.addPaintListener(e -> { + Rectangle r = hintRow.getClientArea(); + e.gc.setForeground(hintBorder); + e.gc.drawRectangle(0, 0, r.width - 1, r.height - 1); + }); + hintRow.addDisposeListener(e -> { + hintFill.dispose(); + hintBorder.dispose(); + }); + + Label hintIcon = new Label(hintRow, SWT.NONE); + hintIcon.setText(new String(Character.toChars(0x24D8))); // circled "i" (ASCII-safe source) + hintIcon.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false)); + hintIcon.setForeground(hintIcon.getDisplay().getSystemColor(SWT.COLOR_LINK_FOREGROUND)); // theme-aware blue + FontData[] iconFontData = hintIcon.getFont().getFontData(); + for (FontData fd : iconFontData) { + fd.setHeight(fd.getHeight() + 3); // a little taller than the text, to fill the line height + } + Font iconFont = new Font(hintIcon.getDisplay(), iconFontData); + hintIcon.setFont(iconFont); + hintIcon.addDisposeListener(e -> iconFont.dispose()); + + severityThresholdHint = new Label(hintRow, SWT.WRAP); + severityThresholdCombo.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + updateSeverityThresholdHint(); + } + }); + // --- Checkmarx MCP Section --- // A horizontal rule marks this as a distinct settings group, separate from the // Realtime Scanner sections above. @@ -317,6 +380,46 @@ private void loadValues() { } else if (containersToolCombo.getItemCount() > 0) { containersToolCombo.select(0); } + + selectSeverityThreshold(Preferences.getSeverityThreshold()); + } + + /** Selects the given level in the Severity Threshold drop-down and refreshes the hint text. */ + private void selectSeverityThreshold(SeverityThreshold threshold) { + if (severityThresholdCombo == null || severityThresholdCombo.isDisposed()) { + return; + } + severityThresholdCombo.select(threshold.ordinal()); + updateSeverityThresholdHint(); + } + + /** A color {@code amount} (0..1) of the way from {@code from} to {@code to}; the caller disposes it. */ + private static Color blend(Color from, Color to, double amount) { + return new Color(from.getDevice(), + (int) (from.getRed() + (to.getRed() - from.getRed()) * amount), + (int) (from.getGreen() + (to.getGreen() - from.getGreen()) * amount), + (int) (from.getBlue() + (to.getBlue() - from.getBlue()) * amount)); + } + + /** Shows which severities the currently selected threshold reports. */ + private void updateSeverityThresholdHint() { + if (severityThresholdHint == null || severityThresholdHint.isDisposed() + || severityThresholdCombo == null || severityThresholdCombo.isDisposed()) { + return; + } + SeverityThreshold selected = SeverityThreshold.fromLabel(severityThresholdCombo.getText()); + severityThresholdHint.setText(String.format(PluginConstants.SEVERITY_THRESHOLD_HINT_FORMAT, + selected.getLabel(), joinLabels(selected.getIncludedLabels()))); + severityThresholdHint.getParent().getParent().layout(true, true); + } + + /** Joins labels as "A", "A & B" or "A, B & C"; the ampersand is doubled so the SWT Label shows it instead of treating it as a mnemonic. */ + private static String joinLabels(java.util.List labels) { + if (labels.size() <= 1) { + return String.join("", labels); + } + int last = labels.size() - 1; + return String.join(", ", labels.subList(0, last)) + " && " + labels.get(last); } @Override @@ -334,6 +437,7 @@ protected void performDefaults() { secretsCheckbox.setSelection(store.getDefaultBoolean(PREF_SECRETS_ENABLED)); containersCheckbox.setSelection(store.getDefaultBoolean(PREF_CONTAINERS_ENABLED)); iacCheckbox.setSelection(store.getDefaultBoolean(PREF_IAC_ENABLED)); + selectSeverityThreshold(SeverityThreshold.DEFAULT); super.performDefaults(); } @@ -431,6 +535,17 @@ public boolean performOk() { } } + // Severity threshold: fall back to the stored value when the control was never created + // or is already disposed (same defensive handling as the controls above). + SeverityThreshold severityThreshold = Preferences.getSeverityThreshold(); + if (severityThresholdCombo != null && !severityThresholdCombo.isDisposed()) { + try { + severityThreshold = SeverityThreshold.fromLabel(severityThresholdCombo.getText()); + } catch (Exception ex) { + CxLogger.warning("[PREFS-PAGE] Failed to read severityThresholdCombo text, using stored value: " + ex.getMessage()); + } + } + // Step 1: Save current UI state to preference store store.setValue(PREF_ASCA_ENABLED, ascaSelected); store.setValue(PREF_OSS_ENABLED, ossSelected); @@ -440,10 +555,12 @@ public boolean performOk() { if (containersTool != null) { store.setValue(PREF_CONTAINERS_TOOL, containersTool); } + store.setValue(Preferences.PREF_SEVERITY_THRESHOLD, severityThreshold.getCliValue()); // Diagnostic: Verify what was saved CxLogger.info("[PREFS-PAGE] Saved to preference store: ASCA=" + ascaSelected + ", OSS=" + ossSelected + - ", SECRETS=" + secretsSelected + ", CONTAINERS=" + containersSelected + ", IAC=" + iacSelected); + ", SECRETS=" + secretsSelected + ", CONTAINERS=" + containersSelected + ", IAC=" + iacSelected + + ", SEVERITY_THRESHOLD=" + severityThreshold.getCliValue()); // Step 2: Save as user preferences (mirrors JetBrains apply() method) // This preserves user's choices if features toggle on/off later diff --git a/common-lib/src/com/checkmarx/eclipse/common/preferences/Preferences.java b/common-lib/src/com/checkmarx/eclipse/common/preferences/Preferences.java index 293b9497..726b3372 100644 --- a/common-lib/src/com/checkmarx/eclipse/common/preferences/Preferences.java +++ b/common-lib/src/com/checkmarx/eclipse/common/preferences/Preferences.java @@ -34,6 +34,9 @@ public class Preferences { public static final String PREF_IAC_ENABLED = "scanner.iac.enabled"; public static final String PREF_CONTAINERS_TOOL = "scanner.containers.tool"; + // Dev Assist severity threshold (see SeverityThreshold); a missing or invalid value means the default (High) + public static final String PREF_SEVERITY_THRESHOLD = "scanner.severity.threshold"; + // User Preferences (preserved when features toggle) - mirrors JetBrains pattern public static final String USER_PREF_ASCA_ENABLED = "userPref.scanner.asca.enabled"; public static final String USER_PREF_OSS_ENABLED = "userPref.scanner.oss.enabled"; @@ -100,6 +103,14 @@ public static boolean isAuthenticated() { return isCredentialsValidated(); } + /** + * Current Dev Assist severity threshold. Returns {@link SeverityThreshold#DEFAULT} (High) when + * nothing is stored yet or the stored value is not a known level. + */ + public static SeverityThreshold getSeverityThreshold() { + return SeverityThreshold.fromValue(STORE.getString(PREF_SEVERITY_THRESHOLD)); + } + public static void setAuthenticationSuccessHandler(IAuthenticationSuccessHandler handler) { authSuccessHandler = handler; } diff --git a/common-lib/src/com/checkmarx/eclipse/common/preferences/SeverityThreshold.java b/common-lib/src/com/checkmarx/eclipse/common/preferences/SeverityThreshold.java new file mode 100644 index 00000000..ff940bb5 --- /dev/null +++ b/common-lib/src/com/checkmarx/eclipse/common/preferences/SeverityThreshold.java @@ -0,0 +1,96 @@ +package com.checkmarx.eclipse.common.preferences; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** + * Dev Assist severity threshold: the lowest severity the realtime scanners report. + *

+ * The threshold is a single minimum level, ordered {@code CRITICAL > HIGH > MEDIUM > LOW}. + * Choosing a level reports that level and everything more severe (the default {@link #HIGH} reports + * Critical and High). The value is passed to the Checkmarx CLI as {@code --severity-threshold}, which + * does the filtering and always keeps Malicious, OK and Unknown results; those are not threshold + * levels and are not part of this enum. + */ +public enum SeverityThreshold { + + CRITICAL("Critical"), + HIGH("High"), + MEDIUM("Medium"), + LOW("Low"); + + /** Threshold used when nothing (or an invalid value) is stored. */ + public static final SeverityThreshold DEFAULT = HIGH; + + private final String label; + + SeverityThreshold(String label) { + this.label = label; + } + + /** Display name shown in the settings drop-down. */ + public String getLabel() { + return label; + } + + /** Lower-case value passed to the CLI as {@code --severity-threshold}. */ + public String getCliValue() { + return name().toLowerCase(Locale.ROOT); + } + + /** Labels of this level and every more severe level, e.g. HIGH gives [Critical, High]. */ + public List getIncludedLabels() { + List labels = new ArrayList<>(); + for (SeverityThreshold level : values()) { + if (level.ordinal() <= ordinal()) { + labels.add(level.label); + } + } + return labels; + } + + /** + * Whether a finding with the given severity is shown at this threshold. A missing or + * unrecognised severity (for example Malicious, OK or Unknown) is always included. + */ + public boolean includes(String severity) { + if (severity == null || severity.trim().isEmpty()) { + return true; + } + if ("info".equalsIgnoreCase(severity.trim())) { + return false; // Info is below the lowest threshold (Low), so it is never shown + } + SeverityThreshold level = find(severity); + return level == null || level.ordinal() <= ordinal(); + } + + /** Parses a stored value (case-insensitive); a missing or invalid value gives {@link #DEFAULT}. */ + public static SeverityThreshold fromValue(String value) { + if (value == null || value.trim().isEmpty()) { + return DEFAULT; + } + SeverityThreshold level = find(value); + return level != null ? level : DEFAULT; + } + + /** Finds the drop-down entry with the given label, or {@link #DEFAULT} when there is none. */ + public static SeverityThreshold fromLabel(String label) { + return fromValue(label); + } + + private static SeverityThreshold find(String value) { + String trimmed = value.trim(); + for (SeverityThreshold level : values()) { + if (level.name().equalsIgnoreCase(trimmed)) { + return level; + } + } + return null; + } + + @Override + public String toString() { + return label; + } +} diff --git a/common-lib/src/com/checkmarx/eclipse/common/utils/PluginConstants.java b/common-lib/src/com/checkmarx/eclipse/common/utils/PluginConstants.java index 2e53df17..01e356da 100644 --- a/common-lib/src/com/checkmarx/eclipse/common/utils/PluginConstants.java +++ b/common-lib/src/com/checkmarx/eclipse/common/utils/PluginConstants.java @@ -170,6 +170,11 @@ public class PluginConstants { public static final String ASCA_CHECKBOX = "Scan your file as you code"; public static final String[] CONTAINERS_TOOLS = new String[] { "docker", "podman" }; + /**********************************Severity Threshold************************************/ + public static final String DEVASSIST_PLUGIN_REALTIME_SCANNERS_SEVERITY_THRESHOLD_TITLE = "Checkmarx Developer Assist Realtime Scanners: Severity Threshold"; + public static final String SEVERITY_THRESHOLD_DESCRIPTION = "Choose the lowest severity that the realtime scanners should report. Vulnerabilities at this severity and above are included. Changing severity threshold restarts the scan."; + public static final String SEVERITY_THRESHOLD_HINT_FORMAT = "%s: Realtime scanners will report %s vulnerabilities. Malicious findings are always included."; + /**********************************Checkmarx MCP************************************/ public static final String CHECKMARX_MCP_SECTION_TITLE = "Checkmarx : MCP"; public static final String MCP_DESCRIPTION = "The Model Context Protocol (MCP) provides advanced contextual analysis for secure coding."; diff --git a/common-lib/src/com/checkmarx/eclipse/common/wrapper/WrapperProvider.java b/common-lib/src/com/checkmarx/eclipse/common/wrapper/WrapperProvider.java index 9a857785..34834687 100644 --- a/common-lib/src/com/checkmarx/eclipse/common/wrapper/WrapperProvider.java +++ b/common-lib/src/com/checkmarx/eclipse/common/wrapper/WrapperProvider.java @@ -265,4 +265,51 @@ public IacRealtimeResults iacRealtimeScan(String path, String containerTool, Str public SecretsRealtimeResults secretsRealtimeScan(String path, String ignoreFilePath) throws Exception { return CxWrapperFactory.build().secretsRealtimeScan(path, ignoreFilePath); } + + // ------------------------------------------------------------------------------------------ + // Overloads that also pass the Dev Assist severity threshold (CLI --severity-threshold). + // The CLI does the filtering. A null or blank threshold adds no flag, so these behave like the + // methods above in that case. The methods above stay unchanged for existing callers. + // ------------------------------------------------------------------------------------------ + + /** + * Run a Checkmarx ASCA realtime scan on a file, reporting only findings at or above the threshold. + * @param severityThreshold lower-case level (critical, high, medium, low, info) or null for no filtering + */ + public ScanResult scanAsca(String path, boolean latestVersion, String agent, String ignoreFilePath, + String severityThreshold) throws Exception { + return CxWrapperFactory.build().ScanAsca(path, latestVersion, agent, ignoreFilePath, severityThreshold); + } + + /** + * Run a Checkmarx OSS realtime scan on a manifest file, reporting only findings at or above the threshold. + */ + public OssRealtimeResults ossRealtimeScan(String path, String ignoreFilePath, String severityThreshold) + throws Exception { + return CxWrapperFactory.build().ossRealtimeScan(path, ignoreFilePath, severityThreshold); + } + + /** + * Run a Checkmarx Containers realtime scan on a file, reporting only findings at or above the threshold. + */ + public ContainersRealtimeResults containersRealtimeScan(String path, String ignoreFilePath, + String severityThreshold) throws Exception { + return CxWrapperFactory.build().containersRealtimeScan(path, ignoreFilePath, severityThreshold); + } + + /** + * Run a Checkmarx IaC realtime scan on a file, reporting only findings at or above the threshold. + */ + public IacRealtimeResults iacRealtimeScan(String path, String containerTool, String ignoreFilePath, + String severityThreshold) throws Exception { + return CxWrapperFactory.build().iacRealtimeScan(path, containerTool, ignoreFilePath, severityThreshold); + } + + /** + * Run a Checkmarx Secrets realtime scan on a file, reporting only findings at or above the threshold. + */ + public SecretsRealtimeResults secretsRealtimeScan(String path, String ignoreFilePath, String severityThreshold) + throws Exception { + return CxWrapperFactory.build().secretsRealtimeScan(path, ignoreFilePath, severityThreshold); + } } diff --git a/devassist-lib/.classpath b/devassist-lib/.classpath index 17aa638a..b6957025 100644 --- a/devassist-lib/.classpath +++ b/devassist-lib/.classpath @@ -3,7 +3,7 @@ - + diff --git a/devassist-lib/META-INF/MANIFEST.MF b/devassist-lib/META-INF/MANIFEST.MF index 326e02f3..6e43c56d 100644 --- a/devassist-lib/META-INF/MANIFEST.MF +++ b/devassist-lib/META-INF/MANIFEST.MF @@ -33,4 +33,5 @@ Import-Package: com.fasterxml.jackson.annotation, Export-Package: com.checkmarx.eclipse.devassist.backend, com.checkmarx.eclipse.devassist.backend.listener, com.checkmarx.eclipse.devassist.ignore, + com.checkmarx.eclipse.devassist.model, com.checkmarx.eclipse.devassist.ui.findings.ignore diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/DevAssistScanStateHolder.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/DevAssistScanStateHolder.java index 503d066f..5477e893 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/DevAssistScanStateHolder.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/DevAssistScanStateHolder.java @@ -152,6 +152,15 @@ public void clearAll() { * @return Composite state hash */ public static long computeFileStateHash(String filePath) { + // The severity threshold is part of the key, so a threshold change invalidates cached entries by construction. + return withSeverityThreshold(computeContentStateHash(filePath)); + } + + private static long withSeverityThreshold(long contentHash) { + return contentHash * 31 + com.checkmarx.eclipse.common.preferences.Preferences.getSeverityThreshold().ordinal(); + } + + private static long computeContentStateHash(String filePath) { try { java.nio.file.Path path = java.nio.file.Paths.get(filePath); long fileModified = java.nio.file.Files.getLastModifiedTime(path).toMillis(); diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/ScannerPreferencesListener.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/ScannerPreferencesListener.java index 22e83f7a..be2c9ae2 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/ScannerPreferencesListener.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/ScannerPreferencesListener.java @@ -8,6 +8,7 @@ import com.checkmarx.eclipse.common.listener.ISettingsChangeNotifier; import com.checkmarx.eclipse.common.listener.IWorkspaceScanService; import com.checkmarx.eclipse.common.preferences.Preferences; +import com.checkmarx.eclipse.common.preferences.SeverityThreshold; import com.checkmarx.eclipse.common.utils.CxLogger; import com.checkmarx.eclipse.devassist.backend.ScannerRegistry.ScannerType; @@ -34,6 +35,9 @@ public class ScannerPreferencesListener implements ISettingsChangeNotifier { private static final String LOG_TAG = "[SCANNER-PREFS-LISTENER]"; + /** Severity threshold the scanners are currently running with; a change triggers a rescan. */ + private volatile SeverityThreshold appliedSeverityThreshold = Preferences.getSeverityThreshold(); + /** * Called when preferences are applied (from CheckmarxPreferencePage.performOk()). * Syncs the preference store with GlobalScannerController so execution guards use latest state, @@ -101,8 +105,34 @@ public void notifySettingsApplied() { } } + // Severity threshold changed: rescan so findings and gutter markers match the new threshold. + applySeverityThresholdChange(controller); + } catch (Exception e) { CxLogger.error(LOG_TAG + " Failed to sync preferences: " + e.getMessage(), e); } } + + /** + * Compares the stored severity threshold with the one the scanners run with and, when it changed, + * rescans (see {@link SeverityThresholdRescanner}). Only runs when something actually changed, so + * applying the preferences without touching the threshold never triggers a rescan. + */ + private void applySeverityThresholdChange(GlobalScannerController controller) { + SeverityThreshold threshold = Preferences.getSeverityThreshold(); + SeverityThreshold previous = appliedSeverityThreshold; + if (threshold == previous) { + return; + } + CxLogger.info(LOG_TAG + " Severity threshold changed from " + previous + " to " + threshold + ", rescanning"); + appliedSeverityThreshold = threshold; + + Set enabled = EnumSet.noneOf(ScannerType.class); + for (ScannerType type : ScannerType.values()) { + if (controller.isScannerEnabled(type)) { + enabled.add(type); + } + } + SeverityThresholdRescanner.rescan(enabled); + } } diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/SeverityThresholdRescanner.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/SeverityThresholdRescanner.java new file mode 100644 index 00000000..644462ff --- /dev/null +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/SeverityThresholdRescanner.java @@ -0,0 +1,436 @@ +package com.checkmarx.eclipse.devassist.backend; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.QualifiedName; +import org.eclipse.core.runtime.Status; +import org.eclipse.core.runtime.jobs.IJobManager; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.PlatformUI; + +import com.checkmarx.eclipse.common.listener.IWorkspaceScanService; +import com.checkmarx.eclipse.common.preferences.Preferences; +import com.checkmarx.eclipse.common.preferences.SeverityThreshold; +import com.checkmarx.eclipse.common.utils.CxLogger; +import com.checkmarx.eclipse.devassist.backend.ScannerRegistry.ScannerType; +import com.checkmarx.eclipse.devassist.backend.listener.ProjectLifecycleListener; +import com.checkmarx.eclipse.devassist.backend.listener.RealTimeScanJob; +import com.checkmarx.eclipse.devassist.backend.result.ResultPublisher; +import com.checkmarx.eclipse.devassist.common.ScanManager; +import com.checkmarx.eclipse.devassist.common.ScanManager.ScanOutcome; +import com.checkmarx.eclipse.devassist.ignore.IgnoreFileManager; +import com.checkmarx.eclipse.devassist.model.ScanIssue; +import com.checkmarx.eclipse.devassist.problems.ProblemDecorator; +import com.checkmarx.eclipse.devassist.problems.ProblemHolderService; +import com.checkmarx.eclipse.devassist.ui.findings.ignore.DevAssistIgnoredFindings; +import com.checkmarx.eclipse.devassist.ui.findings.marker.MarkerIssueMapper; + +/** + * Applies a changed Dev Assist severity threshold: every finding is removed straight away and the + * results that match the new threshold appear again as the scans finish. + *

+ * Order of work (all in one background job, so the preference dialog is never blocked): + *

    + *
  1. Scans that are still running (real-time editor scans, workspace scans) are cancelled and awaited, + * so a scan started under the old threshold cannot publish its result after the clear.
  2. + *
  3. The files that had findings are remembered (with their findings) BEFORE anything is cleared.
  4. + *
  5. The scan-state cache is cleared, so unchanged files are not skipped as "already scanned".
  6. + *
  7. All findings are removed: the results store, the editor gutter icons / underlines and the + * markers of every file that had findings. The Findings view empties.
  8. + *
  9. The remembered files are rescanned one by one and each result is published as it arrives. If a + * file's rescan fails or is skipped, its previous findings that still fit the new threshold are put + * back, so a failed scan never leaves a file blank.
  10. + *
  11. Then the existing workspace scan runs ({@link IWorkspaceScanService#scanWorkspace()}): it + * re-scans every OSS manifest file of the open projects and re-schedules the files open in the + * editors.
  12. + *
+ * The ignore file is never touched here. + */ +public final class SeverityThresholdRescanner { + + private static final String LOG_TAG = "[SEVERITY-THRESHOLD-RESCAN]"; + private static final String PLUGIN_ID = "com.checkmarx.eclipse.plugin"; + private static final QualifiedName REGISTRY_KEY = new QualifiedName(PLUGIN_ID, "scanner-registry"); + private static final QualifiedName STATE_HOLDER_KEY = new QualifiedName(PLUGIN_ID, "state-holder"); + private static final QualifiedName PROBLEM_HOLDER_KEY = new QualifiedName(PLUGIN_ID, "problem-holder"); + + /** Job families of the scans that must be stopped before the findings are cleared. */ + private static final Object[] RUNNING_SCAN_FAMILIES = { RealTimeScanJob.SCAN_FAMILY, + ProjectLifecycleListener.WORKSPACE_SCAN_FAMILY }; + + /** Longest time to wait for cancelled scans to end; a hung CLI call must not block the threshold change. */ + private static final long CANCEL_WAIT_TIMEOUT_MS = 30_000L; + private static final long CANCEL_WAIT_POLL_MS = 100L; + + private SeverityThresholdRescanner() { + } + + /** + * Applies the new threshold. Does nothing when the user is not logged in. + * + * @param enabledScanners scanners that are currently enabled (their cached scan state is cleared) + */ + public static void rescan(Set enabledScanners) { + if (!Preferences.isAuthenticated()) { + CxLogger.info(LOG_TAG + " Not authenticated - skipping rescan"); + return; + } + if (enabledScanners == null || enabledScanners.isEmpty()) { + CxLogger.info(LOG_TAG + " No scanner enabled - only refreshing the ignored findings page"); + refreshIgnoredFindingsPage(); + return; + } + + Job job = new ApplyThresholdJob(EnumSet.copyOf(enabledScanners)); + job.setPriority(Job.BUILD); + job.schedule(); + } + + // --------------------------------------------------------------------------------------------- + // Pure helpers (no Eclipse runtime needed, unit tested) + // --------------------------------------------------------------------------------------------- + + /** + * Copy of the entries that really hold findings. Files whose list is null or empty, and null keys, are + * dropped. The lists are copied, so later changes to the source do not affect the snapshot. + */ + public static Map> snapshotOfFilesWithFindings(Map> all) { + Map> snapshot = new LinkedHashMap<>(); + if (all == null) { + return snapshot; + } + for (Map.Entry> entry : all.entrySet()) { + if (entry.getKey() != null && entry.getValue() != null && !entry.getValue().isEmpty()) { + snapshot.put(entry.getKey(), new ArrayList<>(entry.getValue())); + } + } + return snapshot; + } + + /** + * The previous findings that are still shown at the given threshold. Used to put findings back when a + * file's rescan fails, so the file is not left blank. A null list or a null entry gives nothing. + */ + public static List findingsStillShownAt(List previous, SeverityThreshold threshold) { + if (previous == null || threshold == null) { + return Collections.emptyList(); + } + List kept = new ArrayList<>(); + for (ScanIssue issue : previous) { + if (issue != null && threshold.includes(issue.getSeverity())) { + kept.add(issue); + } + } + return kept; + } + + // --------------------------------------------------------------------------------------------- + + /** Findings per absolute file path, for every open project that has any. */ + static Map>> collectFindingsSnapshot() { + Map>> result = new LinkedHashMap<>(); + for (IProject project : ResourcesPlugin.getWorkspace().getRoot().getProjects()) { + if (!project.isOpen()) { + continue; + } + try { + ProblemHolderService holder = (ProblemHolderService) project.getSessionProperty(PROBLEM_HOLDER_KEY); + if (holder == null) { + continue; + } + Map> snapshot = snapshotOfFilesWithFindings(holder.getAllScanIssues()); + if (!snapshot.isEmpty()) { + result.put(project, snapshot); + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Could not read findings of project " + project.getName() + ": " + + e.getMessage()); + } + } + return result; + } + + /** OS paths of the files currently open in an editor. */ + static Set collectOpenEditorPaths() { + Set paths = new LinkedHashSet<>(); + try { + if (!PlatformUI.isWorkbenchRunning()) { + return paths; + } + for (org.eclipse.ui.IWorkbenchWindow window : PlatformUI.getWorkbench().getWorkbenchWindows()) { + for (org.eclipse.ui.IWorkbenchPage page : window.getPages()) { + for (org.eclipse.ui.IEditorReference ref : page.getEditorReferences()) { + try { + IFile file = ref.getEditorInput().getAdapter(IFile.class); + if (file != null && file.getLocation() != null) { + paths.add(file.getLocation().toOSString()); + } + } catch (Exception e) { + // editor input not available: treat as not open + } + } + } + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Could not read open editors: " + e.getMessage()); + } + return paths; + } + + private static IFile findFile(String path) { + IFile[] files = ResourcesPlugin.getWorkspace().getRoot().findFilesForLocation(Path.fromOSString(path)); + return (files != null && files.length > 0 && files[0].exists()) ? files[0] : null; + } + + /** Cancels the running scans and waits (bounded) until they have ended. */ + private static void cancelRunningScans(IProgressMonitor monitor) { + IJobManager jobManager = Job.getJobManager(); + for (Object family : RUNNING_SCAN_FAMILIES) { + jobManager.cancel(family); + } + long deadline = System.currentTimeMillis() + CANCEL_WAIT_TIMEOUT_MS; + try { + while (anyJobAlive(jobManager)) { + if (monitor.isCanceled()) { + return; + } + if (System.currentTimeMillis() > deadline) { + CxLogger.warning(LOG_TAG + " Cancelled scans did not end within " + CANCEL_WAIT_TIMEOUT_MS + + " ms - continuing anyway"); + return; + } + Thread.sleep(CANCEL_WAIT_POLL_MS); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + + private static boolean anyJobAlive(IJobManager jobManager) { + for (Object family : RUNNING_SCAN_FAMILIES) { + if (jobManager.find(family).length > 0) { + return true; + } + } + return false; + } + + /** + * Removes every finding of the snapshot: results store (the Findings view empties through its update + * event), editor gutter icons / underlines and markers. Files with an ignore entry keep their + * "ignored" gutter icon (the decorator draws it again). + */ + private static void clearFindings(Map>> snapshot) { + for (IProject project : snapshot.keySet()) { + try { + ProblemHolderService holder = (ProblemHolderService) project.getSessionProperty(PROBLEM_HOLDER_KEY); + if (holder != null) { + holder.clearAll(); + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Could not clear findings of project " + project.getName() + ": " + + e.getMessage()); + } + } + + Runnable clearEditors = () -> { + for (Map> files : snapshot.values()) { + for (String path : files.keySet()) { + try { + IFile file = findFile(path); + if (file == null) { + continue; + } + // Markers are removed here as well: the decorator returns early for a file that is not open. + MarkerIssueMapper.clearAllMarkers(file); + ProblemDecorator.decorateEditor(file, Collections.emptyList()); + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Could not clear decorations of " + path + ": " + e.getMessage()); + } + } + } + }; + runOnUiThread(clearEditors); + } + + /** Runs on the UI thread and waits for it; runs directly when there is no usable display. */ + private static void runOnUiThread(Runnable runnable) { + try { + if (PlatformUI.isWorkbenchRunning()) { + Display display = PlatformUI.getWorkbench().getDisplay(); + if (display != null && !display.isDisposed()) { + display.syncExec(runnable); + return; + } + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " UI thread not available: " + e.getMessage()); + } + runnable.run(); + } + + private static void finishWithWorkspaceScan() { + try { + IWorkspaceScanService scanService = Preferences.getWorkspaceScanService(); + if (scanService != null) { + scanService.scanWorkspace(); + } else { + CxLogger.warning(LOG_TAG + " No workspace scan service registered; cannot rescan manifests/editors"); + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Workspace rescan failed: " + e.getMessage()); + } + refreshIgnoredFindingsPage(); + } + + /** The ignored findings page filters by the threshold in the UI only; redraw it with the new value. */ + private static void refreshIgnoredFindingsPage() { + try { + if (!PlatformUI.isWorkbenchRunning()) { + return; + } + Display display = PlatformUI.getWorkbench().getDisplay(); + if (display != null && !display.isDisposed()) { + display.asyncExec(DevAssistIgnoredFindings::refreshIfOpen); + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Could not refresh the ignored findings page: " + e.getMessage()); + } + } + + /** Cancels running scans, clears every finding, rescans the files that had findings, then the workspace. */ + private static final class ApplyThresholdJob extends Job { + + private final Set enabledScanners; + + ApplyThresholdJob(Set enabledScanners) { + super("Checkmarx: applying the severity threshold"); + this.enabledScanners = enabledScanners; + } + + @Override + protected IStatus run(IProgressMonitor monitor) { + try { + // 1. Stop scans that started under the old threshold, so they cannot publish after the clear. + cancelRunningScans(monitor); + + // 2. Remember the files (and their findings) BEFORE anything is cleared. + Map>> snapshot = collectFindingsSnapshot(); + + // 3. Force fresh scans: otherwise unchanged files would be skipped as "already scanned". + ScanStateCacheClearer.clearForScanners(enabledScanners); + + // 4. Remove all findings now; the new results arrive as the scans finish. + clearFindings(snapshot); + + // 5. Rescan those files, then the existing workspace scan (OSS manifests, open editors). + if (!snapshot.isEmpty()) { + rescanFiles(snapshot, monitor); + } + if (monitor.isCanceled()) { + return Status.CANCEL_STATUS; + } + } catch (Exception e) { + CxLogger.error(LOG_TAG + " Applying the severity threshold failed: " + e.getMessage(), e); + } + // Always run the workspace scan, also after a failure above, so the view does not stay empty. + finishWithWorkspaceScan(); + return Status.OK_STATUS; + } + + private void rescanFiles(Map>> snapshot, IProgressMonitor monitor) { + for (Map.Entry>> entry : snapshot.entrySet()) { + IProject project = entry.getKey(); + if (monitor.isCanceled()) { + return; + } + if (!project.isOpen()) { + continue; + } + try { + rescanProjectFiles(project, entry.getValue(), monitor); + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Rescan failed for project " + project.getName() + ": " + e.getMessage()); + restoreFindings(project, entry.getValue(), entry.getValue().keySet()); + } + } + } + + private void rescanProjectFiles(IProject project, Map> previous, + IProgressMonitor monitor) throws Exception { + ScannerRegistry registry = (ScannerRegistry) project.getSessionProperty(REGISTRY_KEY); + DevAssistScanStateHolder stateHolder = (DevAssistScanStateHolder) project + .getSessionProperty(STATE_HOLDER_KEY); + if (registry == null || stateHolder == null) { + CxLogger.warning(LOG_TAG + " Scanner registry/state holder not ready for " + project.getName()); + restoreFindings(project, previous, previous.keySet()); + return; + } + // Same reconcile with disk that RealTimeScanJob does before scanning. + IgnoreFileManager.getInstance(project).refreshFromDisk(); + ScanManager scanManager = new ScanManager(registry, stateHolder); + Set openEditorPaths = collectOpenEditorPaths(); + + for (String path : new ArrayList<>(previous.keySet())) { + if (monitor.isCanceled()) { + return; + } + IFile file = findFile(path); + if (file == null) { + continue; // file was deleted or is outside the workspace + } + // Files open in an editor are rescanned from the live buffer by the workspace scan that follows. + if (openEditorPaths.contains(path)) { + continue; + } + try { + ScanOutcome outcome = scanManager.scanFileWithOutcome(path, monitor); + if (outcome.isScanned() && !monitor.isCanceled()) { + // A real scan ran: publish it, even when nothing is left. + ResultPublisher.publishResults(file, outcome.getIssues()); + } else { + // Skipped, cancelled or failed: do not leave the file blank. + restoreFindings(project, previous, Collections.singleton(path)); + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Could not rescan " + path + ": " + e.getMessage()); + restoreFindings(project, previous, Collections.singleton(path)); + } + } + } + + /** Puts back the earlier findings of the given files that still fit the new threshold. */ + private void restoreFindings(IProject project, Map> previous, + java.util.Collection paths) { + SeverityThreshold threshold = Preferences.getSeverityThreshold(); + for (String path : new ArrayList<>(paths)) { + try { + IFile file = findFile(path); + if (file == null) { + continue; + } + List kept = findingsStillShownAt(previous.get(path), threshold); + if (!kept.isEmpty()) { + ResultPublisher.publishResults(file, kept); + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Could not restore findings of " + path + ": " + e.getMessage()); + } + } + } + } +} diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/ProjectLifecycleListener.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/ProjectLifecycleListener.java index 6c70de3d..6b23d81e 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/ProjectLifecycleListener.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/ProjectLifecycleListener.java @@ -39,6 +39,9 @@ public class ProjectLifecycleListener implements IResourceChangeListener, IProje private static final QualifiedName REGISTRY_KEY = new QualifiedName(PLUGIN_ID, "scanner-registry"); private static final QualifiedName PROBLEM_HOLDER_KEY = new QualifiedName(PLUGIN_ID, "problem-holder"); private static final QualifiedName STATE_HOLDER_KEY = new QualifiedName(PLUGIN_ID, "state-holder"); + /** Job family of the per-project workspace scan jobs (used to cancel them together). */ + public static final String WORKSPACE_SCAN_FAMILY = "com.checkmarx.workspace.scan"; + private static final QualifiedName WORKSPACE_SCAN_JOB_KEY = new QualifiedName(PLUGIN_ID, "workspace-scan-job"); // Exclusion patterns (files/directories to skip during recursive scanning) @@ -291,6 +294,11 @@ public String getStatistics() { private void startWorkspaceFileScanning(IProject project) { Job scanJob = new Job("Checkmarx Workspace Scanner (" + project.getName() + ")") { + @Override + public boolean belongsTo(Object family) { + return WORKSPACE_SCAN_FAMILY.equals(family); + } + @Override protected IStatus run(IProgressMonitor monitor) { try { diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/RealTimeScanJob.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/RealTimeScanJob.java index e46915f3..7c778c71 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/RealTimeScanJob.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/backend/listener/RealTimeScanJob.java @@ -24,6 +24,9 @@ */ public class RealTimeScanJob extends Job { + /** Job family shared by every Checkmarx real-time scan job (used to cancel them together). */ + public static final String SCAN_FAMILY = "com.checkmarx.realtime.scan"; + private final IFile file; private final String fileName; @@ -231,7 +234,7 @@ private boolean isUserAuthenticated() { public boolean belongsTo(Object family) { // Group all Checkmarx real-time scan jobs together // This allows Eclipse to cancel all scans at once if needed - return family != null && family.equals("com.checkmarx.realtime.scan"); + return family != null && family.equals(SCAN_FAMILY); } /** diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/ignore/IgnoreManager.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/ignore/IgnoreManager.java index a06061bc..66917167 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/ignore/IgnoreManager.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/ignore/IgnoreManager.java @@ -688,6 +688,16 @@ public boolean hasIgnoredEntries(com.checkmarx.eclipse.devassist.utils.ScanEngin .anyMatch(entry -> entry.getType() == scanEngine); } + /** + * Whether any ignored entry of the given engine has a severity that the threshold filters out of scan results. + * Only then does a threshold-filtered scan hide a finding that ignore upkeep needs to see. + */ + public boolean hasIgnoredEntriesBelowThreshold(com.checkmarx.eclipse.devassist.utils.ScanEngine scanEngine, + com.checkmarx.eclipse.common.preferences.SeverityThreshold threshold) { + return ignoreFileManager.getIgnoreData().values().stream() + .anyMatch(entry -> entry.getType() == scanEngine && !threshold.includes(entry.getSeverity())); + } + /** * Creates a list of ignore entry keys for a given scan issue. * For IAC and ASCA scan engines, it generates keys for each vulnerability found in the scan issue. diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/problems/ProblemDecorator.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/problems/ProblemDecorator.java index adf6a684..0c820bd0 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/problems/ProblemDecorator.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/problems/ProblemDecorator.java @@ -332,10 +332,17 @@ private static List decorateIgnoredEntries(IFile file, ITextEditor e String annotationType = "com.checkmarx.eclipse.findings.ignored" + (DevAssistUtils.isDarkTheme() ? "_dark" : ""); + com.checkmarx.eclipse.common.preferences.SeverityThreshold threshold = com.checkmarx.eclipse.common.preferences.Preferences + .getSeverityThreshold(); for (IgnoreEntry entry : ignoreFileManager.getAllIgnoreEntries()) { if (entry.getFiles() == null) { continue; } + // Display-only: ignored entries below the severity threshold get no ignored gutter icon. + // The ignore file itself is never modified. + if (!threshold.includes(entry.getSeverity())) { + continue; + } for (IgnoreEntry.FileReference ref : entry.getFiles()) { if (!ref.isActive() || ref.getLine() == null) { continue; diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/asca/AscaScannerService.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/asca/AscaScannerService.java index 5b2ad7e1..053463b0 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/asca/AscaScannerService.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/asca/AscaScannerService.java @@ -104,13 +104,20 @@ private com.checkmarx.eclipse.devassist.common.ScanResult scanInternal(S return null; } // Run ASCA scan with proper temp file management - Object rawResults = runAscaScan(filePath, fileContent); + IgnoreUpkeepScan ignoreUpkeep = new IgnoreUpkeepScan(); + Object rawResults = runAscaScan(filePath, fileContent, ignoreUpkeep); if (rawResults == null) { return null; } com.checkmarx.ast.asca.ScanResult ascaScanResult = (com.checkmarx.ast.asca.ScanResult) rawResults; - // Update line numbers for ignored ASCA issues if any exist - updateIgnoredFileDataOnLatestResult(ascaScanResult, filePath, proj); + // Update line numbers for ignored ASCA issues if any exist. Use the unfiltered scan when the + // severity threshold may have hidden results; if that scan was needed but failed, skip the + // reconciliation so ignore entries are never removed based on filtered results. + if (!ignoreUpkeep.required) { + updateIgnoredFileDataOnLatestResult(ascaScanResult, filePath, proj); + } else if (ignoreUpkeep.result != null) { + updateIgnoredFileDataOnLatestResult(ignoreUpkeep.result, filePath, proj); + } return new AscaScanResultAdaptor(ascaScanResult, filePath, proj); } catch (Exception e) { CxLogger.error(LOG_TAG + " Scan failed: " + e.getMessage(), e); @@ -207,7 +214,7 @@ private String getFileContent(String filePath, IDocument document) { * Run ASCA scan with synchronized temp file management. Ensures temp files are * properly created and cleaned up. */ - private Object runAscaScan(String filePath, String fileContent) { + private Object runAscaScan(String filePath, String fileContent, IgnoreUpkeepScan ignoreUpkeep) { synchronized (SCAN_LOCK) { String tempFilePath = saveTempFile(Paths.get(filePath).getFileName().toString(), fileContent); if (tempFilePath == null) { @@ -220,6 +227,7 @@ private Object runAscaScan(String filePath, String fileContent) { String ignoreFilePath = getIgnoreFilePath(project); Object scanResult = executeAscaScanner(tempFilePath, ignoreFilePath); CxLogger.info(LOG_TAG + " ASCA scan completed"); + runIgnoreUpkeepScanIfNeeded(tempFilePath, ignoreFilePath, scanResult, ignoreUpkeep); return scanResult; } finally { deleteFile(tempFilePath); @@ -227,12 +235,43 @@ private Object runAscaScan(String filePath, String fileContent) { } } + /** + * The scan above only reports findings at or above the severity threshold, but the ignore-entry + * reconciliation (line numbers, and removal of entries whose finding is gone) must see every finding, + * otherwise ignore entries below the threshold would be deleted. When an ASCA ignore entry + * is below the threshold (so the scan hides it), run a second scan without the threshold, like the other scanners + * already do for their ignore upkeep. Must run before the temp file is deleted. + */ + private void runIgnoreUpkeepScanIfNeeded(String tempFilePath, String ignoreFilePath, Object filteredResult, + IgnoreUpkeepScan ignoreUpkeep) { + try { + com.checkmarx.eclipse.common.preferences.SeverityThreshold threshold = + com.checkmarx.eclipse.common.preferences.Preferences.getSeverityThreshold(); + if (filteredResult == null + || !IgnoreManager.getInstance(project).hasIgnoredEntriesBelowThreshold(ScanEngine.ASCA, threshold)) { + return; // no ignored entry can be hidden by the threshold: the scan result is complete + } + ignoreUpkeep.required = true; + ignoreUpkeep.result = scanAscaFile(tempFilePath, true, "Eclipse", ignoreFilePath, false); + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Unfiltered ASCA scan for ignore upkeep failed: " + e.getMessage()); + } + } + + /** Outcome of the unfiltered scan used to reconcile ignore entries (see runIgnoreUpkeepScanIfNeeded). */ + private static final class IgnoreUpkeepScan { + /** True when an unfiltered scan was needed because the threshold may hide results. */ + boolean required; + /** Result of that scan; null if it was not needed or failed. */ + com.checkmarx.ast.asca.ScanResult result; + } + /** * Execute ASCA scan using CxWrapperFactory. */ private Object executeAscaScanner(String filePath, String ignoreFilePath) { try { - return scanAscaFile(filePath, true, "Eclipse", ignoreFilePath); + return scanAscaFile(filePath, true, "Eclipse", ignoreFilePath, true); } catch (Exception e) { CxLogger.error(LOG_TAG + " ASCA scan error: " + e.getMessage(), e); return null; @@ -372,11 +411,19 @@ private void deleteFile(String filePath) { } } + /** + * @param applySeverityThreshold true for the scan whose results are shown (CLI reports only findings at or + * above the Dev Assist severity threshold); false for the unfiltered pass that + * only reconciles ignore entries + */ private com.checkmarx.ast.asca.ScanResult scanAscaFile(String path, boolean ascaLatestVersion, String agent, - String ignoreFilePath) throws IOException, CxException, InterruptedException { + String ignoreFilePath, boolean applySeverityThreshold) throws IOException, CxException, InterruptedException { com.checkmarx.ast.asca.ScanResult scanResult = null; try { - scanResult = wrapperProvider.scanAsca(path, ascaLatestVersion, agent, null); + scanResult = applySeverityThreshold + ? wrapperProvider.scanAsca(path, ascaLatestVersion, agent, null, + com.checkmarx.eclipse.devassist.utils.DevAssistUtils.getSeverityThreshold()) + : wrapperProvider.scanAsca(path, ascaLatestVersion, agent, null); } catch (IOException e) { CxLogger.warning(String.format("%s IOException occurred while ASCA scan for file %s: %s", LOG_TAG, path, e.getMessage())); } catch (InterruptedException e) { diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/containers/ContainerScannerService.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/containers/ContainerScannerService.java index 6a8bb52a..adea55f4 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/containers/ContainerScannerService.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/containers/ContainerScannerService.java @@ -159,7 +159,8 @@ public ScanResult scan(String filePath, IDocument doc ContainersRealtimeResults scanResults = null; try { - scanResults = wrapperProvider.containersRealtimeScan(tempFilePath.toString(), ignoreFilePath); + scanResults = wrapperProvider.containersRealtimeScan(tempFilePath.toString(), ignoreFilePath, + DevAssistUtils.getSeverityThreshold()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); @@ -194,6 +195,7 @@ private void updateIgnoredFileDataOnLatestResult(String tempFilePath, IProject p return; } CxLogger.info(LOG_TAG + " Performing full scan to update line numbers for ignored packages"); + // No severity threshold on purpose: ignore entries missing from these results get deleted. ContainersRealtimeResults fullScanResults = wrapperProvider.containersRealtimeScan(tempFilePath, ""); if (fullScanResults != null) { ContainerScanResultAdaptor fullScanResultAdaptor = diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/iac/IacScannerService.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/iac/IacScannerService.java index a8db03ef..6e5a1461 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/iac/IacScannerService.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/iac/IacScannerService.java @@ -151,7 +151,7 @@ public ScanResult scan(String filePath, IDocument document, IacRealtimeResults scanResults = null; try { scanResults = wrapperProvider - .iacRealtimeScan(tempFilePath, containerTool, ignoreFilePath); + .iacRealtimeScan(tempFilePath, containerTool, ignoreFilePath, DevAssistUtils.getSeverityThreshold()); } catch (Exception e) { // TODO Auto-generated catch block CxLogger.warning(String.format("%s Exception occurred while IAC scan for file %s: %s", LOG_TAG, filePath, e.getMessage())); @@ -206,6 +206,7 @@ private void updateIgnoredFileDataOnLatestResult(String tempFilePath, IProject p return; } CxLogger.info(LOG_TAG + " Performing full scan to update line numbers for ignored IaC issues"); + // No severity threshold on purpose: ignore entries missing from these results get deleted. IacRealtimeResults fullScanResults = wrapperProvider.iacRealtimeScan(tempFilePath, containerTool, ""); if (fullScanResults != null) { IacScanResultAdaptor fullScanResultAdaptor = new IacScanResultAdaptor(fullScanResults, filePath); diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/oss/OssScannerService.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/oss/OssScannerService.java index e7e43766..740076e0 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/oss/OssScannerService.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/oss/OssScannerService.java @@ -125,7 +125,8 @@ public ScanResult scanWithDocument(String filePath, IDocumen CxLogger.info(LOG_TAG + " Starting Realtime OSS Scan on File: " + filePath); String ignoreFilePath = com.checkmarx.eclipse.devassist.utils.DevAssistUtils.getIgnoreFilePath(project); - OssRealtimeResults scanResults = wrapperProvider.ossRealtimeScan(mainTempPath.get(), ignoreFilePath); + OssRealtimeResults scanResults = wrapperProvider.ossRealtimeScan(mainTempPath.get(), ignoreFilePath, + com.checkmarx.eclipse.devassist.utils.DevAssistUtils.getSeverityThreshold()); if (scanResults == null) { return null; } @@ -160,6 +161,7 @@ private void updateIgnoredFileDataOnLatestResult(String tempFilePath, String fil return; } CxLogger.info(LOG_TAG + " Performing full scan to update line numbers for ignored packages"); + // No severity threshold on purpose: ignore entries missing from these results get deleted. OssRealtimeResults fullScanResults = wrapperProvider.ossRealtimeScan(tempFilePath, ""); if (fullScanResults != null && fullScanResults.getPackages() != null) { OssScanResultAdaptor fullScanResultAdaptor = new OssScanResultAdaptor(fullScanResults, filePath); diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/secrets/SecretsScannerService.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/secrets/SecretsScannerService.java index 8dfa17ec..aaf40344 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/secrets/SecretsScannerService.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/scanners/secrets/SecretsScannerService.java @@ -136,7 +136,7 @@ public ScanResult scan(String filePath, IDocument docume String ignoreFilePath = DevAssistUtils.getIgnoreFilePath(proj); SecretsRealtimeResults scanResults = wrapperProvider - .secretsRealtimeScan(tempFilePath.get(), ignoreFilePath); + .secretsRealtimeScan(tempFilePath.get(), ignoreFilePath, DevAssistUtils.getSeverityThreshold()); if (scanResults == null) { CxLogger.warning(LOG_TAG + " Secrets scanner: no results returned - " + filePath); @@ -187,6 +187,7 @@ private void updateIgnoredFileDataOnLatestResult(String tempFilePath, IProject p return; } CxLogger.info(LOG_TAG + " Performing full scan to update line numbers for ignored secrets"); + // No severity threshold on purpose: ignore entries missing from these results get deleted. SecretsRealtimeResults fullScanResults = wrapperProvider.secretsRealtimeScan(tempFilePath, ""); if (fullScanResults != null) { SecretsScanResultAdaptor fullScanResultAdaptor = new SecretsScanResultAdaptor(fullScanResults, filePath); diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/ignore/DevAssistIgnoredFindings.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/ignore/DevAssistIgnoredFindings.java index 0371ef05..bde9b6f1 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/ignore/DevAssistIgnoredFindings.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/ignore/DevAssistIgnoredFindings.java @@ -504,6 +504,10 @@ public void refreshTable() { entries = ignoreFileManager.getIgnoreData().entrySet().stream() .filter(e -> activeFileCount(e.getValue()) > 0) .filter(e -> e.getValue().getSeverity() == null || filterState.hasFilter(e.getValue().getSeverity())) + // Severity threshold: UI-only. Entries below it are hidden but stay in the ignore file, + // so they reappear when the threshold is lowered. Malicious entries and entries with a + // missing/unknown severity are always shown. + .filter(e -> Preferences.getSeverityThreshold().includes(e.getValue().getSeverity())) .collect(Collectors.toList()); } diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/utils/DevAssistUtils.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/utils/DevAssistUtils.java index 9b783f5e..5b93c0be 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/utils/DevAssistUtils.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/utils/DevAssistUtils.java @@ -484,4 +484,18 @@ public static String getContainerTool() { return "docker"; // default to docker if preference retrieval fails } } + + /** + * Returns the Dev Assist severity threshold as the lower-case value the CLI expects for + * {@code --severity-threshold} (critical, high, medium, low, info). Defaults to "high" + * when the setting is missing or invalid. + */ + public static String getSeverityThreshold() { + try { + return Preferences.getSeverityThreshold().getCliValue(); + } catch (Exception e) { + CxLogger.error(LOG_TAG + " Error retrieving severity threshold preference: " + e.getMessage(), e); + return com.checkmarx.eclipse.common.preferences.SeverityThreshold.DEFAULT.getCliValue(); + } + } }