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/telemetry/TelemetryServiceTest.java b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/devassist/telemetry/TelemetryServiceTest.java new file mode 100644 index 00000000..018ce34b --- /dev/null +++ b/checkmarx-ast-eclipse-plugin-tests/src/test/java/checkmarx/ast/eclipse/plugin/tests/unit/devassist/telemetry/TelemetryServiceTest.java @@ -0,0 +1,163 @@ +package checkmarx.ast.eclipse.plugin.tests.unit.devassist.telemetry; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; + +import java.util.Arrays; +import java.util.Collections; + +import org.junit.jupiter.api.Test; + +import com.checkmarx.ast.telemetry.TelemetryEvent; +import com.checkmarx.eclipse.devassist.telemetry.TelemetryService; + +/** + * Verifies the telemetry events built for login, scan and remediation (AST-184122). + */ +class TelemetryServiceTest { + + private static void assertCommonFields(TelemetryEvent event) { + assertEquals("Eclipse", event.getAgent()); + assertEquals("IDE", event.getPluginType()); + assertFalse(event.getCxPluginVersion() == null || event.getCxPluginVersion().isEmpty()); + assertEquals("DevAssist", event.getEventAttributes().get("pluginName")); + } + + @Test + void loginSuccess() { + TelemetryEvent event = TelemetryService.buildLoginEvent(true, null); + + assertCommonFields(event); + assertEquals("authentication", event.getEventType()); + assertEquals("authentication", event.getSubType()); + assertEquals("success", event.getStatus()); + assertEquals("Authentication successful.", event.getStatusResult()); + assertEquals("APIKey", event.getEventAttributes().get("authMethod")); + assertFalse(event.getEventAttributes().get("loginTimestamp").isEmpty()); + java.time.Instant.parse(event.getEventAttributes().get("loginTimestamp")); + } + + @Test + void installEventCarriesIdAndTimestamp() { + TelemetryEvent event = TelemetryService.buildInstallEvent("eclipse-1234", "2026-11-19T08:00:00Z"); + + assertCommonFields(event); + assertEquals("install", event.getEventType()); + assertEquals("installation", event.getSubType()); + assertEquals("success", event.getStatus()); + assertEquals("Plugin installed successfully.", event.getStatusResult()); + assertEquals("eclipse-1234", event.getEventAttributes().get("installationId")); + assertEquals("2026-11-19T08:00:00Z", event.getEventAttributes().get("installationTimestamp")); + } + + @Test + void loginFailureCarriesSanitizedReason() { + TelemetryEvent event = TelemetryService.buildLoginEvent(false, "bad key apikey=abc123 expired"); + + assertEquals("failure", event.getStatus()); + assertEquals("Authentication failed. Reason: bad key apikey=*** expired, Error Code: N/A", + event.getStatusResult()); + } + + @Test + void scanEventCountsSeveritiesAndReportsHighest() { + TelemetryEvent event = TelemetryService.buildScanEvent("Oss", + Arrays.asList("High", "High", "Medium", "Malicious", "Unknown", "OK", null)); + + assertCommonFields(event); + assertEquals("Scan", event.getEventType()); + assertEquals("scantriggerd", event.getSubType()); + assertEquals("success", event.getStatus()); + assertEquals("Oss", event.getEngine()); + assertEquals("Critical", event.getProblemSeverity()); + assertEquals(Integer.valueOf(6), event.getTotalCount()); + assertEquals("Critical=1, High=2, Medium=1, Low=0, Info=2", event.getStatusResult()); + assertEquals("v2", event.getApiVersion()); + assertEquals("v2", event.getEventAttributes().get("apiVersion")); + } + + @Test + void scanWithoutFindingsIsStillReported() { + TelemetryEvent event = TelemetryService.buildScanEvent("Secrets", Collections.emptyList()); + + assertEquals("success", event.getStatus()); + assertEquals("", event.getProblemSeverity()); + assertEquals(Integer.valueOf(0), event.getTotalCount()); + assertEquals("Critical=0, High=0, Medium=0, Low=0, Info=0", event.getStatusResult()); + } + + @Test + void scanFailure() { + TelemetryEvent event = TelemetryService.buildScanFailureEvent("IaC", "boom"); + + assertEquals("Scan", event.getEventType()); + assertEquals("failure", event.getStatus()); + assertEquals("IaC", event.getEngine()); + assertEquals("Scan failed. Reason: boom, Error Code: N/A", event.getStatusResult()); + } + + @Test + void remediationEventHasModeAndVulnerabilityId() { + TelemetryEvent event = TelemetryService.buildClickEvent("Click", "fixWithAIChat", "Oss", "High", + "CVE-2024-1", "success", ""); + + assertCommonFields(event); + assertEquals("Click", event.getEventType()); + assertEquals("fixWithAIChat", event.getSubType()); + assertEquals("Copilot", event.getAiProvider()); + assertEquals("Oss", event.getEngine()); + assertEquals("High", event.getProblemSeverity()); + assertEquals("DevAssist", event.getEventAttributes().get("remediationMode")); + assertEquals("CVE-2024-1", event.getEventAttributes().get("vulnerabilityId")); + assertEquals("Remediation completed successfully.", event.getStatusResult()); + } + + @Test + void clickEventAndScanEventCarryRepoUrl() { + assertEquals("https://github.com/org/repo", TelemetryService.buildClickEvent("click", "fixWithAIChat", "Oss", + "High", "x@1", "success", "", "https://github.com/org/repo").getRepoUrl()); + assertEquals("https://github.com/org/repo", TelemetryService.buildScanEvent("Oss", Collections.emptyList(), + "https://github.com/org/repo").getRepoUrl()); + } + + @Test + void gitRemoteResolverReadsOriginAndStripsCredentials(@org.junit.jupiter.api.io.TempDir java.nio.file.Path dir) + throws java.io.IOException { + java.nio.file.Path git = java.nio.file.Files.createDirectories(dir.resolve(".git")); + java.nio.file.Files.write(git.resolve("config"), Arrays.asList("[core]", " bare = false", + "[remote \"upstream\"]", " url = https://github.com/other/repo.git", + "[remote \"origin\"]", " url = https://user:tok@github.com/org/repo.git")); + java.nio.file.Path file = java.nio.file.Files.createDirectories(dir.resolve("src")).resolve("a.java"); + + assertEquals("https://github.com/org/repo.git", + com.checkmarx.eclipse.devassist.telemetry.GitRemoteResolver.resolve(file.toString())); + assertNull(com.checkmarx.eclipse.devassist.telemetry.GitRemoteResolver.resolve(null)); + } + + @Test + void remediationEventOmitsBlankVulnerabilityId() { + TelemetryEvent event = TelemetryService.buildClickEvent("Click", "fixWithAIChat", "Secrets", "High", " ", + "failure", "Remediation failed. Reason: x, Error Code: N/A"); + + assertFalse(event.getEventAttributes().containsKey("vulnerabilityId")); + assertEquals("failure", event.getStatus()); + } + + @Test + void otherClickEventsHaveNoRemediationAttributes() { + TelemetryEvent event = TelemetryService.buildClickEvent("Click", "viewDetails", "Oss", "Low", "CVE-1", + "success", ""); + + assertFalse(event.getEventAttributes().containsKey("remediationMode")); + assertFalse(event.getEventAttributes().containsKey("vulnerabilityId")); + assertNull(event.getApiVersion()); + } + + @Test + void sanitizeRemovesCredentialsAndTruncates() { + assertEquals("https://***@host/x", TelemetryService.sanitize("https://user:pw@host/x")); + assertEquals("Bearer ***", TelemetryService.sanitize("Bearer abc.def")); + assertEquals(256, TelemetryService.sanitize("a ".repeat(400)).length()); + } +} 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/checkmarx-ast-eclipse-plugin/src/com/checkmarx/eclipse/startup/PluginStartup.java b/checkmarx-ast-eclipse-plugin/src/com/checkmarx/eclipse/startup/PluginStartup.java index 90c8a271..d5df15f7 100644 --- a/checkmarx-ast-eclipse-plugin/src/com/checkmarx/eclipse/startup/PluginStartup.java +++ b/checkmarx-ast-eclipse-plugin/src/com/checkmarx/eclipse/startup/PluginStartup.java @@ -12,6 +12,7 @@ import com.checkmarx.eclipse.devassist.backend.listener.CheckmarxEditorListener; import com.checkmarx.eclipse.devassist.backend.GlobalScannerController; import com.checkmarx.eclipse.devassist.backend.listener.ProjectLifecycleListener; +import com.checkmarx.eclipse.devassist.telemetry.TelemetryService; public class PluginStartup implements IStartup { @@ -48,6 +49,10 @@ public void earlyStartup() { realtimeScanListener = new CheckmarxEditorListener(); window.getPartService().addPartListener(realtimeScanListener); + // Report login for an already logged-in user (once per launch), queued ahead of + // every scan event the scanners below will produce. + TelemetryService.logStartupLoginEvent(); + // Initialize backend scanner infrastructure initializeBackendScanners(); } 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..2bec8728 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, @@ -39,6 +39,7 @@ Export-Package: com.checkmarx.ast.asca, com.checkmarx.ast.results.result, com.checkmarx.ast.scan, com.checkmarx.ast.secretsrealtime, + com.checkmarx.ast.telemetry, com.checkmarx.ast.tenant, com.checkmarx.ast.utils, com.checkmarx.ast.wrapper, 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..3f0e2721 --- /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:fc8cdc828fe09e4e4f59d71a4a049d97bb3152138bedbc50695204c35fe609e0 +size 141725712 diff --git a/common-lib/src/com/checkmarx/eclipse/common/listener/ILoginTelemetryHandler.java b/common-lib/src/com/checkmarx/eclipse/common/listener/ILoginTelemetryHandler.java new file mode 100644 index 00000000..556d09a1 --- /dev/null +++ b/common-lib/src/com/checkmarx/eclipse/common/listener/ILoginTelemetryHandler.java @@ -0,0 +1,18 @@ +package com.checkmarx.eclipse.common.listener; + +/** + * Handler for login telemetry events (AST-184122). + * + * Allows devassist-lib to report an authentication result from PreferencesPage + * without creating a reverse dependency from common-lib to devassist-lib. + */ +public interface ILoginTelemetryHandler { + + /** + * Called with the result of an API key authentication attempt. + * + * @param success true if authentication succeeded + * @param failureReason reason for a failed attempt (may be null on success) + */ + void onLogin(boolean success, String failureReason); +} 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..98fa07b0 100644 --- a/common-lib/src/com/checkmarx/eclipse/common/preferences/Preferences.java +++ b/common-lib/src/com/checkmarx/eclipse/common/preferences/Preferences.java @@ -11,6 +11,7 @@ import org.eclipse.ui.preferences.ScopedPreferenceStore; import com.checkmarx.eclipse.common.listener.IAuthenticationSuccessHandler; +import com.checkmarx.eclipse.common.listener.ILoginTelemetryHandler; import com.checkmarx.eclipse.common.listener.IMcpInstallHandler; import com.checkmarx.eclipse.common.listener.IMcpUninstallHandler; import com.checkmarx.eclipse.common.listener.ISettingsChangeNotifier; @@ -47,6 +48,9 @@ public class Preferences { // Handler for post-authentication UI setup (registered by devassist-lib) private static IAuthenticationSuccessHandler authSuccessHandler; + // Handler that reports login telemetry (registered by devassist-lib) + private static ILoginTelemetryHandler loginTelemetryHandler; + // Notifiers for settings changes (registered by main plugin and devassist-lib). // A List is used because both bundles register their own notifier for different // purposes (UI panel refresh vs. scanner-state sync); a single-slot field would @@ -104,6 +108,14 @@ public static void setAuthenticationSuccessHandler(IAuthenticationSuccessHandler authSuccessHandler = handler; } + public static void setLoginTelemetryHandler(ILoginTelemetryHandler handler) { + loginTelemetryHandler = handler; + } + + public static ILoginTelemetryHandler getLoginTelemetryHandler() { + return loginTelemetryHandler; + } + public static IAuthenticationSuccessHandler getAuthenticationSuccessHandler() { return authSuccessHandler; } diff --git a/common-lib/src/com/checkmarx/eclipse/common/preferences/PreferencesPage.java b/common-lib/src/com/checkmarx/eclipse/common/preferences/PreferencesPage.java index d272318e..be0080b1 100644 --- a/common-lib/src/com/checkmarx/eclipse/common/preferences/PreferencesPage.java +++ b/common-lib/src/com/checkmarx/eclipse/common/preferences/PreferencesPage.java @@ -30,6 +30,7 @@ import com.checkmarx.eclipse.common.utils.PluginConstants; import com.checkmarx.eclipse.common.listener.IAuthenticationSuccessHandler; +import com.checkmarx.eclipse.common.listener.ILoginTelemetryHandler; import com.checkmarx.eclipse.common.listener.IMcpUninstallCallback; import com.checkmarx.eclipse.common.listener.IMcpUninstallHandler; import com.checkmarx.eclipse.common.listener.ISettingsChangeNotifier; @@ -315,6 +316,10 @@ public void widgetSelected(SelectionEvent e) { // anything else gated on login) actually sees it. Preferences.STORE.setValue(Preferences.API_KEY, apiKey_str); Preferences.STORE.setValue(Preferences.ADDITIONAL_OPTIONS, additionalParams_str); + // Report the login BEFORE credentialsValidated flips: that change starts a + // workspace scan immediately, and the login event must reach the CLI first + // (it creates the session id the scan events reuse). + reportLoginTelemetry(true, null); Preferences.setCredentialsValidated(true); // connectionButton stays disabled - it's only re-enabled on logout, or // below if this attempt actually failed. @@ -335,6 +340,7 @@ public void widgetSelected(SelectionEvent e) { // Authentication failed - the flow ends here with no welcome dialog, // so show the failure message right away, restore Logout, and let the // user retry the connect. + reportLoginTelemetry(false, result); if (!connectionButton.isDisposed()) { connectionButton.setEnabled(true); } @@ -429,6 +435,21 @@ public void widgetSelected(SelectionEvent e) { }); } + /** + * Reports the result of a Connect attempt to the login telemetry handler + * (registered by devassist-lib). Never throws - telemetry must not affect login. + */ + private static void reportLoginTelemetry(boolean success, String failureReason) { + try { + ILoginTelemetryHandler handler = Preferences.getLoginTelemetryHandler(); + if (handler != null) { + handler.onLogin(success, failureReason); + } + } catch (Exception e) { + CxLogger.warning("Telemetry: login event could not be reported - " + e.getMessage()); + } + } + private static String mapAuthResult(String result) { if (result != null && result.contains(PluginConstants.AUTH_SUCCESS_PATTERN)) { return PluginConstants.AUTH_SUCCESS_DISPLAY; diff --git a/common-lib/src/com/checkmarx/eclipse/common/wrapper/CxWrapperFactory.java b/common-lib/src/com/checkmarx/eclipse/common/wrapper/CxWrapperFactory.java index 461094ef..41ad82e5 100644 --- a/common-lib/src/com/checkmarx/eclipse/common/wrapper/CxWrapperFactory.java +++ b/common-lib/src/com/checkmarx/eclipse/common/wrapper/CxWrapperFactory.java @@ -77,7 +77,7 @@ private static String getAgentInfo() { * build (Tycho replaces the "qualifier" placeholder in MANIFEST.MF with the * real build qualifier), falling back when running outside an OSGi framework. */ - private static String getPluginVersion() { + public static String getPluginVersion() { try { Bundle bundle = FrameworkUtil.getBundle(CxWrapperFactory.class); return bundle != null ? bundle.getVersion().toString() : "0.0.0"; 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..2ac35d2d 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.telemetry, com.checkmarx.eclipse.devassist.ui.findings.ignore diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/common/ScanManager.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/common/ScanManager.java index 4c5f8534..07b1a452 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/common/ScanManager.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/common/ScanManager.java @@ -9,7 +9,9 @@ import com.checkmarx.eclipse.devassist.backend.ScannerRegistry; import com.checkmarx.eclipse.devassist.backend.ScannerRegistry.ScannerType; import com.checkmarx.eclipse.devassist.basescanner.ScannerService; +import com.checkmarx.eclipse.devassist.model.ScanEngine; import com.checkmarx.eclipse.devassist.model.ScanIssue; +import com.checkmarx.eclipse.devassist.telemetry.TelemetryService; import com.checkmarx.eclipse.common.utils.CxLogger; /** @@ -160,8 +162,13 @@ public ScanOutcome scanFileWithOutcome(String filePath, IProgressMonitor monitor allIssues.addAll(scannerResults); } successfulScanners++; + // One scan event per engine scan (a null result means the engine did not run) + if (scanResult != null) { + reportScanTelemetry(scanner, scannerResults, filePath); + } } catch (Exception e) { e.printStackTrace(); + reportScanFailureTelemetry(scanner, e, filePath); } } @@ -187,6 +194,44 @@ public ScanOutcome scanFileWithOutcome(String filePath, IProgressMonitor monitor } } + /** Resolves the scan engine of a scanner from its config; null if unknown. */ + private static ScanEngine engineOf(ScannerService scanner) { + try { + return ScanEngine.fromString(scanner.getConfig().getEngineName()); + } catch (Exception e) { + return null; + } + } + + private static void reportScanTelemetry(ScannerService scanner, List issues, String filePath) { + try { + ScanEngine engine = engineOf(scanner); + if (engine == null) { + return; + } + List severities = new ArrayList<>(); + if (issues != null) { + for (ScanIssue issue : issues) { + severities.add(issue.getSeverity()); + } + } + TelemetryService.logScanEvent(engine, severities, filePath); + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Scan telemetry failed: " + e.getMessage()); + } + } + + private static void reportScanFailureTelemetry(ScannerService scanner, Exception failure, String filePath) { + try { + ScanEngine engine = engineOf(scanner); + if (engine != null) { + TelemetryService.logScanFailureEvent(engine, failure.getMessage(), filePath); + } + } catch (Exception e) { + CxLogger.warning(LOG_TAG + " Scan telemetry failed: " + e.getMessage()); + } + } + /** * Scan a file using all applicable scanners. * diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/configuration/McpInstallService.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/configuration/McpInstallService.java index a1537700..9f4ddccf 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/configuration/McpInstallService.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/configuration/McpInstallService.java @@ -48,6 +48,11 @@ private static void registerAuthenticationHandlers() { // Register handler for post-authentication UI (welcome dialog, workspace scan) Preferences.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler()); + // Register handler so common-lib PreferencesPage can report login telemetry + // without depending on this bundle directly. + Preferences.setLoginTelemetryHandler( + com.checkmarx.eclipse.devassist.telemetry.TelemetryService::logLoginEvent); + // Register handler so common-lib preference pages (e.g. // CheckmarxPreferencePage) // can trigger MCP install without depending on this bundle directly. diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/remediation/RemediationLinkHandler.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/remediation/RemediationLinkHandler.java index 45c676e8..206b7f60 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/remediation/RemediationLinkHandler.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/remediation/RemediationLinkHandler.java @@ -137,7 +137,12 @@ public boolean handleLink(@NonNull String link) { private boolean handleActions(@NonNull String action, @NonNull ScanIssue scanIssue, @NonNull String actionId) { switch (action) { case FIX: - remediationManager.fixWithCxOneAssist(scanIssue, actionId); + try { + remediationManager.fixWithCxOneAssist(scanIssue, actionId); + } catch (RuntimeException e) { + TelemetryService.logFixWithCxOneAssistFailure(scanIssue, e.getMessage()); + throw e; + } TelemetryService.logFixWithCxOneAssistAction(scanIssue); break; case VIEW_DETAILS: diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/telemetry/GitRemoteResolver.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/telemetry/GitRemoteResolver.java new file mode 100644 index 00000000..2a20932d --- /dev/null +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/telemetry/GitRemoteResolver.java @@ -0,0 +1,81 @@ +package com.checkmarx.eclipse.devassist.telemetry; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Finds the git remote URL of the repository that contains a file, for the + * {@code repoUrl} telemetry field (scan and remediation events). Reads + * {@code .git/config} directly - no git process is started - and never throws. + * Credentials embedded in the URL are removed. Returns {@code null} when the file + * is not in a git repository or has no remote. + */ +public final class GitRemoteResolver { + + private static final Pattern REMOTE_SECTION = Pattern.compile("^\\[remote\\s+\"([^\"]+)\"\\]$"); + private static final Pattern URL_LINE = Pattern.compile("^url\\s*=\\s*(.+)$"); + + private GitRemoteResolver() { + } + + public static String resolve(String filePath) { + try { + if (filePath == null || filePath.trim().isEmpty()) { + return null; + } + Path dir = Paths.get(filePath).toAbsolutePath().getParent(); + while (dir != null) { + Path config = dir.resolve(".git").resolve("config"); + if (Files.isRegularFile(config)) { + return stripCredentials(readRemoteUrl(Files.readAllLines(config, StandardCharsets.UTF_8))); + } + dir = dir.getParent(); + } + } catch (IOException | RuntimeException e) { + // best effort only + } + return null; + } + + /** Picks the "origin" remote, or the first remote that has a URL. */ + static String readRemoteUrl(List configLines) { + String current = null; + String first = null; + for (String raw : configLines) { + String line = raw.trim(); + Matcher section = REMOTE_SECTION.matcher(line); + if (section.matches()) { + current = section.group(1); + continue; + } + if (line.startsWith("[")) { + current = null; + continue; + } + Matcher url = URL_LINE.matcher(line); + if (current != null && url.matches()) { + if ("origin".equals(current)) { + return url.group(1).trim(); + } + if (first == null) { + first = url.group(1).trim(); + } + } + } + return first; + } + + /** {@code https://user:token@host/x} becomes {@code https://host/x}. */ + static String stripCredentials(String url) { + if (url == null || url.trim().isEmpty()) { + return null; + } + return url.trim().replaceFirst("(?i)^([a-z][a-z0-9+.-]*://)[^/@]+@", "$1"); + } +} diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/telemetry/TelemetryService.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/telemetry/TelemetryService.java index 536e78f8..e792995a 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/telemetry/TelemetryService.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/telemetry/TelemetryService.java @@ -1,11 +1,20 @@ package com.checkmarx.eclipse.devassist.telemetry; +import java.time.Instant; +import java.util.List; import java.util.Objects; -import java.util.concurrent.CompletableFuture; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; import org.eclipse.core.runtime.Platform; +import com.checkmarx.ast.telemetry.TelemetryEvent; +import com.checkmarx.eclipse.common.preferences.Preferences; +import com.checkmarx.eclipse.common.runner.Authenticator; import com.checkmarx.eclipse.common.utils.CxLogger; +import com.checkmarx.eclipse.common.utils.PluginConstants; import com.checkmarx.eclipse.common.wrapper.CxWrapperFactory; import com.checkmarx.eclipse.devassist.backend.Constants; import com.checkmarx.eclipse.devassist.model.ScanEngine; @@ -14,25 +23,60 @@ import static java.lang.String.format; /** - * Telemetry service for logging user interactions with remediation actions - * (Fix with CxOne Assist, View Details, Ignore, Ignore All). - * Mirrors the JetBrains plugin's TelemetryService: every event is sent - * asynchronously via the Checkmarx CLI wrapper's telemetryAIEvent, and a - * failure to send is only logged - it never surfaces to the user or blocks - * the action being reported on. + * Telemetry service for the Dev Assist analytics events (AST-184122): login, + * scan and remediation/click events. + * Every event is sent asynchronously via the Checkmarx CLI wrapper's + * telemetryAIEvent, and a failure to send is only logged - it never surfaces to + * the user or blocks the action being reported on. */ public final class TelemetryService { // AI Provider constant private static final String AI_PROVIDER = "Copilot"; - // Agent name base, matching JetBrains' "Jetbrains " pattern + // Sent as the per-event agent (version goes in agentVersion). The agent name used + // for every other CLI call (CxConfig.agentName) is left unchanged. private static final String ECLIPSE_AGENT_NAME = "Eclipse"; // Event Types + // Lowercase, like the VS Code plugin and the design doc's type list private static final String EVENT_TYPE_CLICK = "click"; + private static final String STATUS_RESULT_REMEDIATION_SUCCESS = "Remediation completed successfully."; + private static final String EVENT_TYPE_AUTH = "authentication"; + private static final String EVENT_TYPE_SCAN = "Scan"; + + // Common values + private static final String PLUGIN_TYPE = "IDE"; + private static final String API_VERSION = "v2"; + // Value used by the VS Code plugin and the design doc (APIKey | OAuth) + private static final String AUTH_METHOD_API_KEY = "APIKey"; + private static final String STATUS_RESULT_AUTH_SUCCESS = "Authentication successful."; + private static final String STATUS_RESULT_INSTALL_SUCCESS = "Plugin installed successfully."; + private static final String EVENT_TYPE_INSTALL = "install"; + private static final String SUB_TYPE_INSTALL = "installation"; + private static final String PREF_INSTALLATION_ID = "devassist.telemetry.installationId"; + private static final String PREF_PENDING_INSTALL_TIMESTAMP = "devassist.telemetry.pendingInstallTimestamp"; + private static final String ATTR_LOGIN_TIMESTAMP = "loginTimestamp"; + private static final String ATTR_INSTALLATION_ID = "installationId"; + private static final String ATTR_INSTALLATION_TIMESTAMP = "installationTimestamp"; + private static final String REMEDIATION_MODE = "DevAssist"; + // Sent on every event so Analytics can tell the Checkmarx One and Dev Assist plugins apart + private static final String PLUGIN_NAME_DEV_ASSIST = "DevAssist"; + private static final String STATUS_SUCCESS = "success"; + private static final String STATUS_FAILURE = "failure"; + private static final int MAX_STATUS_RESULT_LENGTH = 256; + + // Event attribute keys + private static final String ATTR_PLUGIN_NAME = "pluginName"; + private static final String ATTR_API_VERSION = "apiVersion"; + private static final String ATTR_AUTH_METHOD = "authMethod"; + private static final String ATTR_VULNERABILITY_ID = "vulnerabilityId"; + private static final String ATTR_REMEDIATION_MODE = "remediationMode"; // Sub Types + private static final String SUB_TYPE_AUTH = "authentication"; + // Spelling taken from the design's routing table (AST-184122, open question 3) + private static final String SUB_TYPE_SCAN = "scantriggerd"; private static final String SUB_TYPE_FIX_WITH_AI_CHAT = "fixWithAIChat"; private static final String SUB_TYPE_VIEW_DETAILS = "viewDetails"; private static final String SUB_TYPE_IGNORE_PACKAGE = "ignorePackage"; @@ -45,35 +89,370 @@ public final class TelemetryService { private static final String ENGINE_ASCA = "Asca"; private static final String ENGINE_CONTAINERS = "Containers"; + private static final String[] SEVERITY_LABELS = { "Critical", "High", "Medium", "Low", "Info" }; + + /** + * All events go through one single-thread executor so they reach the CLI in the + * order they were enqueued (the CLI creates the session id on the login event, + * which must come before any scan/remediation event). Daemon thread: it never + * blocks IDE shutdown. + */ + private static final ExecutorService SENDER = Executors.newSingleThreadExecutor(r -> { + Thread t = new Thread(r, "cx-telemetry-sender"); + t.setDaemon(true); + return t; + }); + private TelemetryService() { } /** - * Sends a user-action ("click") telemetry event. + * Sends a user-action ("Click") telemetry event with success status. * - * @param eventType the type of event (e.g., "click") + * @param eventType the type of event (e.g., "Click") * @param subType the specific action (e.g., "fixWithAIChat", "viewDetails") * @param engine the scan engine type * @param problemSeverity the severity of the issue */ public static void setUserEventDataForLogs(String eventType, String subType, String engine, String problemSeverity) { - CompletableFuture.runAsync(() -> { - try { - CxWrapperFactory.build().telemetryAIEvent( - AI_PROVIDER, // aiProvider - getAgentName(), // agent - eventType, // eventType - subType, // subType - engine, // engine - problemSeverity, // problemSeverity - "", // scanType - "", // status - 0 // totalCount - ); - } catch (Exception e) { - CxLogger.warning(format("Telemetry: Failed to log user event telemetry for %s - %s", subType, e.getMessage())); + send(buildClickEvent(eventType, subType, engine, problemSeverity, null, STATUS_SUCCESS, "")); + } + + /** + * Enqueues the event; sending is asynchronous and a failure is only logged. + */ + private static void send(TelemetryEvent event) { + try { + SENDER.execute(() -> sendNow(event)); + } catch (Exception e) { + CxLogger.warning(format("Telemetry: Could not enqueue event - %s", e.getMessage())); + } + } + + /** Sends the event on the calling (sender) thread; a failure is only logged. */ + private static void sendNow(TelemetryEvent event) { + try { + CxWrapperFactory.build().telemetryAIEvent(event); + } catch (Exception e) { + CxLogger.warning(format("Telemetry: Failed to send %s/%s event - %s", event.getEventType(), + event.getSubType(), e.getMessage())); + } + } + + private static final AtomicBoolean STARTUP_LOGIN_SENT = new AtomicBoolean(false); + + /** + * Sends one login event per Eclipse launch for a user who is already logged in + * (the login flag is persisted and never re-validated at startup). The stored + * credentials are validated on the sender thread - so no UI blocking, and every + * later scan/remediation event is queued behind this login - and the event reports + * the real result. The stored {@code credentialsValidated} flag is not changed. + */ + public static void logStartupLoginEvent() { + ensureInstallation(); + if (!Preferences.isAuthenticated() || !STARTUP_LOGIN_SENT.compareAndSet(false, true)) { + return; + } + try { + SENDER.execute(() -> { + String result = Authenticator.INSTANCE.doAuthentication(Preferences.getApiKey(), + Preferences.getAdditionalOptions()); + boolean success = result != null && result.contains(PluginConstants.AUTH_SUCCESS_PATTERN); + sendNow(buildLoginEvent(success, success ? null : result)); + if (success) { + flushPendingInstallEvent(); + } + }); + } catch (Exception e) { + CxLogger.warning(format("Telemetry: Could not enqueue startup login event - %s", e.getMessage())); + } + } + + private static TelemetryEvent.TelemetryEventBuilder baseEvent(String eventType, String subType, String status, + String statusResult) { + return TelemetryEvent.builder() + .eventType(eventType) + .subType(subType) + .status(status) + .statusResult(statusResult) + .agent(ECLIPSE_AGENT_NAME) + .agentVersion(getAgentVersion()) + .cxPluginVersion(CxWrapperFactory.getPluginVersion()) + .pluginType(PLUGIN_TYPE) + .eventAttribute(ATTR_PLUGIN_NAME, PLUGIN_NAME_DEV_ASSIST); + } + + /** + * Builds a click/remediation event. For "fixWithAIChat" the remediation mode and + * (when not blank) the vulnerability id are added as event attributes. + */ + public static TelemetryEvent buildClickEvent(String eventType, String subType, String engine, + String problemSeverity, String vulnerabilityId, String status, String statusResult) { + return buildClickEvent(eventType, subType, engine, problemSeverity, vulnerabilityId, status, statusResult, + null); + } + + /** Same as above, with the repository URL of the file the finding is in (may be null). */ + public static TelemetryEvent buildClickEvent(String eventType, String subType, String engine, + String problemSeverity, String vulnerabilityId, String status, String statusResult, String repoUrl) { + boolean remediation = SUB_TYPE_FIX_WITH_AI_CHAT.equals(subType); + String result = remediation && STATUS_SUCCESS.equals(status) + && (statusResult == null || statusResult.isEmpty()) ? STATUS_RESULT_REMEDIATION_SUCCESS : statusResult; + TelemetryEvent.TelemetryEventBuilder builder = baseEvent(eventType, subType, status, result) + .aiProvider(AI_PROVIDER) + .engine(engine) + .problemSeverity(problemSeverity) + .repoUrl(repoUrl); + if (remediation) { + builder.eventAttribute(ATTR_REMEDIATION_MODE, REMEDIATION_MODE); + if (vulnerabilityId != null && !vulnerabilityId.trim().isEmpty()) { + builder.eventAttribute(ATTR_VULNERABILITY_ID, vulnerabilityId.trim()); + } + } + return builder.build(); + } + + /** + * Builds the login event. {@code failureReason} is used only when {@code success} is false. + * {@code loginTimestamp} is the time of the login (ISO-8601 UTC), like the VS Code plugin. + */ + public static TelemetryEvent buildLoginEvent(boolean success, String failureReason) { + return baseEvent(EVENT_TYPE_AUTH, SUB_TYPE_AUTH, success ? STATUS_SUCCESS : STATUS_FAILURE, + success ? STATUS_RESULT_AUTH_SUCCESS : failureStatusResult("Authentication failed", failureReason)) + .eventAttribute(ATTR_AUTH_METHOD, AUTH_METHOD_API_KEY) + .eventAttribute(ATTR_LOGIN_TIMESTAMP, Instant.now().toString()) + .build(); + } + + /** Builds the install event; {@code installationTimestamp} is when the plugin was first installed. */ + public static TelemetryEvent buildInstallEvent(String installationId, String installationTimestamp) { + return baseEvent(EVENT_TYPE_INSTALL, SUB_TYPE_INSTALL, STATUS_SUCCESS, STATUS_RESULT_INSTALL_SUCCESS) + .eventAttribute(ATTR_INSTALLATION_ID, installationId) + .eventAttribute(ATTR_INSTALLATION_TIMESTAMP, installationTimestamp) + .build(); + } + + /** + * Makes sure this Eclipse has an installation id ({@code eclipse-}). A brand new + * install (no id, never logged in, no API key) also gets a pending install event, sent + * after the first successful login. An upgrade of an existing install gets an id only, + * and no install event, like the VS Code plugin. + */ + public static synchronized void ensureInstallation() { + try { + String id = Preferences.STORE.getString(PREF_INSTALLATION_ID); + if (id != null && !id.trim().isEmpty()) { + return; + } + String apiKey = Preferences.getApiKey(); + boolean freshInstall = !Preferences.isAuthenticated() && (apiKey == null || apiKey.trim().isEmpty()); + Preferences.STORE.setValue(PREF_INSTALLATION_ID, "eclipse-" + UUID.randomUUID()); + if (freshInstall) { + Preferences.STORE.setValue(PREF_PENDING_INSTALL_TIMESTAMP, Instant.now().toString()); + } + if (Preferences.STORE.needsSaving()) { + Preferences.STORE.save(); + } + } catch (Exception e) { + CxLogger.warning(format("Telemetry: Could not create installation id - %s", e.getMessage())); + } + } + + /** + * Sends the pending install event, if there is one. Runs on the sender thread right + * after a successful login (the CLI needs the session id created by it). The pending + * marker is cleared only when the CLI call succeeded, so a failure is retried at the + * next successful login. + */ + private static synchronized void flushPendingInstallEvent() { + try { + String timestamp = Preferences.STORE.getString(PREF_PENDING_INSTALL_TIMESTAMP); + String id = Preferences.STORE.getString(PREF_INSTALLATION_ID); + if (timestamp == null || timestamp.trim().isEmpty() || id == null || id.trim().isEmpty()) { + return; + } + CxWrapperFactory.build().telemetryAIEvent(buildInstallEvent(id, timestamp)); + Preferences.STORE.setValue(PREF_PENDING_INSTALL_TIMESTAMP, ""); + if (Preferences.STORE.needsSaving()) { + Preferences.STORE.save(); + } + } catch (Exception e) { + CxLogger.warning(format("Telemetry: Install event not sent, will retry after the next login - %s", + e.getMessage())); + } + } + + /** + * Builds a successful scan event for one engine: severity counts in + * {@code statusResult}, highest severity in {@code problemSeverity}, total in + * {@code totalCount}. A scan without findings is reported too. + * + * @param engine telemetry engine name (Oss, Secrets, IaC, Asca, Containers) + * @param severities raw severity of every finding of this engine + */ + public static TelemetryEvent buildScanEvent(String engine, List severities) { + return buildScanEvent(engine, severities, null); + } + + /** Same as above, with the repository URL of the scanned file (may be null). */ + public static TelemetryEvent buildScanEvent(String engine, List severities, String repoUrl) { + int[] counts = new int[SEVERITY_LABELS.length]; + if (severities != null) { + for (String severity : severities) { + int index = severityIndex(severity); + if (index >= 0) { + counts[index]++; + } + } + } + int total = 0; + String highest = ""; + StringBuilder statusResult = new StringBuilder(); + for (int i = 0; i < SEVERITY_LABELS.length; i++) { + total += counts[i]; + if (highest.isEmpty() && counts[i] > 0) { + highest = SEVERITY_LABELS[i]; } - }); + if (i > 0) { + statusResult.append(", "); + } + statusResult.append(SEVERITY_LABELS[i]).append('=').append(counts[i]); + } + return baseEvent(EVENT_TYPE_SCAN, SUB_TYPE_SCAN, STATUS_SUCCESS, statusResult.toString()) + .engine(engine) + .problemSeverity(highest) + .totalCount(total) + .repoUrl(repoUrl) + .apiVersion(API_VERSION) + .eventAttribute(ATTR_API_VERSION, API_VERSION) + .build(); + } + + /** Builds a failed scan event for one engine. */ + public static TelemetryEvent buildScanFailureEvent(String engine, String failureReason) { + return buildScanFailureEvent(engine, failureReason, null); + } + + /** Same as above, with the repository URL of the scanned file (may be null). */ + public static TelemetryEvent buildScanFailureEvent(String engine, String failureReason, String repoUrl) { + return baseEvent(EVENT_TYPE_SCAN, SUB_TYPE_SCAN, STATUS_FAILURE, + failureStatusResult("Scan failed", failureReason)) + .engine(engine) + .repoUrl(repoUrl) + .apiVersion(API_VERSION) + .eventAttribute(ATTR_API_VERSION, API_VERSION) + .build(); + } + + /** + * Maps a finding severity to an index in {@link #SEVERITY_LABELS}. Malicious + * counts as Critical, anything unrecognised as Info, and "OK" is not a finding. + */ + private static int severityIndex(String severity) { + String raw = severity == null ? "unknown" : severity.trim().toLowerCase(); + switch (raw) { + case "critical": + case "malicious": + return 0; + case "high": + return 1; + case "medium": + return 2; + case "low": + return 3; + case "ok": + return -1; + default: + return 4; + } + } + + private static String failureStatusResult(String prefix, String reason) { + return prefix + ". Reason: " + sanitize(reason == null || reason.trim().isEmpty() ? "unknown" : reason) + + ", Error Code: N/A"; + } + + /** + * Removes anything that looks like a credential from free text, collapses + * whitespace and truncates it. + */ + public static String sanitize(String text) { + if (text == null) { + return ""; + } + String result = text + .replaceAll("(?i)([a-z][a-z0-9+.-]*://)[^\\s/@]+@", "$1***@") + .replaceAll("(?i)\\b(api[-_]?key|apikey|token|secret|password)\\s*[:=]\\s*[^\\s,;]+", "$1=***") + .replaceAll("(?i)\\b(bearer|basic)\\s+[^\\s,;]+", "$1 ***") + .replaceAll("\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+", "***") + .replaceAll("[A-Za-z0-9_\\-+/]{32,}={0,2}", "***") + .replaceAll("\\s+", " ") + .trim(); + return result.length() > MAX_STATUS_RESULT_LENGTH ? result.substring(0, MAX_STATUS_RESULT_LENGTH) : result; + } + + /** + * Logs a login attempt (API key). Must be called before anything that can start a + * scan, so the CLI session id exists before the first scan event. + * + * @param success whether authentication succeeded + * @param failureReason reason shown in {@code statusResult} on failure + */ + public static void logLoginEvent(boolean success, String failureReason) { + try { + SENDER.execute(() -> { + sendNow(buildLoginEvent(success, failureReason)); + if (success) { + flushPendingInstallEvent(); + } + }); + } catch (Exception e) { + CxLogger.warning(format("Telemetry: Could not enqueue login event - %s", e.getMessage())); + } + } + + /** + * Logs one scan event for an engine whose scan completed. + * + * @param scanEngine the engine that was scanned + * @param severities severity of every finding the engine returned + */ + public static void logScanEvent(ScanEngine scanEngine, List severities, String filePath) { + send(buildScanEvent(mapScanEngineToTelemetryEngine(scanEngine), severities, GitRemoteResolver.resolve(filePath))); + } + + /** + * Logs a failed scan for an engine. + */ + public static void logScanFailureEvent(ScanEngine scanEngine, String failureReason, String filePath) { + send(buildScanFailureEvent(mapScanEngineToTelemetryEngine(scanEngine), failureReason, + GitRemoteResolver.resolve(filePath))); + } + + /** + * Identifier of the finding, like the VS Code plugin: ASCA rule id, IaC similarity id, + * Secrets title, Containers image:tag, OSS package@version. + */ + static String vulnerabilityIdOf(ScanIssue issue) { + String title = issue.getTitle() == null ? "" : issue.getTitle(); + ScanEngine engine = issue.getScanEngine(); + if (engine == null) { + return title; + } + switch (engine) { + case ASCA: + return issue.getRuleId() != null ? String.valueOf(issue.getRuleId()) : title; + case IAC: + return issue.getSimilarityId() == null ? "" : issue.getSimilarityId(); + case SECRETS: + return title; + case CONTAINERS: + return issue.getImageTag() != null && !issue.getImageTag().isEmpty() ? title + ":" + issue.getImageTag() + : title; + default: + return issue.getPackageVersion() != null && !issue.getPackageVersion().isEmpty() + ? title + "@" + issue.getPackageVersion() : title; + } } /** @@ -92,7 +471,8 @@ private static void logUserAction(ScanIssue scanIssue, String actionSubType, Str String engine = mapScanEngineToTelemetryEngine(scanIssue.getScanEngine()); String severity = normalizeSeverity(scanIssue.getSeverity()); - setUserEventDataForLogs(EVENT_TYPE_CLICK, actionSubType, engine, severity); + send(buildClickEvent(EVENT_TYPE_CLICK, actionSubType, engine, severity, vulnerabilityIdOf(scanIssue), + STATUS_SUCCESS, "", GitRemoteResolver.resolve(scanIssue.getFilePath()))); } /** @@ -104,6 +484,23 @@ public static void logFixWithCxOneAssistAction(ScanIssue scanIssue) { logUserAction(scanIssue, SUB_TYPE_FIX_WITH_AI_CHAT, "Fix with CxOne Assist"); } + /** + * Logs a "Fix with CxOne Assist" action that failed. + * + * @param scanIssue the scan issue being acted upon + * @param failureReason why the fix could not be dispatched + */ + public static void logFixWithCxOneAssistFailure(ScanIssue scanIssue, String failureReason) { + if (Objects.isNull(scanIssue)) { + CxLogger.warning("Telemetry: Cannot log Fix with CxOne Assist failure - scan issue is null"); + return; + } + send(buildClickEvent(EVENT_TYPE_CLICK, SUB_TYPE_FIX_WITH_AI_CHAT, + mapScanEngineToTelemetryEngine(scanIssue.getScanEngine()), normalizeSeverity(scanIssue.getSeverity()), + vulnerabilityIdOf(scanIssue), STATUS_FAILURE, failureStatusResult("Remediation failed", failureReason), + GitRemoteResolver.resolve(scanIssue.getFilePath()))); + } + /** * Logs user action for "View Details". * @@ -135,7 +532,7 @@ public static void logIgnoreAllAction(ScanIssue scanIssue) { * Maps the model's ScanEngine enum to the telemetry engine string expected * by the backend (matching JetBrains' naming exactly). */ - private static String mapScanEngineToTelemetryEngine(ScanEngine scanEngine) { + public static String mapScanEngineToTelemetryEngine(ScanEngine scanEngine) { if (Objects.isNull(scanEngine)) { return ENGINE_OSS; // default fallback } @@ -181,20 +578,16 @@ private static String normalizeSeverity(String severity) { } /** - * Gets the agent name based on the running Eclipse platform version. + * Gets the Eclipse platform version, sent as {@code agentVersion}. */ - private static String getAgentName() { + private static String getAgentVersion() { try { - String version = Platform.getBundle("org.eclipse.platform") != null - ? Platform.getBundle("org.eclipse.platform").getVersion().toString() - : null; - if (version != null) { - return ECLIPSE_AGENT_NAME + " " + version; + if (Platform.getBundle("org.eclipse.platform") != null) { + return Platform.getBundle("org.eclipse.platform").getVersion().toString(); } } catch (Exception e) { - CxLogger.warning("Telemetry: Could not determine Eclipse platform version, using default - " + e.getMessage()); + CxLogger.warning("Telemetry: Could not determine Eclipse platform version - " + e.getMessage()); } - - return ECLIPSE_AGENT_NAME; + return ""; } } diff --git a/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/CxFindingsView.java b/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/CxFindingsView.java index 07f9562f..15d7643e 100644 --- a/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/CxFindingsView.java +++ b/devassist-lib/src/com/checkmarx/eclipse/devassist/ui/findings/CxFindingsView.java @@ -1029,7 +1029,12 @@ private void showContextMenu(MouseEvent e) { fixWithAIItem.addSelectionListener(new org.eclipse.swt.events.SelectionAdapter() { @Override public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { - new RemediationManager().fixWithCxOneAssist(issue, DevAssistConstants.QUICK_FIX); + try { + new RemediationManager().fixWithCxOneAssist(issue, DevAssistConstants.QUICK_FIX); + } catch (RuntimeException ex) { + TelemetryService.logFixWithCxOneAssistFailure(issue, ex.getMessage()); + throw ex; + } TelemetryService.logFixWithCxOneAssistAction(issue); } });