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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/main/java/com/checkmarx/ast/telemetry/TelemetryEvent.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package com.checkmarx.ast.telemetry;

import lombok.Builder;
import lombok.Getter;
import lombok.Singular;

import java.util.Map;

/**
* Attributes of a Dev Assist telemetry event sent through {@code cx telemetry ai}.
* <p>
* Only non-blank values are forwarded to the CLI. The CLI itself adds the session, unique and machine identifiers.
* Event specific values (for example {@code installationId}, {@code authMethod}, {@code vulnerabilityId},
* {@code remediationMode}) go in {@link #eventAttributes} and are sent as a single
* {@code --event-attributes "key=value;key=value"} argument, which the CLI nests under {@code eventAttributes}.
*/
@Getter
@Builder
public class TelemetryEvent {
/** AI provider name (e.g. "Copilot"). */
private final String aiProvider;
/** Event type (e.g. "click", "authentication", "Scan"). */
private final String eventType;
/** Event sub type (e.g. "fixWithAIChat"). */
private final String subType;
/** Scan engine (e.g. "Oss", "Secrets", "IaC", "Asca", "Containers"). */
private final String engine;
/** Severity of the problem the event relates to. */
private final String problemSeverity;
/** Scan type for scan events. */
private final String scanType;
/** Event status (e.g. "success"). */
private final String status;
/** Detailed status / failure reason. */
private final String statusResult;
/** Number of findings, sent only when not null. */
private final Integer totalCount;
/**
* IDE or agent name (e.g. "Eclipse"). When set, it is sent as {@code --agent} and replaces
* {@code CxConfig#getAgentName()} for this call. When blank, the configured agent name is used.
*/
private final String agent;
/** Version of the host IDE / agent. */
private final String agentVersion;
/** Version of the Checkmarx plugin. */
private final String cxPluginVersion;
/** Plugin type (e.g. "IDE"). */
private final String pluginType;
/** Repository URL of the scanned project. */
private final String repoUrl;
/** Telemetry API version (e.g. "v2"). Sent as the top-level {@code --api-version} flag, like the JavaScript wrapper. */
private final String apiVersion;
/**
* Event specific attributes, sent as {@code --event-attributes key=value;key=value}.
* Entries with a blank value or an invalid key (blank, or containing ';' or '=') are left out,
* and ';' inside a value is replaced with '_'.
*/
@Singular
private final Map<String, String> eventAttributes;
}
10 changes: 9 additions & 1 deletion src/main/java/com/checkmarx/ast/wrapper/CxConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ public void setAdditionalParameters(String additionalParameters) {
}

List<String> toArguments() {
return toArguments(true);
}

