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
22 changes: 13 additions & 9 deletions internal/commands/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,15 +136,19 @@ func validLogin(telemetryWrapper wrappers.TelemetryWrapper) func(cmd *cobra.Comm
authWrapper.SetPath(viper.GetString(params.ScansPathKey))
err := authWrapper.ValidateLogin()

uniqueID := wrappers.GetUniqueID()
if uniqueID != "" {
telemetryErr := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{
UniqueID: uniqueID,
Type: "authentication",
SubType: "authentication",
})
if telemetryErr != nil {
logger.PrintIfVerbose("Failed to send telemetry data: " + telemetryErr.Error())
// Send telemetry only for CLI agents
Comment thread
cx-sumit-morchhale marked this conversation as resolved.
Resolved
agent := viper.GetString(params.AgentNameKey)
if agent == params.DefaultAgent {
uniqueID := wrappers.GetUniqueID()
if uniqueID != "" {
telemetryErr := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{
UniqueID: uniqueID,
Type: "authentication",
SubType: "authentication",
})
if telemetryErr != nil {
logger.PrintIfVerbose("Failed to send telemetry data: " + telemetryErr.Error())
}
}
}

Expand Down
75 changes: 73 additions & 2 deletions internal/commands/telemetry.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
package commands

import (
"strings"

"github.com/MakeNowJust/heredoc"
"github.com/checkmarx/ast-cli/internal/logger"
"github.com/checkmarx/ast-cli/internal/params"
"github.com/checkmarx/ast-cli/internal/wrappers"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

const keyValuePairsSplit = 2

func NewTelemetryCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Command {
telemetryCmd := &cobra.Command{
Use: "telemetry",
Expand All @@ -27,7 +33,7 @@ func telemetryAISubCommand(telemetryAIWrapper wrappers.TelemetryWrapper) *cobra.
Long: "Collects telemetry data for user interactions related to AI features.",
Example: heredoc.Doc(
`
$ cx telemetry ai --ai-provider <AI Provider> --problem-severity <Problem Severity> --type<Event Type> --sub-type<Event Name> --agent <Agent> --engine <Engine>
$ cx telemetry ai --ai-provider <AI Provider> --problem-severity <Problem Severity> --type<Event Type> --sub-type<Event Name> --agent <Agent> --engine <Engine> --event-attributes "apiVersion=v2;vulnerabilityId=CVE-2021-44228;remediationMode=DevAssist"
`,
),

Expand All @@ -42,11 +48,50 @@ func telemetryAISubCommand(telemetryAIWrapper wrappers.TelemetryWrapper) *cobra.
telemetryAICmd.PersistentFlags().String(params.AgentFlag, "", "Agent")
telemetryAICmd.PersistentFlags().String(params.ScanTypeFlag, "", "Scan Type")
telemetryAICmd.PersistentFlags().String(params.StatusFlag, "", "Status")
telemetryAICmd.PersistentFlags().String(params.StatusResultFlag, "", "Status Result")
telemetryAICmd.PersistentFlags().Int(params.TotalCountFlag, 0, "Total Count")
telemetryAICmd.PersistentFlags().String(params.AgentVersionFlag, "", "Agent Version")
telemetryAICmd.PersistentFlags().String(params.CxPluginVersionFlag, "", "CX Plugin Version")
telemetryAICmd.PersistentFlags().String(params.PluginTypeFlag, "", "Plugin Type")
telemetryAICmd.PersistentFlags().String(params.RepoURLFlag, "", "Repository URL")
telemetryAICmd.PersistentFlags().String(params.EventAttributesFlag, "", "Event Attributes in key=value;key=value format (e.g., apiVersion=v2;vulnerabilityId=CVE-2021-44228;remediationMode=DevAssist). Pairs are split on ';', a pair without '=' is skipped, and values cannot contain ';'")
telemetryAICmd.PersistentFlags().String(params.ApiVersionFlag, "", "API Version")

return telemetryAICmd
}

func parseEventAttributes(eventAttributesStr string) *wrappers.EventAttributes {
if eventAttributesStr == "" {
Comment thread
cx-sumit-morchhale marked this conversation as resolved.
Resolved
return nil
}

attrs := make(wrappers.EventAttributes)
pairs := strings.Split(eventAttributesStr, ";")

for _, pair := range pairs {
kv := strings.SplitN(pair, "=", keyValuePairsSplit)
if len(kv) != keyValuePairsSplit {
logger.PrintIfVerbose("Skipping event attribute without '=': " + pair)
continue
}

key := strings.TrimSpace(kv[0])
value := strings.TrimSpace(kv[1])

if key == "" {
logger.PrintIfVerbose("Skipping event attribute with empty key: " + pair)
continue
}
attrs[key] = value
}

if len(attrs) == 0 {
return nil
}

return &attrs
}

func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, _ []string) error {
aiProvider, _ := cmd.Flags().GetString("ai-provider")
Expand All @@ -57,19 +102,45 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm
engine, _ := cmd.Flags().GetString("engine")
scanType, _ := cmd.Flags().GetString("scan-type")
status, _ := cmd.Flags().GetString("status")
totalCount, _ := cmd.Flags().GetInt("total-count")
totalCount, _ := cmd.Flags().GetInt(params.TotalCountFlag)
statusResult, _ := cmd.Flags().GetString(params.StatusResultFlag)
agentVersion, _ := cmd.Flags().GetString(params.AgentVersionFlag)
Comment thread
cx-sumit-morchhale marked this conversation as resolved.
Resolved
cxPluginVersion, _ := cmd.Flags().GetString(params.CxPluginVersionFlag)
pluginType, _ := cmd.Flags().GetString(params.PluginTypeFlag)
repoURL, _ := cmd.Flags().GetString(params.RepoURLFlag)
eventAttributesStr, _ := cmd.Flags().GetString(params.EventAttributesFlag)
apiVersion, _ := cmd.Flags().GetString(params.ApiVersionFlag)

uniqueID := wrappers.GetUniqueID()

var sessionID string
Comment thread
cx-sumit-morchhale marked this conversation as resolved.
Resolved
if eventType == "authentication" && status == "success" {
sessionID = wrappers.GetSessionID()
} else {
sessionID = viper.GetString(params.SessionIDConfigKey)
}

eventAttrs := parseEventAttributes(eventAttributesStr)

err := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{
AIProvider: aiProvider,
ProblemSeverity: problemSeverity,
Type: eventType,
SubType: subType,
Agent: agent,
AgentVersion: agentVersion,
CxPluginVersion: cxPluginVersion,
PluginType: pluginType,
Engine: engine,
ScanType: scanType,
Status: status,
StatusResult: statusResult,
APIVersion: apiVersion,
TotalCount: totalCount,
RepoURL: repoURL,
UniqueID: uniqueID,
SessionID: sessionID,
EventAttributes: eventAttrs,
})

if err != nil {
Expand Down
72 changes: 72 additions & 0 deletions internal/commands/telemetry_test.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,84 @@
//go:build !integration

package commands

import (
"io"
"testing"

"github.com/checkmarx/ast-cli/internal/params"
"github.com/checkmarx/ast-cli/internal/wrappers"
"github.com/checkmarx/ast-cli/internal/wrappers/mock"
"github.com/spf13/viper"
"gotest.tools/assert"
)

func TestParseEventAttributes(t *testing.T) {
tests := []struct {
name string
input string
expected wrappers.EventAttributes
}{
{name: "empty input returns nil", input: "", expected: nil},
{name: "single pair", input: "apiVersion=v2", expected: wrappers.EventAttributes{"apiVersion": "v2"}},
{
name: "arbitrary keys are all kept",
input: "apiVersion=v2;vulnerabilityId=CVE-2021-44228;remediationMode=DevAssist",
expected: wrappers.EventAttributes{"apiVersion": "v2", "vulnerabilityId": "CVE-2021-44228", "remediationMode": "DevAssist"},
},
{name: "value containing equals keeps text after first equals", input: "token=a=b=c", expected: wrappers.EventAttributes{"token": "a=b=c"}},
{name: "pair without equals is skipped", input: "a=1;bad;c=3", expected: wrappers.EventAttributes{"a": "1", "c": "3"}},
{name: "empty key is skipped", input: "=v;b=2", expected: wrappers.EventAttributes{"b": "2"}},
{name: "whitespace around key and value is trimmed", input: " a = 1 ; b=2 ", expected: wrappers.EventAttributes{"a": "1", "b": "2"}},
{name: "semicolon in value splits into separate pairs", input: "a=x;y=2", expected: wrappers.EventAttributes{"a": "x", "y": "2"}},
{name: "only malformed pairs returns nil", input: "bad;worse", expected: nil},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := parseEventAttributes(tt.input)
if tt.expected == nil {
assert.Assert(t, got == nil, "expected nil attributes")
return
}
assert.Assert(t, got != nil, "expected attributes")
assert.DeepEqual(t, *got, tt.expected)
})
}
}

func TestRunTelemetryAI_PassesEventAttributesAndSessionID(t *testing.T) {
originalSessionID := viper.GetString(params.SessionIDConfigKey)
defer viper.Set(params.SessionIDConfigKey, originalSessionID)
viper.Set(params.SessionIDConfigKey, "existing-session")

var captured *wrappers.DataForAITelemetry
telemetryWrapper := mock.TelemetryMockWrapper{
CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error {
captured = data
return nil
},
}

cmd := NewTelemetryCommand(telemetryWrapper)
cmd.SetOut(io.Discard)
cmd.SetArgs([]string{
"ai", "--type", "click", "--engine", "secrets",
"--event-attributes", "apiVersion=v2;vulnerabilityId=CVE-2021-44228;remediationMode=DevAssist",
})
err := cmd.Execute()

assert.NilError(t, err)
assert.Assert(t, captured != nil, "expected telemetry data to be sent")
assert.Equal(t, "existing-session", captured.SessionID, "non-auth events reuse the stored session ID")
assert.Assert(t, captured.EventAttributes != nil, "expected event attributes")
assert.DeepEqual(t, *captured.EventAttributes, wrappers.EventAttributes{
"apiVersion": "v2",
"vulnerabilityId": "CVE-2021-44228",
"remediationMode": "DevAssist",
})
}

func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) {
mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true}
execCmdNilAssertion(
Expand Down
1 change: 1 addition & 0 deletions internal/params/envs.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ const (
ConfigFilePathEnv = "CX_CONFIG_FILE_PATH"
RealtimeScannerPathEnv = "CX_REALTIME_SCANNER_PATH"
UniqueIDEnv = "CX_UNIQUE_ID"
SessionIDEnv = "CX_SESSION_ID"
StartMultiPartUploadPathEnv = "CX_START_MULTIPART_UPLOAD_PATH"
MultipartPresignedPathEnv = "CX_MULTIPART_PRESIGNED_URL_PATH"
CompleteMultipartUploadPathEnv = "CX_COMPLETE_MULTIPART_UPLOAD_PATH"
Expand Down
8 changes: 7 additions & 1 deletion internal/params/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,15 @@ const (
SubTypeFlag = "sub-type"
EngineFlag = "engine"
StatusFlag = "status"
StatusResultFlag = "status-result"
scanTypeFlag = "scan-type"
TotalCountFlag = "total-count"
AgentVersionFlag = "agent-version"
CxPluginVersionFlag = "cx-plugin-version"
PluginTypeFlag = "plugin-type"
RepoURLFlag = "repo-url"
EventAttributesFlag = "event-attributes"
ApiVersionFlag = "api-version"
OriginFlag = "origin"
AgentFlagUsage = "Scan origin name"
ApplicationName = "application-name"
Expand Down Expand Up @@ -167,7 +174,6 @@ const (
URLFlagUsage = "API base URL"
QueryIDFlag = "query-id"
SSHKeyFlag = "ssh-key"
RepoURLFlag = "repo-url"
SSHValue = "ssh-value"
KicsContainerNameKey = "kics-container-name"
KicsPlatformsFlag = "kics-platforms"
Expand Down
1 change: 1 addition & 0 deletions internal/params/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ var (
ConfigFilePathKey = strings.ToLower(ConfigFilePathEnv)
RealtimeScannerPathKey = strings.ToLower(RealtimeScannerPathEnv)
UniqueIDConfigKey = strings.ToLower(UniqueIDEnv)
SessionIDConfigKey = strings.ToLower(SessionIDEnv)
StartMultiPartUploadPathKey = strings.ToLower(StartMultiPartUploadPathEnv)
MultipartPresignedPathKey = strings.ToLower(MultipartPresignedPathEnv)
CompleteMultiPartUploadPathKey = strings.ToLower(CompleteMultipartUploadPathEnv)
Expand Down
48 changes: 47 additions & 1 deletion internal/wrappers/jwt-helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@ import (
"github.com/spf13/viper"
)

const (
uuidLength = 36
uniqueIDPartsCnt = 2
)

// JWTStruct model used to get all jwt fields
type JWTStruct struct {
Tenant string `json:"tenant_name"`
Expand Down Expand Up @@ -222,10 +227,14 @@ func GetUniqueID() string {

// Check if unique id is already set
uniqueID = viper.GetString(commonParams.UniqueIDConfigKey)
if uniqueID != "" {
if uniqueID != "" && isValidUniqueIDFormat(uniqueID) {
return uniqueID
}

if uniqueID != "" {
logger.PrintIfVerbose("Existing unique ID invalid format, regenerating")
}

// Generate new unique id
currentUser, err := user.Current()
if err != nil {
Expand All @@ -247,3 +256,40 @@ func GetUniqueID() string {
}
return uniqueID
}

func isValidUniqueIDFormat(uniqueID string) bool {
parts := strings.SplitN(uniqueID, "_", uniqueIDPartsCnt)
if len(parts) != uniqueIDPartsCnt {
return false
}

guid := parts[0]
storedUsername := parts[1]

if len(guid) != uuidLength {
return false
}

if _, err := uuid.Parse(guid); err != nil {
return false
}

return storedUsername != ""
}

// GetSessionID always generates a new session ID UUID, overwriting any existing value, and persists it to the config file.
func GetSessionID() string {
sessionID := uuid.New().String()
Comment thread
cx-sumit-morchhale marked this conversation as resolved.
Resolved
viper.Set(commonParams.SessionIDConfigKey, sessionID)
configFilePath, err := configuration.GetConfigFilePath()
if err != nil {
logger.PrintIfVerbose("Failed to get config file path: " + err.Error())
return sessionID
}

err = configuration.SafeWriteSingleConfigKeyString(configFilePath, commonParams.SessionIDConfigKey, sessionID)
if err != nil {
logger.PrintIfVerbose("Failed to write session ID config: " + err.Error())
}
return sessionID
}
Loading
Loading