/**
* @param includeAgent when false, {@code --agent} is not added, so a caller that sends its own agent
* (e.g. a telemetry event) does not send the flag twice.
*/
List<String> toArguments(boolean includeAgent) {
List<String> commands = new ArrayList<>();

if (StringUtils.isNotBlank(getClientId()) && StringUtils.isNotBlank(getApiKey())) {
Expand Down Expand Up @@ -66,7 +74,7 @@ List<String> toArguments() {
commands.add(CxConstants.BASE_AUTH_URI);
commands.add(getBaseAuthUri());
}
if (getAgentName() != null && !getAgentName().isEmpty()) {
if (includeAgent && getAgentName() != null && !getAgentName().isEmpty()) {
commands.add("--agent");
commands.add(getAgentName());
}
Expand Down
7 changes: 7 additions & 0 deletions src/main/java/com/checkmarx/ast/wrapper/CxConstants.java
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,13 @@ public final class CxConstants {
static final String SCAN_TYPE_FLAG = "--scan-type";
static final String STATUS = "--status";
static final String TOTAL_COUNT = "--total-count";
static final String STATUS_RESULT = "--status-result";
static final String AGENT_VERSION = "--agent-version";
static final String CX_PLUGIN_VERSION = "--cx-plugin-version";
static final String PLUGIN_TYPE = "--plugin-type";
static final String REPO_URL = "--repo-url";
static final String API_VERSION = "--api-version";
static final String EVENT_ATTRIBUTES = "--event-attributes";
static final String DOCKER = "docker";
static final String PODMAN = "podman";
static final String PODMAN_FALLBACK_PATH = "/usr/local/bin/podman";
Expand Down
80 changes: 80 additions & 0 deletions src/main/java/com/checkmarx/ast/wrapper/CxWrapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import com.checkmarx.ast.results.ResultsSummary;
import com.checkmarx.ast.results.result.Node;
import com.checkmarx.ast.scan.Scan;
import com.checkmarx.ast.telemetry.TelemetryEvent;
import com.checkmarx.ast.tenant.TenantSetting;
import com.checkmarx.ast.utils.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand Down Expand Up @@ -816,6 +817,85 @@ public String telemetryAIEvent(String aiProvider, String agent, String eventType
return Execution.executeCommand(withConfigArguments(arguments), logger, line -> line);
}

/**
* Executes the telemetry AI command with the extended Dev Assist analytics attributes.
* Blank attributes are not sent to the CLI. Event specific attributes are sent as one
* {@code --event-attributes key=value;key=value} argument. When {@link TelemetryEvent#getAgent()} is set it
* replaces {@link CxConfig#getAgentName()} for this call, so {@code --agent} is never sent twice.
*
* @param event the telemetry event attributes
* @return Command output as string
* @throws IOException if I/O error occurs
* @throws InterruptedException if command execution is interrupted
* @throws CxException if CLI command fails
*/
public String telemetryAIEvent(@NonNull TelemetryEvent event)
throws IOException, InterruptedException, CxException {
this.logger.info("Executing telemetry AI event with provider: {}, type: {}, subType: {}",
event.getAiProvider(), event.getEventType(), event.getSubType());

boolean includeConfigAgent = StringUtils.isBlank(event.getAgent());
List<String> arguments = new ArrayList<>();
arguments.add(this.executable);
arguments.addAll(buildTelemetryArguments(event));
arguments.addAll(this.cxConfig.toArguments(includeConfigAgent));
return Execution.executeCommand(arguments, logger, line -> line);
}

static List<String> buildTelemetryArguments(TelemetryEvent event) {
List<String> arguments = new ArrayList<>();
arguments.add(CxConstants.CMD_TELEMETRY);
arguments.add(CxConstants.SUB_CMD_TELEMETRY_AI);
addIfNotBlank(arguments, CxConstants.AI_PROVIDER, event.getAiProvider());
addIfNotBlank(arguments, CxConstants.TYPE, event.getEventType());
addIfNotBlank(arguments, CxConstants.SUB_TYPE, event.getSubType());
addIfNotBlank(arguments, CxConstants.ENGINE, event.getEngine());
addIfNotBlank(arguments, CxConstants.PROBLEM_SEVERITY, event.getProblemSeverity());
addIfNotBlank(arguments, CxConstants.SCAN_TYPE_FLAG, event.getScanType());
addIfNotBlank(arguments, CxConstants.STATUS, event.getStatus());
if (event.getTotalCount() != null && event.getTotalCount() >= 0) {
arguments.add(CxConstants.TOTAL_COUNT);
arguments.add(event.getTotalCount().toString());
}
addIfNotBlank(arguments, CxConstants.AGENT, event.getAgent());
addIfNotBlank(arguments, CxConstants.AGENT_VERSION, event.getAgentVersion());
addIfNotBlank(arguments, CxConstants.CX_PLUGIN_VERSION, event.getCxPluginVersion());
addIfNotBlank(arguments, CxConstants.PLUGIN_TYPE, event.getPluginType());
addIfNotBlank(arguments, CxConstants.STATUS_RESULT, event.getStatusResult());
addIfNotBlank(arguments, CxConstants.REPO_URL, event.getRepoUrl());
addIfNotBlank(arguments, CxConstants.API_VERSION, event.getApiVersion());
addIfNotBlank(arguments, CxConstants.EVENT_ATTRIBUTES, serializeEventAttributes(event.getEventAttributes()));
return arguments;
}

/**
* Serializes attributes as {@code key=value;key=value}. Entries with a blank value or an invalid key
* (blank, or containing ';' or '=') are left out. ';' inside a value is replaced with '_' so it cannot break
* the format; '=' is allowed in a value because the CLI splits each pair on the first '=' only.
*/
static String serializeEventAttributes(Map<String, String> attributes) {
if (attributes == null || attributes.isEmpty()) {
return "";
}
List<String> pairs = new ArrayList<>();
for (Map.Entry<String, String> entry : attributes.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (StringUtils.isBlank(key) || key.contains(";") || key.contains("=") || StringUtils.isBlank(value)) {
continue;
}
pairs.add(key + "=" + value.replace(';', '_'));
}
return String.join(";", pairs);
}

private static void addIfNotBlank(List<String> arguments, String flag, String value) {
if (StringUtils.isNotBlank(value)) {
arguments.add(flag);
arguments.add(value);
}
}

private int getIndexOfBfLNode(List<Node> bflNodes, List<Node> resultNodes) {

int bflNodeNotFound = -1;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
package com.checkmarx.ast.wrapper;

import com.checkmarx.ast.telemetry.TelemetryEvent;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.*;

class CxWrapperTelemetryArgumentsTest {

@Test
void testBuildTelemetryArguments_allAttributes() {
TelemetryEvent event = TelemetryEvent.builder()
.aiProvider("Copilot")
.eventType("Click")
.subType("fixWithAIChat")
.engine("Oss")
.problemSeverity("High")
.scanType("Oss")
.status("success")
.statusResult("ok")
.totalCount(3)
.agent("Eclipse")
.agentVersion("2024.1")
.cxPluginVersion("2.0.1")
.pluginType("IDE")
.repoUrl("https://github.com/org/repo")
.apiVersion("v2")
.eventAttribute("vulnerabilityId", "CVE-2024-0001")
.eventAttribute("remediationMode", "DevAssist")
.build();

List<String> args = CxWrapper.buildTelemetryArguments(event);

assertEquals(Arrays.asList(
"telemetry", "ai",
"--ai-provider", "Copilot",
"--type", "Click",
"--sub-type", "fixWithAIChat",
"--engine", "Oss",
"--problem-severity", "High",
"--scan-type", "Oss",
"--status", "success",
"--total-count", "3",
"--agent", "Eclipse",
"--agent-version", "2024.1",
"--cx-plugin-version", "2.0.1",
"--plugin-type", "IDE",
"--status-result", "ok",
"--repo-url", "https://github.com/org/repo",
"--api-version", "v2",
"--event-attributes", "vulnerabilityId=CVE-2024-0001;remediationMode=DevAssist"), args);
}

@Test
void testBuildTelemetryArguments_omitsBlankAndNullAttributes() {
TelemetryEvent event = TelemetryEvent.builder()
.eventType("authentication")
.status("success")
.engine("")
.agent(" ")
.eventAttribute("authMethod", "API_KEY")
.eventAttribute("blank", " ")
.build();

List<String> args = CxWrapper.buildTelemetryArguments(event);

assertEquals(Arrays.asList(
"telemetry", "ai",
"--type", "authentication",
"--status", "success",
"--event-attributes", "authMethod=API_KEY"), args);
}

@Test
void testBuildTelemetryArguments_noEventAttributesFlagWhenAllAttributesInvalid() {
TelemetryEvent event = TelemetryEvent.builder()
.eventAttribute("a", "")
.eventAttribute("b;c", "1")
.build();

assertEquals(Arrays.asList("telemetry", "ai"), CxWrapper.buildTelemetryArguments(event));
}

@Test
void testBuildTelemetryArguments_apiVersionIsTopLevelFlagNotAnEventAttribute() {
TelemetryEvent event = TelemetryEvent.builder().eventType("Scan").apiVersion("v2").build();

assertEquals(Arrays.asList("telemetry", "ai", "--type", "Scan", "--api-version", "v2"),
CxWrapper.buildTelemetryArguments(event));
}

@Test
void testBuildTelemetryArguments_blankApiVersionIsOmitted() {
TelemetryEvent event = TelemetryEvent.builder().apiVersion(" ").build();

assertEquals(Arrays.asList("telemetry", "ai"), CxWrapper.buildTelemetryArguments(event));
}

@Test
void testBuildTelemetryArguments_zeroTotalCountIsSent() {
TelemetryEvent event = TelemetryEvent.builder().totalCount(0).build();

List<String> args = CxWrapper.buildTelemetryArguments(event);

assertEquals(Arrays.asList("telemetry", "ai", "--total-count", "0"), args);
}

@Test
void testBuildTelemetryArguments_negativeTotalCountIsOmitted() {
TelemetryEvent event = TelemetryEvent.builder().totalCount(-1).build();

assertEquals(Arrays.asList("telemetry", "ai"), CxWrapper.buildTelemetryArguments(event));
}

@Test
void testBuildTelemetryArguments_emptyEvent() {
List<String> args = CxWrapper.buildTelemetryArguments(TelemetryEvent.builder().build());

assertEquals(Arrays.asList("telemetry", "ai"), args);
}

@Test
void testSerializeEventAttributes_nullAndEmpty() {
assertEquals("", CxWrapper.serializeEventAttributes(null));
assertEquals("", CxWrapper.serializeEventAttributes(new LinkedHashMap<>()));
}

@Test
void testSerializeEventAttributes_keepsInsertionOrder() {
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("apiVersion", "v2");
attributes.put("authMethod", "API_KEY");

assertEquals("apiVersion=v2;authMethod=API_KEY", CxWrapper.serializeEventAttributes(attributes));
}

@Test
void testSerializeEventAttributes_sanitizesValuesAndDropsInvalidEntries() {
Map<String, String> attributes = new LinkedHashMap<>();
attributes.put("vulnerabilityId", "x;y=z");
attributes.put("empty", "");
attributes.put("nullValue", null);
attributes.put("d=x", "2");
attributes.put("e;y", "3");
attributes.put(" ", "4");

assertEquals("vulnerabilityId=x_y=z", CxWrapper.serializeEventAttributes(attributes));
}

@Test
void testConfigArguments_agentIncludedByDefault() {
CxConfig config = CxConfig.builder().apiKey("key").agentName("Eclipse_1.0.0").build();

assertEquals(Arrays.asList("--apikey", "key", "--agent", "Eclipse_1.0.0"), config.toArguments());
assertEquals(config.toArguments(), config.toArguments(true));
}

@Test
void testConfigArguments_agentOmittedWhenEventSendsItsOwn() {
CxConfig config = CxConfig.builder().apiKey("key").agentName("Eclipse_1.0.0").build();

assertEquals(Arrays.asList("--apikey", "key"), config.toArguments(false));
}
}
Loading