From ed9b8cc237cddf02ab44c54c87ea533ec20833d8 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:44:24 +0530 Subject: [PATCH 01/19] AST-195928 - Add Dev Assist analytics fields to agent-hook telemetry The scan (hooks-detect) and remediation (hooks-remediate) events that `cx hooks` sends now carry the fields the Dev Assist analytics design needs: - agentVersion, cxPluginVersion and pluginType, from the CX_AGENT_VERSION, CX_PLUGIN_VERSION and CX_PLUGIN_TYPE variables the agent plugins set - sessionId, from the session the authentication event stored - repoUrl, from the hook's working directory, with any username, password or token removed - status, and on scans a statusResult of per-severity counts (Critical=n,High=n,Medium=n,Low=n,Info=n) - on remediation, eventAttributes.remediationMode=SelfHealing, aiAgentSessionId and vulnerabilityId (CVE ids for SCA, the rule id for ASCA, the similarity id for KICS, the rule title for secrets) Scan counts now report every detected finding. The severity threshold still decides what is denied, but no longer hides findings from the analytics. The shared logic lives in the new agenthooks/hooktelemetry package. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> --- internal/commands/agenthooks/cx/hooks.go | 22 ++- internal/commands/agenthooks/cx/hooks_test.go | 10 +- .../agenthooks/guardrails/asca/asca.go | 22 ++- .../agenthooks/guardrails/asca/asca_test.go | 6 +- .../agenthooks/guardrails/kics/kics.go | 39 +++- .../agenthooks/guardrails/kics/kics_test.go | 6 +- .../agenthooks/guardrails/secrets/secrets.go | 20 +- .../agenthooks/hooktelemetry/hooktelemetry.go | 184 ++++++++++++++++++ .../hooktelemetry/hooktelemetry_test.go | 97 +++++++++ internal/commands/agenthooks/sca/sca.go | 13 ++ internal/params/envs.go | 3 + 11 files changed, 393 insertions(+), 29 deletions(-) create mode 100644 internal/commands/agenthooks/hooktelemetry/hooktelemetry.go create mode 100644 internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index dbe0b0d65..4cfd9b4b8 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -12,6 +12,7 @@ import ( "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/asca" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/kics" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/secrets" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/sca" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/scannerconfig" @@ -89,7 +90,7 @@ func cxBeforeToolCall(ev agenthooks.ToolCallEvent) agenthooks.ToolVerdict { sid := sessionIDFromToolCall(&ev) if finding, remediation, severity := scaScanner.CheckBashInstall(ev.Command, ev.WorkDir, agent, sid); finding != "" && !belowThreshold(ev.Agent, severity) { sessiontally.Add(sid, engineSca, 1, 1) - logRemediationTelemetry(agent, "SCA", severity, sid) + logRemediationTelemetry(agent, "SCA", severity, sid, ev.WorkDir) return agenthooks.DenyWithContext(finding, remediation) } } @@ -145,7 +146,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { if scannerOn(ev.Agent, scannerconfig.ASCA) { if blocked, reason, context, severity := asca.ScanFileEdit(&ev, telemetryWrapper, agent); blocked && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineAsca, 1, 1) - logRemediationTelemetry(agent, "Asca", severity, ev.SessionID) + logRemediationTelemetry(agent, "Asca", severity, ev.SessionID, ev.WorkDir) return agenthooks.RejectEditWithContext(reason, context) } } @@ -154,7 +155,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { blocked, reason, context, note, severity := kics.ScanFileEdit(&ev, kicsScanner, telemetryWrapper, agent) if blocked && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineKics, 1, 1) - logRemediationTelemetry(agent, "IaC", severity, ev.SessionID) + logRemediationTelemetry(agent, "IaC", severity, ev.SessionID, ev.WorkDir) return agenthooks.RejectEditWithContext(reason, context) } kicsNote = note @@ -163,7 +164,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { for _, diff := range ev.Changes { if finding, remediation, severity := scaScanner.CheckManifestEdit(ev.FilePath, fullAfterContent(ev.FilePath, diff), ev.WorkDir, agent, ev.SessionID); finding != "" && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineSca, 1, 1) - logRemediationTelemetry(agent, "Oss", severity, ev.SessionID) + logRemediationTelemetry(agent, "Oss", severity, ev.SessionID, ev.WorkDir) return agenthooks.RejectEditWithContext(finding, remediation) } } @@ -171,7 +172,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { if secretsScanner != nil && secretsApply(ev.Agent) && scannerOn(ev.Agent, scannerconfig.Secrets) { if blocked, reason, context, severity := secrets.ScanFileEdit(&ev, secretsScanner, telemetryWrapper, agent); blocked && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineSecrets, 1, 1) - logRemediationTelemetry(agent, "Secrets", severity, ev.SessionID) + logRemediationTelemetry(agent, "Secrets", severity, ev.SessionID, ev.WorkDir) return agenthooks.RejectEditWithContext(reason, context) } } @@ -288,11 +289,18 @@ func RegisterPassThrough() { } // logRemediationTelemetry sends telemetry when remediation context is delivered to the agent. -func logRemediationTelemetry(agent, engine, severity, sessionID string) { +func logRemediationTelemetry(agent, engine, severity, sessionID, workDir string) { if telemetryWrapper == nil { return } + attrs := wrappers.EventAttributes{"remediationMode": hooktelemetry.RemediationModeSelfHealing} + if ids := hooktelemetry.TakeFindingIDs(); ids != "" { + attrs["vulnerabilityId"] = ids + } + if sessionID != "" { + attrs["aiAgentSessionId"] = sessionID + } telemetryData := &wrappers.DataForAITelemetry{ AIProvider: agent, Agent: hostenv.TelemetryAgent(agent), @@ -303,7 +311,9 @@ func logRemediationTelemetry(agent, engine, severity, sessionID string) { SubType: "fixWithAIAssist", ProblemSeverity: severity, AiAgentSessionId: sessionID, + EventAttributes: &attrs, } + hooktelemetry.Enrich(telemetryData, workDir) if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { // fail-open diff --git a/internal/commands/agenthooks/cx/hooks_test.go b/internal/commands/agenthooks/cx/hooks_test.go index a70eeb8c1..be395fab5 100644 --- a/internal/commands/agenthooks/cx/hooks_test.go +++ b/internal/commands/agenthooks/cx/hooks_test.go @@ -628,13 +628,13 @@ func TestLogRemediationTelemetry(t *testing.T) { t.Run("nil_wrapper_noop", func(t *testing.T) { telemetryWrapper = nil - logRemediationTelemetry("Claude", "SCA", "High", "s1") // must not panic + logRemediationTelemetry("Claude", "SCA", "High", "s1", "") // must not panic }) t.Run("sends_payload", func(t *testing.T) { tel := &recordingTelemetry{} telemetryWrapper = tel - logRemediationTelemetry("Cursor", "Asca", "Critical", "sess-9") + logRemediationTelemetry("Cursor", "Asca", "Critical", "sess-9", "") if len(tel.calls) != 1 { t.Fatalf("got %d calls, want 1", len(tel.calls)) } @@ -656,7 +656,7 @@ func TestLogRemediationTelemetry(t *testing.T) { t.Run("send_error_fail_open", func(t *testing.T) { tel := &recordingTelemetry{err: os.ErrPermission} telemetryWrapper = tel - logRemediationTelemetry("Claude", "SCA", "High", "s2") // must not panic + logRemediationTelemetry("Claude", "SCA", "High", "s2", "") // must not panic if len(tel.calls) != 1 { t.Fatalf("got %d calls, want 1", len(tel.calls)) } @@ -858,7 +858,7 @@ func TestLogRemediationTelemetry_NilWrapper_NoOp(t *testing.T) { telemetryWrapper = nil assert.NotPanics(t, func() { - logRemediationTelemetry("Claude", "SCA", "finding", "remediation") + logRemediationTelemetry("Claude", "SCA", "finding", "remediation", "") }) } @@ -868,7 +868,7 @@ func TestLogRemediationTelemetry_WithWrapper_Sends(t *testing.T) { telemetryWrapper = mock.TelemetryMockWrapper{} assert.NotPanics(t, func() { - logRemediationTelemetry("Claude", "SCA", "finding", "remediation") + logRemediationTelemetry("Claude", "SCA", "finding", "remediation", "") }) } diff --git a/internal/commands/agenthooks/guardrails/asca/asca.go b/internal/commands/agenthooks/guardrails/asca/asca.go index 2427913e0..411373bf1 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca.go +++ b/internal/commands/agenthooks/guardrails/asca/asca.go @@ -3,9 +3,11 @@ package asca import ( "os" "path/filepath" + "strconv" "strings" agenthooks "github.com/Checkmarx/ast-cx-hooks" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/services" @@ -42,6 +44,7 @@ var BelowThreshold func(severity string) bool // verdict. Fail-open on infrastructure errors (ASCA install fail, engine unavailable, panic). func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.TelemetryWrapper, agent string) (blocked bool, reason, context, severity string) { findingCount := 0 + var severities []string defer func() { if r := recover(); r != nil { @@ -49,7 +52,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme reason = "" context = "" } - logASCATelemetry(telemetryWrapper, agent, ev.SessionID, findingCount) + logASCATelemetry(telemetryWrapper, agent, ev.SessionID, ev.WorkDir, findingCount, severities) }() if !isSupportedByASCA(ev.FilePath) { @@ -104,14 +107,23 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme newFindings = nil } } + // Telemetry reports what was DETECTED; the threshold only decides what is denied. + detected := newFindings + findingCount = len(detected) + for i := range detected { + severities = append(severities, detected[i].Severity) + } newFindings = aboveThreshold(newFindings) if len(newFindings) == 0 { - findingCount = 0 return false, "", "", "" } + ids := make([]string, 0, len(newFindings)) + for i := range newFindings { + ids = append(ids, strconv.FormatUint(uint64(newFindings[i].RuleID), 10)) + } + hooktelemetry.SetFindingIDs(ids) r, c := formatFindings(ev.FilePath, newFindings, ev.WorkDir, agent, ev.SessionID) - findingCount = len(newFindings) return true, r, c, highestSeverity(newFindings) } @@ -187,7 +199,7 @@ func shouldUpdateVersion() bool { // logASCATelemetry sends a telemetry event for ASCA scan results. // Called once after ASCA scan is performed with the actual finding count. -func logASCATelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID string, totalCount int) { +func logASCATelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID, workDir string, totalCount int, severities []string) { if telemetryWrapper == nil || totalCount == 0 { return } @@ -201,8 +213,10 @@ func logASCATelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session Type: "hooks-detect", SubType: "scan", ScanType: "asca", + StatusResult: hooktelemetry.SeverityCounts(severities), AiAgentSessionId: sessionID, } + hooktelemetry.Enrich(telemetryData, workDir) if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { // fail-open diff --git a/internal/commands/agenthooks/guardrails/asca/asca_test.go b/internal/commands/agenthooks/guardrails/asca/asca_test.go index f71a76c85..42484e16c 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca_test.go +++ b/internal/commands/agenthooks/guardrails/asca/asca_test.go @@ -568,7 +568,7 @@ func TestShouldUpdateVersion_DisabledReturnsFalse(t *testing.T) { func TestLogASCATelemetry_NilWrapper_NoOp(t *testing.T) { assert.NotPanics(t, func() { - logASCATelemetry(nil, "Claude", "", 3) + logASCATelemetry(nil, "Claude", "", "", 3, nil) }) } @@ -580,7 +580,7 @@ func TestLogASCATelemetry_ZeroCount_DoesNotSend(t *testing.T) { return nil }, } - logASCATelemetry(telemetry, "Claude", "", 0) + logASCATelemetry(telemetry, "Claude", "", "", 0, nil) assert.False(t, sent) } @@ -592,7 +592,7 @@ func TestLogASCATelemetry_WithFindings_Sends(t *testing.T) { return nil }, } - logASCATelemetry(telemetry, "Claude", "", 2) + logASCATelemetry(telemetry, "Claude", "", "", 2, nil) assert.NotNil(t, captured) assert.Equal(t, "Asca", captured.Engine) assert.Equal(t, 2, captured.TotalCount) diff --git a/internal/commands/agenthooks/guardrails/kics/kics.go b/internal/commands/agenthooks/guardrails/kics/kics.go index 684f4ee01..7cdee78e0 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics.go +++ b/internal/commands/agenthooks/guardrails/kics/kics.go @@ -7,6 +7,7 @@ import ( "strings" agenthooks "github.com/Checkmarx/ast-cx-hooks" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/params" @@ -55,6 +56,7 @@ var BelowThreshold func(severity string) bool // returning a skippedNote so the skipped check is visible. func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper wrappers.TelemetryWrapper, agent string) (blocked bool, reason, context, note, severity string) { findingCount := 0 + var severities []string defer func() { if r := recover(); r != nil { @@ -65,7 +67,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w note = skippedNote(ev.FilePath, fmt.Errorf("internal error: %v", r)) severity = "" } - logKicsTelemetry(telemetryWrapper, agent, ev.SessionID, findingCount) + logKicsTelemetry(telemetryWrapper, agent, ev.SessionID, ev.WorkDir, findingCount, severities) }() if !isSupportedByKICS(ev.FilePath) { @@ -100,12 +102,15 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w // For new files (no original content), every finding is new if originalContent == "" { + detected := newResults + findingCount = len(detected) + severities = resultSeverities(detected) newResults = aboveThreshold(newResults) if len(newResults) == 0 { return false, "", "", "", "" } + hooktelemetry.SetFindingIDs(resultIDs(newResults)) r, c := formatFindings(ev.FilePath, newResults, ev.Agent, ev.WorkDir, ev.SessionID) - findingCount = len(newResults) return true, r, c, "", highestSeverity(newResults) } @@ -123,16 +128,38 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w return false, "", "", skippedNote(ev.FilePath, err), "" } - newFindings := aboveThreshold(NewFindings(origResults, newResults)) + // Telemetry reports what was DETECTED; the threshold only decides what is denied. + detected := NewFindings(origResults, newResults) + findingCount = len(detected) + severities = resultSeverities(detected) + newFindings := aboveThreshold(detected) if len(newFindings) == 0 { return false, "", "", "", "" } + hooktelemetry.SetFindingIDs(resultIDs(newFindings)) r, c := formatFindings(ev.FilePath, newFindings, ev.Agent, ev.WorkDir, ev.SessionID) - findingCount = len(newFindings) return true, r, c, "", highestSeverity(newFindings) } +// resultIDs lists each finding's similarity id, the identifier reported as vulnerabilityId. +func resultIDs(findings []iacrealtime.IacRealtimeResult) []string { + out := make([]string, 0, len(findings)) + for i := range findings { + out = append(out, findings[i].SimilarityID) + } + return out +} + +// resultSeverities lists each finding's severity, for the scan event's per-severity counts. +func resultSeverities(findings []iacrealtime.IacRealtimeResult) []string { + out := make([]string, 0, len(findings)) + for i := range findings { + out = append(out, findings[i].Severity) + } + return out +} + // aboveThreshold drops findings below the developer's severity threshold. func aboveThreshold(findings []iacrealtime.IacRealtimeResult) []iacrealtime.IacRealtimeResult { if BelowThreshold == nil { @@ -165,7 +192,7 @@ func highestSeverity(findings []iacrealtime.IacRealtimeResult) string { // logKicsTelemetry sends a telemetry event for KICS scan results. // Called once after KICS scan is performed with the actual finding count. -func logKicsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID string, totalCount int) { +func logKicsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID, workDir string, totalCount int, severities []string) { if telemetryWrapper == nil || totalCount == 0 { return } @@ -179,8 +206,10 @@ func logKicsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session Type: "hooks-detect", SubType: "scan", ScanType: "iac", + StatusResult: hooktelemetry.SeverityCounts(severities), AiAgentSessionId: sessionID, } + hooktelemetry.Enrich(telemetryData, workDir) if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { // fail-open: telemetry is best-effort and must never block the guardrail diff --git a/internal/commands/agenthooks/guardrails/kics/kics_test.go b/internal/commands/agenthooks/guardrails/kics/kics_test.go index 058f6f1b1..4b6bcc848 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics_test.go +++ b/internal/commands/agenthooks/guardrails/kics/kics_test.go @@ -239,7 +239,7 @@ func TestScanFileEdit_EngineDownProducesNote(t *testing.T) { func TestLogKicsTelemetry_NilWrapper_NoOp(t *testing.T) { assert.NotPanics(t, func() { - logKicsTelemetry(nil, "Claude", "", 3) + logKicsTelemetry(nil, "Claude", "", "", 3, nil) }) } @@ -251,7 +251,7 @@ func TestLogKicsTelemetry_ZeroCount_DoesNotSend(t *testing.T) { return nil }, } - logKicsTelemetry(telemetry, "Claude", "", 0) + logKicsTelemetry(telemetry, "Claude", "", "", 0, nil) assert.False(t, sent) } @@ -263,7 +263,7 @@ func TestLogKicsTelemetry_WithFindings_Sends(t *testing.T) { return nil }, } - logKicsTelemetry(telemetry, "Claude", "sess-1", 2) + logKicsTelemetry(telemetry, "Claude", "sess-1", "", 2, nil) assert.NotNil(t, captured) assert.Equal(t, "IaC", captured.Engine) assert.Equal(t, 2, captured.TotalCount) diff --git a/internal/commands/agenthooks/guardrails/secrets/secrets.go b/internal/commands/agenthooks/guardrails/secrets/secrets.go index b4c3bbd8e..3592be718 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets.go @@ -4,6 +4,7 @@ import ( "os" agenthooks "github.com/Checkmarx/ast-cx-hooks" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" @@ -36,6 +37,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w } findingCount := 0 + var severities []string defer func() { if r := recover(); r != nil { logger.PrintfIfVerbose("secrets guardrail: recovered from panic, failing open: %v", r) @@ -44,7 +46,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w context = "" severity = "" } - logSecretsTelemetry(telemetryWrapper, agent, ev.SessionID, findingCount) + logSecretsTelemetry(telemetryWrapper, agent, ev.SessionID, ev.WorkDir, findingCount, severities) }() newContent, originalContent, ok := proposedContent(ev.FilePath, ev.Changes) @@ -79,13 +81,23 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w } } + // Telemetry reports what was DETECTED; the threshold only decides what is denied. + detected := findings + findingCount = len(detected) + for i := range detected { + severities = append(severities, detected[i].Severity) + } findings = aboveThreshold(findings) if len(findings) == 0 { return false, "", "", "" } + ids := make([]string, 0, len(findings)) + for i := range findings { + ids = append(ids, findings[i].Title) + } + hooktelemetry.SetFindingIDs(ids) r, c := formatFindings(ev.FilePath, findings, ev.Agent, ev.WorkDir, ev.SessionID) - findingCount = len(findings) return true, r, c, highestSeverity(findings) } @@ -116,7 +128,7 @@ func highestSeverity(findings []secretsrealtime.SecretsRealtimeResult) string { return best } -func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID string, totalCount int) { +func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID, workDir string, totalCount int, severities []string) { if telemetryWrapper == nil || totalCount == 0 { return } @@ -130,8 +142,10 @@ func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sess Type: "hooks-detect", SubType: "scan", ScanType: "secrets", + StatusResult: hooktelemetry.SeverityCounts(severities), AiAgentSessionId: sessionID, } + hooktelemetry.Enrich(telemetryData, workDir) if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { logger.PrintfIfVerbose("secrets guardrail: failed to send telemetry: %v", err) diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go new file mode 100644 index 000000000..0beccad74 --- /dev/null +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -0,0 +1,184 @@ +// Package hooktelemetry adds the Dev Assist analytics fields to the telemetry events the agent hooks +// send (scan and remediation). The plugin that launches `cx hooks` passes what only it knows (agent +// version, plugin version, plugin type) through environment variables; the session id comes from the +// CLI config, and the repository URL from the hook's working directory. +package hooktelemetry + +import ( + "fmt" + "os" + "strings" + "sync" + + gogit "github.com/go-git/go-git/v5" + "github.com/spf13/viper" + + "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/wrappers" +) + +const ( + // StatusSuccess is the status sent for an event whose operation completed. + StatusSuccess = "success" + // RemediationModeSelfHealing marks a remediation driven by a hook deny (the agent fixes its own edit). + RemediationModeSelfHealing = "SelfHealing" + + remoteName = "origin" + schemeSeparator = "://" +) + +// severityOrder is the order severities appear in a scan event's statusResult. +var severityOrder = []string{"Critical", "High", "Medium", "Low", "Info"} + +// maxFindingIDs caps how many IDs one remediation event carries. +const maxFindingIDs = 10 + +var ( + repoURLMu sync.Mutex + repoURLCache = map[string]string{} + + findingIDsMu sync.Mutex + findingIDs []string +) + +// SetFindingIDs records the IDs (CVE, rule id, ...) of the findings a guardrail is about to deny, so +// the remediation event for that deny can report them as eventAttributes.vulnerabilityId. `cx hooks` +// handles one hook event per process, so the last recorded set always belongs to the current deny. +// Empty IDs and duplicates are dropped; at most maxFindingIDs are kept. +func SetFindingIDs(ids []string) { + seen := make(map[string]bool, len(ids)) + kept := make([]string, 0, len(ids)) + for _, id := range ids { + id = strings.TrimSpace(id) + if id == "" || seen[id] { + continue + } + seen[id] = true + kept = append(kept, id) + if len(kept) == maxFindingIDs { + break + } + } + findingIDsMu.Lock() + findingIDs = kept + findingIDsMu.Unlock() +} + +// TakeFindingIDs returns the IDs recorded by SetFindingIDs, comma-separated ("" when none), and clears +// them so a later event in the same process never reuses them. +func TakeFindingIDs() string { + findingIDsMu.Lock() + defer findingIDsMu.Unlock() + ids := strings.Join(findingIDs, ",") + findingIDs = nil + return ids +} + +// Enrich fills the fields every hook telemetry event shares. It never fails: a value that cannot be +// determined is left empty and the JSON omits it. +func Enrich(data *wrappers.DataForAITelemetry, workDir string) { + if data == nil { + return + } + data.AgentVersion = strings.TrimSpace(os.Getenv(params.AgentVersionEnv)) + data.CxPluginVersion = strings.TrimSpace(os.Getenv(params.CxPluginVersionEnv)) + data.PluginType = strings.TrimSpace(os.Getenv(params.PluginTypeEnv)) + data.SessionID = viper.GetString(params.SessionIDConfigKey) + data.RepoURL = RepoURL(workDir) + if data.Status == "" { + data.Status = StatusSuccess + } +} + +// SeverityCounts renders severities as "Critical=n,High=n,Medium=n,Low=n,Info=n", the scan event's +// statusResult. Severities outside the known five are not counted. +func SeverityCounts(severities []string) string { + counts := make(map[string]int, len(severityOrder)) + for _, s := range severities { + for _, known := range severityOrder { + if strings.EqualFold(s, known) { + counts[known]++ + break + } + } + } + parts := make([]string, 0, len(severityOrder)) + for _, s := range severityOrder { + parts = append(parts, fmt.Sprintf("%s=%d", s, counts[s])) + } + return strings.Join(parts, ",") +} + +// RepoURL returns the credential-free "origin" URL of the git repository containing workDir, or "" when +// there is none. The result is cached per workDir for the life of the process. +func RepoURL(workDir string) string { + if workDir == "" { + return "" + } + repoURLMu.Lock() + defer repoURLMu.Unlock() + if u, ok := repoURLCache[workDir]; ok { + return u + } + u := SanitizeRepoURL(originURL(workDir)) + repoURLCache[workDir] = u + return u +} + +func originURL(workDir string) string { + repo, err := gogit.PlainOpenWithOptions(workDir, &gogit.PlainOpenOptions{DetectDotGit: true}) + if err != nil { + return "" + } + remote, err := repo.Remote(remoteName) + if err != nil { + return "" + } + urls := remote.Config().URLs + if len(urls) == 0 { + return "" + } + return urls[0] +} + +// SanitizeRepoURL removes every credential from a git remote URL so it is safe to send: the userinfo of +// any scheme (tokens, passwords and usernames), the query and the fragment. An SCP-style remote +// (git@host:org/repo) becomes https://host/org/repo. A local path, or anything unrecognised, returns "". +func SanitizeRepoURL(raw string) string { + raw = strings.TrimSpace(raw) + if raw == "" { + return "" + } + var host, path string + if i := strings.Index(raw, schemeSeparator); i >= 0 { + rest := raw[i+len(schemeSeparator):] + if at := strings.LastIndexByte(rest, '@'); at >= 0 { + rest = rest[at+1:] + } + host, path, _ = strings.Cut(rest, "/") + path = "/" + path + } else { + // SCP-style: [user@]host:path. A Windows drive (C:\...) or a bare path has no host part. + colon := strings.IndexByte(raw, ':') + if colon <= 1 || strings.ContainsAny(raw[:colon], `/\`) { + return "" + } + host = raw[:colon] + if at := strings.LastIndexByte(host, '@'); at >= 0 { + host = host[at+1:] + } + path = "/" + strings.TrimPrefix(raw[colon+1:], "/") + } + if j := strings.IndexAny(path, "?#"); j >= 0 { + path = path[:j] + } + // Drop a port so ssh and https remotes of the same repository match. + if k := strings.LastIndexByte(host, ':'); k >= 0 { + host = host[:k] + } + if host == "" { + return "" + } + path = strings.TrimSuffix(strings.TrimSuffix(path, "/"), ".git") + return "https://" + host + path +} diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go new file mode 100644 index 000000000..5e5da8e2c --- /dev/null +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -0,0 +1,97 @@ +//go:build !integration + +package hooktelemetry + +import ( + "os" + "strings" + "testing" + + gogit "github.com/go-git/go-git/v5" + "github.com/go-git/go-git/v5/config" + "github.com/spf13/viper" + "gotest.tools/assert" + + "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/wrappers" +) + +// testRemotePassword is the password embedded in a credentialed remote URL fixture. It is read from the +// environment so no credential is hardcoded; any non-empty value exercises the stripping logic. +func testRemotePassword() string { + if v := os.Getenv("CX_TEST_REMOTE_PASSWORD"); v != "" { + return v + } + return "unused" +} + +func TestSanitizeRepoURL(t *testing.T) { + credentialedURL := "https://user:" + testRemotePassword() + "@github.com/acme/repo" + tests := []struct{ in, want string }{ + {"https://github.com/acme/repo.git", "https://github.com/acme/repo"}, + {"https://token@github.com/acme/repo.git", "https://github.com/acme/repo"}, + {credentialedURL, "https://github.com/acme/repo"}, + {"https://github.com/acme/repo?token=abc#frag", "https://github.com/acme/repo"}, + {"ssh://git@github.com:22/acme/repo.git", "https://github.com/acme/repo"}, + {"git@github.com:acme/repo.git", "https://github.com/acme/repo"}, + {"https://dev.azure.com:443/org/proj/_git/repo/", "https://dev.azure.com/org/proj/_git/repo"}, + {`C:\work\repo`, ""}, + {"/home/me/repo", ""}, + {"", ""}, + } + for _, tt := range tests { + assert.Equal(t, SanitizeRepoURL(tt.in), tt.want, "input %q", tt.in) + } +} + +func TestSeverityCounts(t *testing.T) { + got := SeverityCounts([]string{"High", "critical", "High", "Low", "unknown"}) + assert.Equal(t, got, "Critical=1,High=2,Medium=0,Low=1,Info=0") + assert.Equal(t, SeverityCounts(nil), "Critical=0,High=0,Medium=0,Low=0,Info=0") +} + +func TestEnrich(t *testing.T) { + dir := t.TempDir() + repo, err := gogit.PlainInit(dir, false) + assert.NilError(t, err) + _, err = repo.CreateRemote(&config.RemoteConfig{Name: "origin", URLs: []string{"https://token@github.com/acme/repo.git"}}) + assert.NilError(t, err) + + t.Setenv(params.AgentVersionEnv, " 2.1.4 ") + t.Setenv(params.CxPluginVersionEnv, "1.0.3") + t.Setenv(params.PluginTypeEnv, "CLI") + original := viper.GetString(params.SessionIDConfigKey) + defer viper.Set(params.SessionIDConfigKey, original) + viper.Set(params.SessionIDConfigKey, "sess-123") + + data := &wrappers.DataForAITelemetry{Type: "hooks-detect"} + Enrich(data, dir) + + assert.Equal(t, data.AgentVersion, "2.1.4") + assert.Equal(t, data.CxPluginVersion, "1.0.3") + assert.Equal(t, data.PluginType, "CLI") + assert.Equal(t, data.SessionID, "sess-123") + assert.Equal(t, data.RepoURL, "https://github.com/acme/repo") + assert.Equal(t, data.Status, StatusSuccess) +} + +func TestFindingIDs(t *testing.T) { + SetFindingIDs([]string{"CVE-1", " ", "CVE-2", "CVE-1"}) + assert.Equal(t, TakeFindingIDs(), "CVE-1,CVE-2", "blanks and duplicates are dropped") + assert.Equal(t, TakeFindingIDs(), "", "taking clears the recorded ids") + + many := make([]string, 0, maxFindingIDs+5) + for i := 0; i < maxFindingIDs+5; i++ { + many = append(many, "id"+string(rune('a'+i))) + } + SetFindingIDs(many) + assert.Equal(t, len(strings.Split(TakeFindingIDs(), ",")), maxFindingIDs, "capped at maxFindingIDs") +} + +func TestEnrichToleratesMissingContext(t *testing.T) { + Enrich(nil, "") // must not panic + data := &wrappers.DataForAITelemetry{Status: "failure"} + Enrich(data, t.TempDir()) // not a git repo + assert.Equal(t, data.RepoURL, "") + assert.Equal(t, data.Status, "failure", "an explicit status is kept") +} diff --git a/internal/commands/agenthooks/sca/sca.go b/internal/commands/agenthooks/sca/sca.go index 641906fd4..178d9570f 100644 --- a/internal/commands/agenthooks/sca/sca.go +++ b/internal/commands/agenthooks/sca/sca.go @@ -3,6 +3,7 @@ package sca import ( "os" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" ) @@ -80,12 +81,24 @@ func denyFrom(malicious, vulnerable []ossrealtime.OssPackage, workDir, agent, se } vulnerable = aboveThreshold(vulnerable) if len(vulnerable) > 0 { + hooktelemetry.SetFindingIDs(vulnerableCVEs(vulnerable)) f, r := DenyVulnerable(vulnerable, workDir, agent, sessionID) return tag + " " + f, tag + " " + r, highestVulnSeverity(vulnerable) } return "", "", "" } +// vulnerableCVEs lists the CVE ids of the denied vulnerable packages, reported as vulnerabilityId. +func vulnerableCVEs(pkgs []ossrealtime.OssPackage) []string { + var ids []string + for i := range pkgs { + for _, v := range pkgs[i].Vulnerabilities { + ids = append(ids, v.CVE) + } + } + return ids +} + // aboveThreshold drops CVEs below the developer's severity threshold, and any package left with // none. Malicious packages never go through here. A CVE with an unknown severity is kept. func aboveThreshold(pkgs []ossrealtime.OssPackage) []ossrealtime.OssPackage { diff --git a/internal/params/envs.go b/internal/params/envs.go index 75b256715..a430bf8ff 100644 --- a/internal/params/envs.go +++ b/internal/params/envs.go @@ -87,6 +87,9 @@ const ( RealtimeScannerPathEnv = "CX_REALTIME_SCANNER_PATH" UniqueIDEnv = "CX_UNIQUE_ID" SessionIDEnv = "CX_SESSION_ID" + AgentVersionEnv = "CX_AGENT_VERSION" + CxPluginVersionEnv = "CX_PLUGIN_VERSION" + PluginTypeEnv = "CX_PLUGIN_TYPE" StartMultiPartUploadPathEnv = "CX_START_MULTIPART_UPLOAD_PATH" MultipartPresignedPathEnv = "CX_MULTIPART_PRESIGNED_URL_PATH" CompleteMultipartUploadPathEnv = "CX_COMPLETE_MULTIPART_UPLOAD_PATH" From 9cbe21f873eafa1df46bd02d8a6fe6d60a6d2c7f Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Fri, 27 Nov 2026 12:15:28 +0530 Subject: [PATCH 02/19] AST-195928 - Complete Dev Assist scan and ignore telemetry Signed-off-by: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> --- internal/commands/agenthooks/cx/hooks.go | 1 + .../agenthooks/guardrails/asca/delta.go | 20 +--- .../agenthooks/guardrails/kics/delta.go | 15 +-- .../agenthooks/guardrails/secrets/delta.go | 15 +-- .../agenthooks/hooktelemetry/hooktelemetry.go | 25 +++++ .../hooktelemetry/hooktelemetry_test.go | 16 ++++ internal/commands/agenthooks/sca/prompts.go | 18 +--- internal/commands/agenthooks/sca/sca.go | 54 +++++++++++ internal/commands/agenthooks/sca/scan.go | 2 + .../agenthooks/sca/telemetry_ids_test.go | 69 ++++++++++++++ internal/commands/ignore_vulnerability.go | 62 +++++++++++- .../ignore_vulnerability_telemetry_test.go | 94 +++++++++++++++++++ internal/commands/telemetry.go | 5 +- internal/commands/telemetry_test.go | 30 ++++++ internal/wrappers/utils/utils.go | 3 + 15 files changed, 367 insertions(+), 62 deletions(-) create mode 100644 internal/commands/agenthooks/sca/telemetry_ids_test.go create mode 100644 internal/commands/ignore_vulnerability_telemetry_test.go diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index 4cfd9b4b8..f28ea0966 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -267,6 +267,7 @@ func promptWorkspaceRoots(raw any) []string { // SCA, KICS, and secret-detection scanners used by the Bash and FileEdit handlers. func RegisterGuardrails(jwt wrappers.JWTWrapper, ff wrappers.FeatureFlagsWrapper, rt wrappers.RealtimeScannerWrapper, tel wrappers.TelemetryWrapper) { scaScanner = sca.NewScanner(jwt, ff, rt) + scaScanner.Telemetry = tel kicsScanner = kics.NewScanner(jwt, ff) secretsScanner = secrets.NewScanner(jwt, ff) telemetryWrapper = tel diff --git a/internal/commands/agenthooks/guardrails/asca/delta.go b/internal/commands/agenthooks/guardrails/asca/delta.go index 61631d6e5..8d753859d 100644 --- a/internal/commands/agenthooks/guardrails/asca/delta.go +++ b/internal/commands/agenthooks/guardrails/asca/delta.go @@ -10,6 +10,7 @@ import ( "github.com/checkmarx/ast-cli/internal/commands/agenthooks/agentprofile" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/cursorplugin" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" ) @@ -154,21 +155,6 @@ func cursorEscapeJSON(data string) string { return strings.ReplaceAll(data, `"`, `\"`) } -// optionalFlagsFragment carries the suppression's provenance (AI provider, agent, session id) to the -// child `cx ignore-vulnerability` process via --optional-flags, which reads them through -// utils.GetOptionalParam and logs them — matching logRemediationTelemetry's aiProvider/agent/session. -// Empty agent → no fragment (nothing to attribute). -func optionalFlagsFragment(agent, sessionID string) string { - if agent == "" { - return "" - } - pairs := "aiProvider=" + agent + ";agent=" + agent + "-cli" - if sessionID != "" { - pairs += ";aiAgentSessionId=" + sessionID - } - return fmt.Sprintf(" --optional-flags %q", pairs) -} - // hookDenyHeader is the agent-facing opening of additionalContext. The provenance tag is // prepended separately in formatFindings. This header does not contain the spoof phrases // the skills treat as proof a message is not from Checkmarx. @@ -204,7 +190,7 @@ const ascaRemediationReport = "5. Always finish with this report, even if you as // use ignore.QuoteDataFlag (PowerShell-safe quoting on Windows); other agents keep the // original single-quoted JSON payload. func additionalContext(filePath, cxBinary string, findings []grpcs.ScanDetail, workDir, agent, sessionID string) string { - provenance := optionalFlagsFragment(agent, sessionID) + provenance := hooktelemetry.IgnoreFlags(agent, sessionID) var suppressCmds strings.Builder for _, f := range findings { data, _ := json.Marshal(grpcs.AscaIgnoreFinding{ @@ -266,7 +252,7 @@ func additionalContext(filePath, cxBinary string, findings []grpcs.ScanDetail, w // cursorAdditionalContext is remediation guidance for Cursor only. Uses the plugin-prefixed MCP // tool name and PowerShell --% stop-parsing for suppress commands on Windows. func cursorAdditionalContext(filePath, cxBinary string, findings []grpcs.ScanDetail, workDir, sessionID string) string { - provenance := optionalFlagsFragment(agentCursor, sessionID) + provenance := hooktelemetry.IgnoreFlags(agentCursor, sessionID) var suppressCmds strings.Builder for i := range findings { f := &findings[i] diff --git a/internal/commands/agenthooks/guardrails/kics/delta.go b/internal/commands/agenthooks/guardrails/kics/delta.go index beec5ea8c..bf6d5286d 100644 --- a/internal/commands/agenthooks/guardrails/kics/delta.go +++ b/internal/commands/agenthooks/guardrails/kics/delta.go @@ -10,6 +10,7 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/agentprofile" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/cursorplugin" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" ) @@ -118,18 +119,6 @@ func cursorIgnoredFilePathFlag(workDir string) string { return fmt.Sprintf(" --ignored-file-path %q", p) } -func optionalFlagsFragment(agent agenthooks.AgentID, sessionID string) string { - label := agentLabel(agent) - if label == "" { - return "" - } - pairs := "aiProvider=" + label + ";agent=" + label + "-cli" - if sessionID != "" { - pairs += ";aiAgentSessionId=" + sessionID - } - return fmt.Sprintf(" --optional-flags %q", pairs) -} - func agentLabel(agent agenthooks.AgentID) string { switch agent { case agenthooks.AgentClaude: @@ -148,7 +137,7 @@ func agentLabel(agent agenthooks.AgentID) string { } func kicsSuppressCommands(cxBinary string, findings []iacrealtime.IacRealtimeResult, workDir string, agent agenthooks.AgentID, sessionID string) string { - provenance := optionalFlagsFragment(agent, sessionID) + provenance := hooktelemetry.IgnoreFlags(agentLabel(agent), sessionID) var suppressCmds strings.Builder for i := range findings { f := &findings[i] diff --git a/internal/commands/agenthooks/guardrails/secrets/delta.go b/internal/commands/agenthooks/guardrails/secrets/delta.go index 1d79833de..831c336b4 100644 --- a/internal/commands/agenthooks/guardrails/secrets/delta.go +++ b/internal/commands/agenthooks/guardrails/secrets/delta.go @@ -9,6 +9,7 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/cursorplugin" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" ) @@ -118,18 +119,6 @@ func cursorIgnoredFilePathFlag(workDir string) string { return fmt.Sprintf(" --ignored-file-path %q", p) } -func optionalFlagsFragment(agent agenthooks.AgentID, sessionID string) string { - label := agentLabel(agent) - if label == "" { - return "" - } - pairs := "aiProvider=" + label + ";agent=" + label + "-cli" - if sessionID != "" { - pairs += ";aiAgentSessionId=" + sessionID - } - return fmt.Sprintf(" --optional-flags %q", pairs) -} - func agentLabel(agent agenthooks.AgentID) string { switch agent { case agenthooks.AgentClaude: @@ -151,7 +140,7 @@ func agentLabel(agent agenthooks.AgentID) string { // The finding JSON (which must include SecretValue) is stored in a temp file and passed as // --data @ so the secret value is not embedded in the agent-visible command. func secretsSuppressCommands(cxBinary string, findings []secretsrealtime.SecretsRealtimeResult, workDir string, agent agenthooks.AgentID, sessionID string) string { - provenance := optionalFlagsFragment(agent, sessionID) + provenance := hooktelemetry.IgnoreFlags(agentLabel(agent), sessionID) var suppressCmds strings.Builder for i := range findings { f := &findings[i] diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go index 0beccad74..9aa17b739 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -7,12 +7,14 @@ package hooktelemetry import ( "fmt" "os" + "regexp" "strings" "sync" gogit "github.com/go-git/go-git/v5" "github.com/spf13/viper" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/wrappers" ) @@ -74,6 +76,29 @@ func TakeFindingIDs() string { return ids } +// ignoreFlagValue keeps values safe in the optional flag parser and in generated shell commands. +var ignoreFlagValue = regexp.MustCompile(`^[A-Za-z0-9._:/+@-]+$`) + +// IgnoreFlags carries the hook's attribution to the separate ignore command. +func IgnoreFlags(agent, sessionID string) string { + if !ignoreFlagValue.MatchString(agent) { + return "" + } + pairs := []string{"aiProvider=" + agent, "agent=" + hostenv.TelemetryAgent(agent)} + for _, field := range []struct{ key, value string }{ + {"aiAgentSessionId", sessionID}, + {"agentVersion", os.Getenv(params.AgentVersionEnv)}, + {"cxPluginVersion", os.Getenv(params.CxPluginVersionEnv)}, + {"pluginType", os.Getenv(params.PluginTypeEnv)}, + } { + value := strings.TrimSpace(field.value) + if ignoreFlagValue.MatchString(value) { + pairs = append(pairs, field.key+"="+value) + } + } + return fmt.Sprintf(" --optional-flags %q", strings.Join(pairs, ";")) +} + // Enrich fills the fields every hook telemetry event shares. It never fails: a value that cannot be // determined is left empty and the JSON omits it. func Enrich(data *wrappers.DataForAITelemetry, workDir string) { diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go index 5e5da8e2c..3f50acf6b 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -95,3 +95,19 @@ func TestEnrichToleratesMissingContext(t *testing.T) { assert.Equal(t, data.RepoURL, "") assert.Equal(t, data.Status, "failure", "an explicit status is kept") } + +func TestIgnoreFlags(t *testing.T) { + t.Setenv("PLUGIN_ROOT", "") + t.Setenv("CX_COPILOT_HOST", "vscode") + t.Setenv(params.AgentVersionEnv, " 1.2.3 ") + t.Setenv(params.CxPluginVersionEnv, "2.3.4") + t.Setenv(params.PluginTypeEnv, "CLI") + + want := " --optional-flags \"aiProvider=Copilot;agent=Copilot-VSCode;aiAgentSessionId=session-1;agentVersion=1.2.3;cxPluginVersion=2.3.4;pluginType=CLI\"" + assert.Equal(t, IgnoreFlags("Copilot", "session-1"), want) + + t.Setenv(params.AgentVersionEnv, "1;pluginType=unexpected") + t.Setenv(params.CxPluginVersionEnv, "") + assert.Equal(t, IgnoreFlags("Cursor", "invalid session"), " --optional-flags \"aiProvider=Cursor;agent=Cursor-cli;pluginType=CLI\"") + assert.Equal(t, IgnoreFlags("", ""), "") +} diff --git a/internal/commands/agenthooks/sca/prompts.go b/internal/commands/agenthooks/sca/prompts.go index 507db2498..4bf9d1686 100644 --- a/internal/commands/agenthooks/sca/prompts.go +++ b/internal/commands/agenthooks/sca/prompts.go @@ -10,6 +10,7 @@ import ( "github.com/checkmarx/ast-cli/internal/commands/agenthooks/agentprofile" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/cursorplugin" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" ) @@ -170,7 +171,7 @@ func remediationNote(packages, agent string) string { // original single-quoted JSON payload. func vulnerableRemediationNote(pkgs []ossrealtime.OssPackage, workDir, agent, sessionID string) string { cxBinary := cxExecutable() - provenance := optionalFlagsFragment(agent, sessionID) + provenance := hooktelemetry.IgnoreFlags(agent, sessionID) var suppressCmds strings.Builder for _, p := range pkgs { data, _ := json.Marshal([]map[string]string{{ @@ -327,21 +328,6 @@ func cursorEscapeJSON(data string) string { return strings.ReplaceAll(data, `"`, `\"`) } -// optionalFlagsFragment carries the suppression's provenance (AI provider, agent, session id) to the -// child `cx ignore-vulnerability` process via --optional-flags, which reads them through -// utils.GetOptionalParam and logs them — matching logRemediationTelemetry's aiProvider/agent/session. -// Empty agent → no fragment (nothing to attribute). -func optionalFlagsFragment(agent, sessionID string) string { - if agent == "" { - return "" - } - pairs := "aiProvider=" + agent + ";agent=" + agent + "-cli" - if sessionID != "" { - pairs += ";aiAgentSessionId=" + sessionID - } - return fmt.Sprintf(" --optional-flags %q", pairs) -} - func cxExecutable() string { cxExe, err := os.Executable() if err != nil { diff --git a/internal/commands/agenthooks/sca/sca.go b/internal/commands/agenthooks/sca/sca.go index 178d9570f..ede379346 100644 --- a/internal/commands/agenthooks/sca/sca.go +++ b/internal/commands/agenthooks/sca/sca.go @@ -4,7 +4,9 @@ import ( "os" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" + "github.com/checkmarx/ast-cli/internal/wrappers" ) // BelowThreshold is set by the hook dispatcher and reports whether a finding's severity is under the @@ -25,6 +27,7 @@ func (s *Scanner) CheckBashInstall(command, workDir, agent, sessionID string) (f if err != nil { continue } + s.logScan(agent, sessionID, workDir, mal, vuln) if f, r, sev := denyFrom(mal, vuln, workDir, agent, sessionID); f != "" { return f, r, sev } @@ -67,6 +70,7 @@ func (s *Scanner) CheckManifestEdit(filePath string, afterContent []byte, workDi if err != nil { return "", "", "" } + s.logScan(agent, sessionID, workDir, mal, vuln) return denyFrom(mal, vuln, workDir, agent, sessionID) } @@ -76,6 +80,7 @@ func (s *Scanner) CheckManifestEdit(filePath string, afterContent []byte, workDi func denyFrom(malicious, vulnerable []ossrealtime.OssPackage, workDir, agent, sessionID string) (finding, remediation, severity string) { tag := provenanceTag(agent) if len(malicious) > 0 { + hooktelemetry.SetFindingIDs(maliciousPackageIDs(malicious)) f, r := DenyMalicious(malicious, agent) return tag + " " + f, tag + " " + r, statusMalicious } @@ -88,6 +93,55 @@ func denyFrom(malicious, vulnerable []ossrealtime.OssPackage, workDir, agent, se return "", "", "" } +// logScan sends the SCA scan (hooks-detect) event: every detected CVE counted by severity, plus one +// Critical per malicious package. Like the other engines it reports what was DETECTED (the severity +// threshold only decides the deny) and sends nothing for a clean scan. Fail-open. +func (s *Scanner) logScan(agent, sessionID, workDir string, malicious, vulnerable []ossrealtime.OssPackage) { + if s.Telemetry == nil { + return + } + severities := make([]string, 0, len(malicious)) + for range malicious { + severities = append(severities, "Critical") + } + for i := range vulnerable { + for _, v := range vulnerable[i].Vulnerabilities { + severities = append(severities, v.Severity) + } + } + if len(severities) == 0 { + return + } + data := &wrappers.DataForAITelemetry{ + Agent: hostenv.TelemetryAgent(agent), + AIProvider: agent, + Engine: "Oss", + TotalCount: len(severities), + UniqueID: wrappers.GetUniqueID(), + Type: "hooks-detect", + SubType: "scan", + ScanType: "oss", + StatusResult: hooktelemetry.SeverityCounts(severities), + AiAgentSessionId: sessionID, + } + hooktelemetry.Enrich(data, workDir) + _ = s.Telemetry.SendAIDataToLog(data) +} + +// maliciousPackageIDs identifies denied malicious packages as name@version (they have no CVE), +// reported as vulnerabilityId. +func maliciousPackageIDs(pkgs []ossrealtime.OssPackage) []string { + ids := make([]string, 0, len(pkgs)) + for i := range pkgs { + id := pkgs[i].PackageName + if pkgs[i].PackageVersion != "" { + id += "@" + pkgs[i].PackageVersion + } + ids = append(ids, id) + } + return ids +} + // vulnerableCVEs lists the CVE ids of the denied vulnerable packages, reported as vulnerabilityId. func vulnerableCVEs(pkgs []ossrealtime.OssPackage) []string { var ids []string diff --git a/internal/commands/agenthooks/sca/scan.go b/internal/commands/agenthooks/sca/scan.go index e78ab6b54..647d3fa4b 100644 --- a/internal/commands/agenthooks/sca/scan.go +++ b/internal/commands/agenthooks/sca/scan.go @@ -31,6 +31,8 @@ type Scanner struct { // workspace rather than the hook process's own working directory. A hook runs // as a one-shot process handling a single event, so this single field is safe. workDir string + // Telemetry, when set, receives one scan (hooks-detect) event per SCA scan with findings. + Telemetry wrappers.TelemetryWrapper } // NewScanner returns a Scanner backed by the given wrappers. The scan call diff --git a/internal/commands/agenthooks/sca/telemetry_ids_test.go b/internal/commands/agenthooks/sca/telemetry_ids_test.go new file mode 100644 index 000000000..daf833536 --- /dev/null +++ b/internal/commands/agenthooks/sca/telemetry_ids_test.go @@ -0,0 +1,69 @@ +//go:build !integration + +package sca + +import ( + "testing" + + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" + "github.com/checkmarx/ast-cli/internal/wrappers" + "github.com/checkmarx/ast-cli/internal/wrappers/mock" +) + +func TestDenyFrom_RecordsVulnerabilityIDs(t *testing.T) { + old := BelowThreshold + t.Cleanup(func() { BelowThreshold = old }) + BelowThreshold = nil + hooktelemetry.TakeFindingIDs() // start clean + + vuln := []ossrealtime.OssPackage{{PackageName: "lodash", PackageVersion: "4.17.20", + Vulnerabilities: []ossrealtime.Vulnerability{{CVE: "CVE-2021-23337", Severity: "High"}, {CVE: "CVE-2020-28500", Severity: "Medium"}}}} + if f, _, _ := denyFrom(nil, vuln, "", "Claude", "s"); f == "" { + t.Fatal("vulnerable package must deny") + } + if got := hooktelemetry.TakeFindingIDs(); got != "CVE-2021-23337,CVE-2020-28500" { + t.Fatalf("vulnerable deny must record its CVEs, got %q", got) + } + + mal := []ossrealtime.OssPackage{ + {PackageName: "evil-pkg", PackageVersion: "1.0.0", Status: statusMalicious}, + {PackageName: "no-version", Status: statusMalicious}, + } + if f, _, _ := denyFrom(mal, nil, "", "Claude", "s"); f == "" { + t.Fatal("malicious package must deny") + } + if got := hooktelemetry.TakeFindingIDs(); got != "evil-pkg@1.0.0,no-version" { + t.Fatalf("malicious deny must record name@version, got %q", got) + } +} + +func TestLogScan_SendsDetectedCounts(t *testing.T) { + var sent []*wrappers.DataForAITelemetry + s := &Scanner{Telemetry: mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(d *wrappers.DataForAITelemetry) error { + sent = append(sent, d) + return nil + }}} + + s.logScan("Claude", "sess", t.TempDir(), nil, nil) + if len(sent) != 0 { + t.Fatal("a clean scan sends nothing") + } + + mal := []ossrealtime.OssPackage{{PackageName: "evil", Status: statusMalicious}} + vuln := []ossrealtime.OssPackage{{PackageName: "lodash", Vulnerabilities: []ossrealtime.Vulnerability{ + {CVE: "CVE-1", Severity: "High"}, {CVE: "CVE-2", Severity: "Low"}}}} + s.logScan("Claude", "sess", t.TempDir(), mal, vuln) + if len(sent) != 1 { + t.Fatalf("expected one scan event, got %d", len(sent)) + } + d := sent[0] + if d.Type != "hooks-detect" || d.Engine != "Oss" || d.Agent != "Claude-cli" || d.TotalCount != 3 { + t.Fatalf("unexpected event: %+v", d) + } + if d.StatusResult != "Critical=1,High=1,Medium=0,Low=1,Info=0" { + t.Fatalf("unexpected statusResult %q", d.StatusResult) + } + + (&Scanner{}).logScan("Claude", "sess", "", mal, vuln) // no telemetry wrapper: must not panic +} diff --git a/internal/commands/ignore_vulnerability.go b/internal/commands/ignore_vulnerability.go index 1f3f22d1c..d3ed22ddb 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -7,8 +7,14 @@ import ( "strings" "github.com/MakeNowJust/heredoc" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" commonParams "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/containersrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" + "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" "github.com/checkmarx/ast-cli/internal/wrappers" "github.com/checkmarx/ast-cli/internal/wrappers/utils" "github.com/pkg/errors" @@ -101,7 +107,7 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd action = "revived" } if !remove && changed > 0 { - logIgnoreTelemetry(telemetryWrapper, scanType) + logIgnoreTelemetry(telemetryWrapper, scanType, entries) } _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s %d vulnerability(ies); %d entr%s now in %s\n", @@ -141,7 +147,7 @@ func plural(n int) string { } // logIgnoreTelemetry sends telemetry when an agent ignores a finding via the realtime ignore file. -func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType string) { +func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType string, entries []any) { if telemetryWrapper == nil { return } @@ -150,6 +156,19 @@ func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType str sessionID := utils.GetOptionalParam("aiAgentSessionId") agent := utils.GetOptionalParam("agent") engine := engineName(scanType) + + attrs := wrappers.EventAttributes{} + ids := make([]string, 0, len(entries)) + for _, e := range entries { + ids = append(ids, ignoreEntryID(e)) + } + hooktelemetry.SetFindingIDs(ids) + if v := hooktelemetry.TakeFindingIDs(); v != "" { + attrs["vulnerabilityId"] = v + } + if sessionID != "" { + attrs["aiAgentSessionId"] = sessionID + } telemetryData := &wrappers.DataForAITelemetry{ AIProvider: aiProvider, Agent: agent, @@ -160,12 +179,51 @@ func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType str SubType: "ignorePackage", AiAgentSessionId: sessionID, } + if len(attrs) > 0 { + telemetryData.EventAttributes = &attrs + } + // The agent runs `cx ignore-vulnerability` from its shell, not through the plugin's cx_run.sh, so + // the env context may be absent: --optional-flags agentVersion/cxPluginVersion/pluginType win. + workDir, _ := os.Getwd() + hooktelemetry.Enrich(telemetryData, workDir) + if v := utils.GetOptionalParam("agentVersion"); v != "" { + telemetryData.AgentVersion = v + } + if v := utils.GetOptionalParam("cxPluginVersion"); v != "" { + telemetryData.CxPluginVersion = v + } + if v := utils.GetOptionalParam("pluginType"); v != "" { + telemetryData.PluginType = v + } if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { // fail-open } } +// ignoreEntryID is the vulnerabilityId reported for an ignored finding: the CVE-less package or image +// coordinates for oss/containers, the rule id for ASCA, the similarity id (or title) for IaC, and only +// the rule title for secrets — never the secret value the entry also holds. +func ignoreEntryID(entry any) string { + switch e := entry.(type) { + case ossrealtime.IgnoredPackage: + return e.PackageName + "@" + e.PackageVersion + case containersrealtime.IgnoredContainersFinding: + return e.ImageName + ":" + e.ImageTag + case iacrealtime.IgnoredIacFinding: + if e.SimilarityID != "" { + return e.SimilarityID + } + return e.Title + case secretsrealtime.IgnoredSecret: + return e.Title + case grpcs.AscaIgnoreFinding: + return fmt.Sprint(e.RuleID) + default: + return "" + } +} + // engineName maps a --scan-type value to the capitalized engine label used in telemetry // (matching the convention in agenthooks/cx/hooks.go, e.g. "Oss", "Asca", "Sca"). func engineName(scanType string) string { diff --git a/internal/commands/ignore_vulnerability_telemetry_test.go b/internal/commands/ignore_vulnerability_telemetry_test.go new file mode 100644 index 000000000..8a60c0b1f --- /dev/null +++ b/internal/commands/ignore_vulnerability_telemetry_test.go @@ -0,0 +1,94 @@ +//go:build !integration + +package commands + +import ( + "strings" + "testing" + + "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/containersrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" + "github.com/checkmarx/ast-cli/internal/wrappers" + "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" + "github.com/checkmarx/ast-cli/internal/wrappers/mock" + "github.com/checkmarx/ast-cli/internal/wrappers/utils" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +func TestIgnoreEntryID(t *testing.T) { + cases := []struct { + entry any + want string + }{ + {ossrealtime.IgnoredPackage{PackageManager: "npm", PackageName: "lodash", PackageVersion: "4.17.20"}, "lodash@4.17.20"}, + {containersrealtime.IgnoredContainersFinding{ImageName: "nginx", ImageTag: "1.25"}, "nginx:1.25"}, + {iacrealtime.IgnoredIacFinding{Title: "Privileged", SimilarityID: "sim-1"}, "sim-1"}, + {iacrealtime.IgnoredIacFinding{Title: "Privileged"}, "Privileged"}, + {secretsrealtime.IgnoredSecret{Title: "github-pat", SecretValue: "must-not-leak"}, "github-pat"}, + {grpcs.AscaIgnoreFinding{FileName: "a.py", Line: 3, RuleID: 4003}, "4003"}, + {"unknown", ""}, + } + for _, c := range cases { + if got := ignoreEntryID(c.entry); got != c.want { + t.Errorf("ignoreEntryID(%T) = %q, want %q", c.entry, got, c.want) + } + } +} + +func TestLogIgnoreTelemetry_CarriesIDsAndNeverTheSecret(t *testing.T) { + var sent *wrappers.DataForAITelemetry + tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(d *wrappers.DataForAITelemetry) error { + sent = d + return nil + }} + logIgnoreTelemetry(tel, "secrets", []any{secretsrealtime.IgnoredSecret{Title: "github-pat", SecretValue: "must-not-leak"}}) + + if sent == nil || sent.EventAttributes == nil { + t.Fatal("expected an ignore event with event attributes") + } + if got := (*sent.EventAttributes)["vulnerabilityId"]; got != "github-pat" { + t.Fatalf("vulnerabilityId = %q", got) + } + if sent.Status != "success" { + t.Fatalf("status = %q, want success (common fields are filled)", sent.Status) + } + for k, v := range *sent.EventAttributes { + if strings.Contains(v, "must-not-leak") { + t.Fatalf("secret value leaked in attribute %q", k) + } + } +} + +func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { + t.Setenv("CX_AGENT_VERSION", "env-version") + for _, key := range []string{"aiProvider", "agent", "aiAgentSessionId", "agentVersion", "cxPluginVersion", "pluginType"} { + previous := utils.GetOptionalParam(key) + t.Cleanup(func() { _ = utils.SetOptionalParam(key, previous) }) + } + key := params.OptionalFlagsKey + previous := viper.Get(key) + t.Cleanup(func() { viper.Set(key, previous) }) + viper.Set(key, "aiProvider=Codex;agent=Codex-cli;aiAgentSessionId=agent-session;agentVersion=1.2.3;cxPluginVersion=2.3.4;pluginType=CLI") + if err := extractOptionalFlags(&cobra.Command{}); err != nil { + t.Fatal(err) + } + + var sent *wrappers.DataForAITelemetry + tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + sent = data + return nil + }} + logIgnoreTelemetry(tel, "asca", nil) + if sent == nil || sent.AIProvider != "Codex" || sent.Agent != "Codex-cli" || + sent.AiAgentSessionId != "agent-session" || sent.AgentVersion != "1.2.3" || + sent.CxPluginVersion != "2.3.4" || sent.PluginType != "CLI" { + t.Fatalf("unexpected ignore telemetry: %+v", sent) + } + if sent.EventAttributes == nil || (*sent.EventAttributes)["aiAgentSessionId"] != "agent-session" { + t.Fatalf("missing session attribute: %+v", sent.EventAttributes) + } +} diff --git a/internal/commands/telemetry.go b/internal/commands/telemetry.go index 49ebfce78..99be5b036 100644 --- a/internal/commands/telemetry.go +++ b/internal/commands/telemetry.go @@ -45,7 +45,7 @@ func telemetryAISubCommand(telemetryAIWrapper wrappers.TelemetryWrapper) *cobra. telemetryAICmd.PersistentFlags().String(params.TypeFlag, "", "Type") telemetryAICmd.PersistentFlags().String(params.SubTypeFlag, "", "Sub Type") telemetryAICmd.PersistentFlags().String(params.EngineFlag, "", "Engine") - telemetryAICmd.PersistentFlags().String(params.AgentFlag, "", "Agent") + telemetryAICmd.PersistentFlags().String(params.AgentFlag, "", "Agent (authentication telemetry is skipped when omitted)") telemetryAICmd.PersistentFlags().String(params.ScanTypeFlag, "", "Scan Type") telemetryAICmd.PersistentFlags().String(params.StatusFlag, "", "Status") telemetryAICmd.PersistentFlags().String(params.StatusResultFlag, "", "Status Result") @@ -99,6 +99,9 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm eventType, _ := cmd.Flags().GetString("type") subType, _ := cmd.Flags().GetString("sub-type") agent, _ := cmd.Flags().GetString("agent") + if eventType == "authentication" && strings.TrimSpace(agent) == "" { + return nil + } engine, _ := cmd.Flags().GetString("engine") scanType, _ := cmd.Flags().GetString("scan-type") status, _ := cmd.Flags().GetString("status") diff --git a/internal/commands/telemetry_test.go b/internal/commands/telemetry_test.go index dcca56155..e0848d46a 100644 --- a/internal/commands/telemetry_test.go +++ b/internal/commands/telemetry_test.go @@ -79,6 +79,36 @@ func TestRunTelemetryAI_PassesEventAttributesAndSessionID(t *testing.T) { }) } +func TestRunTelemetryAI_AuthenticationWithoutAgentSkipsSend(t *testing.T) { + originalSessionID := viper.GetString(params.SessionIDConfigKey) + t.Cleanup(func() { viper.Set(params.SessionIDConfigKey, originalSessionID) }) + viper.Set(params.SessionIDConfigKey, "existing-session") + + for _, tc := range []struct { + name string + args []string + }{ + {name: "omitted"}, + {name: "blank", args: []string{"--agent", " "}}, + } { + t.Run(tc.name, func(t *testing.T) { + called := false + cmd := NewTelemetryCommand(mock.TelemetryMockWrapper{ + CustomSendAIDataToLog: func(_ *wrappers.DataForAITelemetry) error { + called = true + return nil + }, + }) + cmd.SetOut(io.Discard) + cmd.SetArgs(append([]string{"ai", "--type", "authentication", "--status", "success"}, tc.args...)) + + assert.NilError(t, cmd.Execute()) + assert.Assert(t, !called, "authentication telemetry should be skipped") + assert.Equal(t, viper.GetString(params.SessionIDConfigKey), "existing-session") + }) + } +} + func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} execCmdNilAssertion( diff --git a/internal/wrappers/utils/utils.go b/internal/wrappers/utils/utils.go index 36691431c..b48b70bc8 100644 --- a/internal/wrappers/utils/utils.go +++ b/internal/wrappers/utils/utils.go @@ -20,6 +20,9 @@ var allowedOptionalKeys = map[string]bool{ "aiProvider": true, "aiAgentSessionId": true, "agent": true, + "agentVersion": true, + "cxPluginVersion": true, + "pluginType": true, "use-gitignore": true, "exclude-git-folder": true, } From 453c1512e69c62af404a8ff2d40b20592cb361ac Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:09:27 +0530 Subject: [PATCH 03/19] AST-195928 - Fix hook telemetry accuracy and latency Signed-off-by: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> --- internal/commands/agenthooks/cx/hooks.go | 3 ++ .../agenthooks/guardrails/secrets/secrets.go | 1 - .../guardrails/secrets/secrets_test.go | 6 ++- internal/commands/ignore_vulnerability.go | 10 ++-- .../ignore_vulnerability_telemetry_test.go | 34 +++++++++++-- internal/commands/telemetry.go | 10 ++-- internal/wrappers/client_test.go | 42 +++++++++++++++ internal/wrappers/telemetry-http.go | 51 ++++++++++++++++--- 8 files changed, 140 insertions(+), 17 deletions(-) diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index f28ea0966..6da2ef53d 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -266,6 +266,9 @@ func promptWorkspaceRoots(raw any) []string { // RegisterGuardrails wires the four guardrail handlers and instantiates the // SCA, KICS, and secret-detection scanners used by the Bash and FileEdit handlers. func RegisterGuardrails(jwt wrappers.JWTWrapper, ff wrappers.FeatureFlagsWrapper, rt wrappers.RealtimeScannerWrapper, tel wrappers.TelemetryWrapper) { + if transport, ok := tel.(*wrappers.TelemetryHTTPWrapper); ok { + tel = transport.ForAgentHooks() + } scaScanner = sca.NewScanner(jwt, ff, rt) scaScanner.Telemetry = tel kicsScanner = kics.NewScanner(jwt, ff) diff --git a/internal/commands/agenthooks/guardrails/secrets/secrets.go b/internal/commands/agenthooks/guardrails/secrets/secrets.go index 3592be718..b3e486527 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets.go @@ -51,7 +51,6 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w newContent, originalContent, ok := proposedContent(ev.FilePath, ev.Changes) if !ok { - findingCount = 1 return true, provenanceTag() + " " + unresolvedEditReason, provenanceTag() + " " + unresolvedEditContext, "" } if newContent == "" { diff --git a/internal/commands/agenthooks/guardrails/secrets/secrets_test.go b/internal/commands/agenthooks/guardrails/secrets/secrets_test.go index c39e6f0d2..2f013edf9 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets_test.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets_test.go @@ -173,7 +173,8 @@ func TestScanFileEdit_BeforeTextNotFound_BlocksInsteadOfSkipping(t *testing.T) { WorkDir: dir, Changes: []agenthooks.FileDiff{{Before: "STALE_TEXT_NOT_ON_DISK", After: "TOKEN=" + sampleSecret}}, } - blocked, reason, context, _ := ScanFileEdit(ev, svc, nil, "Claude") + tel := &recordingTelemetry{} + blocked, reason, context, _ := ScanFileEdit(ev, svc, tel, "Claude") if !blocked { t.Fatal("an edit whose Before text cannot be located should be blocked, not silently dropped and allowed") } @@ -181,6 +182,9 @@ func TestScanFileEdit_BeforeTextNotFound_BlocksInsteadOfSkipping(t *testing.T) { if scanCalled { t.Fatal("should not scan content that silently omits the unresolved edit") } + if len(tel.calls) != 0 { + t.Fatalf("unresolved edit should not emit scan telemetry, got %d events", len(tel.calls)) + } } func TestScanFileEdit_ScanError_FailOpen(t *testing.T) { diff --git a/internal/commands/ignore_vulnerability.go b/internal/commands/ignore_vulnerability.go index d3ed22ddb..3eb84cab1 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -14,8 +14,8 @@ import ( "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" - "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" "github.com/checkmarx/ast-cli/internal/wrappers" + "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" "github.com/checkmarx/ast-cli/internal/wrappers/utils" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -83,12 +83,16 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd } changed := 0 + var addedEntries []any for _, entry := range entries { var ok bool if remove { list, ok, err = ignore.Remove(list, entry) } else { list, ok, err = ignore.Append(list, entry) + if ok { + addedEntries = append(addedEntries, entry) + } } if err != nil { return err @@ -106,8 +110,8 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd if remove { action = "revived" } - if !remove && changed > 0 { - logIgnoreTelemetry(telemetryWrapper, scanType, entries) + if len(addedEntries) > 0 { + logIgnoreTelemetry(telemetryWrapper, scanType, addedEntries) } _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s %d vulnerability(ies); %d entr%s now in %s\n", diff --git a/internal/commands/ignore_vulnerability_telemetry_test.go b/internal/commands/ignore_vulnerability_telemetry_test.go index 8a60c0b1f..ce2b97f6e 100644 --- a/internal/commands/ignore_vulnerability_telemetry_test.go +++ b/internal/commands/ignore_vulnerability_telemetry_test.go @@ -3,6 +3,8 @@ package commands import ( + "io" + "path/filepath" "strings" "testing" @@ -63,7 +65,33 @@ func TestLogIgnoreTelemetry_CarriesIDsAndNeverTheSecret(t *testing.T) { } } +func TestIgnoreTelemetryOnlyReportsNewBatchEntries(t *testing.T) { + const existing = `{"PackageManager":"npm","PackageName":"existing","PackageVersion":"1.0.0"}` + const added = `{"PackageManager":"npm","PackageName":"added","PackageVersion":"2.0.0"}` + path := filepath.Join(t.TempDir(), "ignore.json") + var events []*wrappers.DataForAITelemetry + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + events = append(events, data) + return nil + }} + for _, payload := range []string{existing, "[" + existing + "," + added + "]"} { + cmd := NewIgnoreVulnerabilityCommand(telemetry) + cmd.SetOut(io.Discard) + cmd.SetArgs([]string{"--scan-type", "oss", "--data", payload, "--ignored-file-path", path}) + if err := cmd.Execute(); err != nil { + t.Fatal(err) + } + } + if len(events) != 2 { + t.Fatalf("got %d ignore events, want 2", len(events)) + } + if attrs := events[1].EventAttributes; attrs == nil || (*attrs)["vulnerabilityId"] != "added@2.0.0" { + t.Fatalf("mixed batch should report only the new entry, got %v", attrs) + } +} + func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { + const agentSessionID = "agent-session" t.Setenv("CX_AGENT_VERSION", "env-version") for _, key := range []string{"aiProvider", "agent", "aiAgentSessionId", "agentVersion", "cxPluginVersion", "pluginType"} { previous := utils.GetOptionalParam(key) @@ -72,7 +100,7 @@ func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { key := params.OptionalFlagsKey previous := viper.Get(key) t.Cleanup(func() { viper.Set(key, previous) }) - viper.Set(key, "aiProvider=Codex;agent=Codex-cli;aiAgentSessionId=agent-session;agentVersion=1.2.3;cxPluginVersion=2.3.4;pluginType=CLI") + viper.Set(key, "aiProvider=Codex;agent=Codex-cli;aiAgentSessionId="+agentSessionID+";agentVersion=1.2.3;cxPluginVersion=2.3.4;pluginType=CLI") if err := extractOptionalFlags(&cobra.Command{}); err != nil { t.Fatal(err) } @@ -84,11 +112,11 @@ func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { }} logIgnoreTelemetry(tel, "asca", nil) if sent == nil || sent.AIProvider != "Codex" || sent.Agent != "Codex-cli" || - sent.AiAgentSessionId != "agent-session" || sent.AgentVersion != "1.2.3" || + sent.AiAgentSessionId != agentSessionID || sent.AgentVersion != "1.2.3" || sent.CxPluginVersion != "2.3.4" || sent.PluginType != "CLI" { t.Fatalf("unexpected ignore telemetry: %+v", sent) } - if sent.EventAttributes == nil || (*sent.EventAttributes)["aiAgentSessionId"] != "agent-session" { + if sent.EventAttributes == nil || (*sent.EventAttributes)["aiAgentSessionId"] != agentSessionID { t.Fatalf("missing session attribute: %+v", sent.EventAttributes) } } diff --git a/internal/commands/telemetry.go b/internal/commands/telemetry.go index 99be5b036..6f2a82728 100644 --- a/internal/commands/telemetry.go +++ b/internal/commands/telemetry.go @@ -12,7 +12,11 @@ import ( "github.com/spf13/viper" ) -const keyValuePairsSplit = 2 +const ( + keyValuePairsSplit = 2 + authenticationEventType = "authentication" + telemetrySuccessStatus = "success" +) func NewTelemetryCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Command { telemetryCmd := &cobra.Command{ @@ -99,7 +103,7 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm eventType, _ := cmd.Flags().GetString("type") subType, _ := cmd.Flags().GetString("sub-type") agent, _ := cmd.Flags().GetString("agent") - if eventType == "authentication" && strings.TrimSpace(agent) == "" { + if eventType == authenticationEventType && strings.TrimSpace(agent) == "" { return nil } engine, _ := cmd.Flags().GetString("engine") @@ -117,7 +121,7 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm uniqueID := wrappers.GetUniqueID() var sessionID string - if eventType == "authentication" && status == "success" { + if eventType == authenticationEventType && status == telemetrySuccessStatus { sessionID = wrappers.GetSessionID() } else { sessionID = viper.GetString(params.SessionIDConfigKey) diff --git a/internal/wrappers/client_test.go b/internal/wrappers/client_test.go index 93610b717..6a072c885 100644 --- a/internal/wrappers/client_test.go +++ b/internal/wrappers/client_test.go @@ -317,6 +317,48 @@ func unsignedJWT(claims map[string]interface{}) string { return header + "." + payload + ".sig" } +func TestAgentHookTelemetryTimesOutWithoutRetrying(t *testing.T) { + requests := make(chan string, 2) + release := make(chan struct{}) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + requests <- req.URL.Path + <-release + w.WriteHeader(http.StatusBadGateway) + })) + t.Cleanup(server.Close) + t.Cleanup(func() { close(release) }) + for key, value := range map[string]any{ + commonParams.IgnoreProxyKey: true, + commonParams.ApikeyOverrideFlag: false, + commonParams.TokenExpirySecondsKey: 300, + } { + previous := viper.Get(key) + t.Cleanup(func() { viper.Set(key, previous) }) + viper.Set(key, value) + } + credentialsMutex.Lock() + previousToken, previousTime := cachedAccessToken, cachedAccessTime + credentialsMutex.Unlock() + t.Cleanup(func() { + credentialsMutex.Lock() + defer credentialsMutex.Unlock() + cachedAccessToken, cachedAccessTime = previousToken, previousTime + }) + writeCredentialsToCache(unsignedJWT(map[string]any{BaseURLKey: server.URL})) + + telemetry := NewHTTPTelemetryAIWrapper("telemetry").ForAgentHooks() + err := telemetry.SendAIDataToLog(&DataForAITelemetry{}) + if !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("expected telemetry request to time out, got %v", err) + } + if got := len(requests); got != 1 { + t.Fatalf("got %d telemetry requests, want 1", got) + } + if path := <-requests; path != "/telemetry/log" { + t.Fatalf("telemetry request used path %q", path) + } +} + // TestExtractFromTokenClaims covers fix #10: the "aud" (and any) claim may be a // string or an array of strings. The array form must not panic. func TestExtractFromTokenClaims(t *testing.T) { diff --git a/internal/wrappers/telemetry-http.go b/internal/wrappers/telemetry-http.go index 03f8ae5f6..10a3ad365 100644 --- a/internal/wrappers/telemetry-http.go +++ b/internal/wrappers/telemetry-http.go @@ -3,7 +3,6 @@ package wrappers import ( "bytes" "encoding/json" - "fmt" "net/http" commonParams "github.com/checkmarx/ast-cli/internal/params" @@ -11,8 +10,11 @@ import ( "github.com/spf13/viper" ) +const agentHookTelemetryTimeoutSeconds = 1 + type TelemetryHTTPWrapper struct { - path string + path string + agentHooks bool } func NewHTTPTelemetryAIWrapper(path string) *TelemetryHTTPWrapper { @@ -21,17 +23,28 @@ func NewHTTPTelemetryAIWrapper(path string) *TelemetryHTTPWrapper { } } +// ForAgentHooks returns a copy with a short timeout and no retries. +func (r *TelemetryHTTPWrapper) ForAgentHooks() *TelemetryHTTPWrapper { + return &TelemetryHTTPWrapper{path: r.path, agentHooks: true} +} + func (r *TelemetryHTTPWrapper) SendAIDataToLog(data *DataForAITelemetry) error { - clientTimeout := viper.GetUint(commonParams.ClientTimeoutKey) jsonBytes, err := json.Marshal(data) if err != nil { return err } - fn := func() (*http.Response, error) { - return SendHTTPRequestWithJSONContentType(http.MethodPost, fmt.Sprint(r.path, "/log"), bytes.NewBuffer(jsonBytes), true, clientTimeout) + path := r.path + "/log" + var resp *http.Response + if r.agentHooks { + resp, err = sendHookTelemetry(path, jsonBytes) + } else { + clientTimeout := viper.GetUint(commonParams.ClientTimeoutKey) + fn := func() (*http.Response, error) { + return SendHTTPRequestWithJSONContentType(http.MethodPost, path, bytes.NewReader(jsonBytes), true, clientTimeout) + } + resp, err = retryHTTPRequest(fn, retryAttempts, retryDelay) } - resp, err := retryHTTPRequest(fn, retryAttempts, retryDelay) if err != nil { return err } @@ -40,6 +53,9 @@ func (r *TelemetryHTTPWrapper) SendAIDataToLog(data *DataForAITelemetry) error { _ = resp.Body.Close() } }() + if r.agentHooks && (resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices) { + return errors.Errorf("failed to log hook telemetry, status code: %s", resp.Status) + } switch resp.StatusCode { case http.StatusBadRequest, http.StatusInternalServerError: return errors.Errorf("Failed to log the data, status code: %s", resp.Status) @@ -48,3 +64,26 @@ func (r *TelemetryHTTPWrapper) SendAIDataToLog(data *DataForAITelemetry) error { } return nil } + +// sendHookTelemetry uses the access token cached by the hook's license check. +// Refreshing a missing token or retrying a slow endpoint would delay the verdict. +func sendHookTelemetry(path string, payload []byte) (*http.Response, error) { + token := getClientCredentialsFromCache(viper.GetInt(commonParams.TokenExpirySecondsKey)) + if token == "" { + return nil, errors.New("no cached access token for hook telemetry") + } + url, err := GetURL(path, token) + if err != nil { + return nil, err + } + req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload)) + if err != nil { + return nil, err + } + setAgentNameAndOrigin(req, false) + req.Header.Set("Content-Type", jsonContentType) + enrichWithOath2Credentials(req, token, bearerFormat) + client := GetClient(agentHookTelemetryTimeoutSeconds) + defer client.CloseIdleConnections() + return client.Do(req) +} From 650f3f2b97677ed3e26407803ad47d8551386e73 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Fri, 27 Nov 2026 20:58:39 +0530 Subject: [PATCH 04/19] AST-195928 - Complete CLI authentication and scanner telemetry --- internal/commands/agenthooks/cx/hooks.go | 12 ++- internal/commands/agenthooks/cx/hooks_test.go | 16 ++- .../agenthooks/guardrails/asca/asca.go | 6 +- .../agenthooks/guardrails/asca/asca_test.go | 4 +- .../agenthooks/guardrails/kics/kics.go | 8 +- .../agenthooks/guardrails/secrets/secrets.go | 6 +- .../agenthooks/hooktelemetry/hooktelemetry.go | 57 ++++++----- .../hooktelemetry/hooktelemetry_test.go | 31 ++++-- internal/commands/agenthooks/sca/sca.go | 13 ++- .../agenthooks/sca/telemetry_ids_test.go | 19 ++-- internal/commands/auth.go | 19 ++-- internal/commands/auth_login.go | 98 ++++++++++++++++--- internal/commands/auth_login_test.go | 91 +++++++++++++++++ internal/commands/ignore_vulnerability.go | 12 +-- .../ignore_vulnerability_telemetry_test.go | 10 +- internal/wrappers/client.go | 24 +++++ internal/wrappers/client_test.go | 36 +++++++ 17 files changed, 366 insertions(+), 96 deletions(-) diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index 6da2ef53d..ad004dd9c 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -21,8 +21,7 @@ import ( "github.com/checkmarx/ast-cli/internal/wrappers" ) -// canonical per-engine labels for the session summary (normalizes the legacy SCA/Oss split used by -// the per-event remediation telemetry; ASCA already uses "Asca"). +// Canonical per-engine labels for the session summary. const ( engineAsca = "Asca" engineSca = "Sca" @@ -90,7 +89,7 @@ func cxBeforeToolCall(ev agenthooks.ToolCallEvent) agenthooks.ToolVerdict { sid := sessionIDFromToolCall(&ev) if finding, remediation, severity := scaScanner.CheckBashInstall(ev.Command, ev.WorkDir, agent, sid); finding != "" && !belowThreshold(ev.Agent, severity) { sessiontally.Add(sid, engineSca, 1, 1) - logRemediationTelemetry(agent, "SCA", severity, sid, ev.WorkDir) + logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, sid, ev.WorkDir) return agenthooks.DenyWithContext(finding, remediation) } } @@ -164,7 +163,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { for _, diff := range ev.Changes { if finding, remediation, severity := scaScanner.CheckManifestEdit(ev.FilePath, fullAfterContent(ev.FilePath, diff), ev.WorkDir, agent, ev.SessionID); finding != "" && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineSca, 1, 1) - logRemediationTelemetry(agent, "Oss", severity, ev.SessionID, ev.WorkDir) + logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, ev.SessionID, ev.WorkDir) return agenthooks.RejectEditWithContext(finding, remediation) } } @@ -294,12 +293,13 @@ func RegisterPassThrough() { // logRemediationTelemetry sends telemetry when remediation context is delivered to the agent. func logRemediationTelemetry(agent, engine, severity, sessionID, workDir string) { + ids, count := hooktelemetry.TakeRemediationFindings() if telemetryWrapper == nil { return } attrs := wrappers.EventAttributes{"remediationMode": hooktelemetry.RemediationModeSelfHealing} - if ids := hooktelemetry.TakeFindingIDs(); ids != "" { + if ids != "" { attrs["vulnerabilityId"] = ids } if sessionID != "" { @@ -313,6 +313,8 @@ func logRemediationTelemetry(agent, engine, severity, sessionID, workDir string) UniqueID: wrappers.GetUniqueID(), Type: "hooks-remediate", SubType: "fixWithAIAssist", + StatusResult: "Remediation instructions delivered.", + TotalCount: count, ProblemSeverity: severity, AiAgentSessionId: sessionID, EventAttributes: &attrs, diff --git a/internal/commands/agenthooks/cx/hooks_test.go b/internal/commands/agenthooks/cx/hooks_test.go index be395fab5..edf8a833a 100644 --- a/internal/commands/agenthooks/cx/hooks_test.go +++ b/internal/commands/agenthooks/cx/hooks_test.go @@ -20,6 +20,7 @@ import ( "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/kics" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/secrets" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/sca" "github.com/checkmarx/ast-cli/internal/services/realtimeengine" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" @@ -222,8 +223,8 @@ func TestCxBeforeToolCall_SCAFinding_DeniesWithContext(t *testing.T) { if len(tel.calls) != 1 { t.Fatalf("expected 1 telemetry call, got %d", len(tel.calls)) } - if tel.calls[0].Engine != "SCA" { - t.Errorf("Engine = %q, want SCA", tel.calls[0].Engine) + if tel.calls[0].Engine != "oss" || tel.calls[0].ScanType != "oss" { + t.Errorf("Engine/ScanType = %q/%q, want oss/oss", tel.calls[0].Engine, tel.calls[0].ScanType) } } @@ -414,8 +415,8 @@ func TestCxBeforeFileEdit_SCAManifest_RejectsWithContext(t *testing.T) { if len(tel.calls) != 1 { t.Fatalf("expected 1 telemetry call, got %d", len(tel.calls)) } - if tel.calls[0].Engine != "Oss" { - t.Errorf("Engine = %q, want Oss", tel.calls[0].Engine) + if tel.calls[0].Engine != "oss" || tel.calls[0].ScanType != "oss" { + t.Errorf("Engine/ScanType = %q/%q, want oss/oss", tel.calls[0].Engine, tel.calls[0].ScanType) } } @@ -634,6 +635,8 @@ func TestLogRemediationTelemetry(t *testing.T) { t.Run("sends_payload", func(t *testing.T) { tel := &recordingTelemetry{} telemetryWrapper = tel + const ruleID = "1027" + hooktelemetry.SetRemediationFindings([]string{ruleID, ruleID}, 2) logRemediationTelemetry("Cursor", "Asca", "Critical", "sess-9", "") if len(tel.calls) != 1 { t.Fatalf("got %d calls, want 1", len(tel.calls)) @@ -648,6 +651,11 @@ func TestLogRemediationTelemetry(t *testing.T) { if got.Type != telemetryTypeHooksRemediate || got.SubType != "fixWithAIAssist" { t.Errorf("Type/SubType = %q/%q", got.Type, got.SubType) } + assert.Equal(t, 2, got.TotalCount) + assert.Equal(t, ruleID, (*got.EventAttributes)["vulnerabilityId"]) + if got.StatusResult != "Remediation instructions delivered." { + t.Errorf("StatusResult = %q", got.StatusResult) + } if got.ProblemSeverity != "Critical" || got.AiAgentSessionId != "sess-9" { t.Errorf("severity/session = %q/%q", got.ProblemSeverity, got.AiAgentSessionId) } diff --git a/internal/commands/agenthooks/guardrails/asca/asca.go b/internal/commands/agenthooks/guardrails/asca/asca.go index 411373bf1..85b114b1d 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca.go +++ b/internal/commands/agenthooks/guardrails/asca/asca.go @@ -122,8 +122,8 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme for i := range newFindings { ids = append(ids, strconv.FormatUint(uint64(newFindings[i].RuleID), 10)) } - hooktelemetry.SetFindingIDs(ids) r, c := formatFindings(ev.FilePath, newFindings, ev.WorkDir, agent, ev.SessionID) + hooktelemetry.SetRemediationFindings(ids, len(newFindings)) return true, r, c, highestSeverity(newFindings) } @@ -204,6 +204,7 @@ func logASCATelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session return } + severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) telemetryData := &wrappers.DataForAITelemetry{ Agent: hostenv.TelemetryAgent(agent), AIProvider: agent, @@ -213,7 +214,8 @@ func logASCATelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session Type: "hooks-detect", SubType: "scan", ScanType: "asca", - StatusResult: hooktelemetry.SeverityCounts(severities), + ProblemSeverity: severity, + StatusResult: statusResult, AiAgentSessionId: sessionID, } hooktelemetry.Enrich(telemetryData, workDir) diff --git a/internal/commands/agenthooks/guardrails/asca/asca_test.go b/internal/commands/agenthooks/guardrails/asca/asca_test.go index 42484e16c..932f56952 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca_test.go +++ b/internal/commands/agenthooks/guardrails/asca/asca_test.go @@ -592,10 +592,12 @@ func TestLogASCATelemetry_WithFindings_Sends(t *testing.T) { return nil }, } - logASCATelemetry(telemetry, "Claude", "", "", 2, nil) + logASCATelemetry(telemetry, "Claude", "", "", 2, []string{"HIGH", "Low"}) assert.NotNil(t, captured) assert.Equal(t, "Asca", captured.Engine) assert.Equal(t, 2, captured.TotalCount) + assert.Equal(t, "High", captured.ProblemSeverity) + assert.Equal(t, "Critical=0,High=1,Medium=0,Low=1,Info=0", captured.StatusResult) assert.Equal(t, "Claude", captured.AIProvider) } diff --git a/internal/commands/agenthooks/guardrails/kics/kics.go b/internal/commands/agenthooks/guardrails/kics/kics.go index 7cdee78e0..a0ff66668 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics.go +++ b/internal/commands/agenthooks/guardrails/kics/kics.go @@ -109,8 +109,8 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w if len(newResults) == 0 { return false, "", "", "", "" } - hooktelemetry.SetFindingIDs(resultIDs(newResults)) r, c := formatFindings(ev.FilePath, newResults, ev.Agent, ev.WorkDir, ev.SessionID) + hooktelemetry.SetRemediationFindings(resultIDs(newResults), len(newResults)) return true, r, c, "", highestSeverity(newResults) } @@ -137,8 +137,8 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w return false, "", "", "", "" } - hooktelemetry.SetFindingIDs(resultIDs(newFindings)) r, c := formatFindings(ev.FilePath, newFindings, ev.Agent, ev.WorkDir, ev.SessionID) + hooktelemetry.SetRemediationFindings(resultIDs(newFindings), len(newFindings)) return true, r, c, "", highestSeverity(newFindings) } @@ -197,6 +197,7 @@ func logKicsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session return } + severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) telemetryData := &wrappers.DataForAITelemetry{ Agent: hostenv.TelemetryAgent(agent), AIProvider: agent, @@ -206,7 +207,8 @@ func logKicsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session Type: "hooks-detect", SubType: "scan", ScanType: "iac", - StatusResult: hooktelemetry.SeverityCounts(severities), + ProblemSeverity: severity, + StatusResult: statusResult, AiAgentSessionId: sessionID, } hooktelemetry.Enrich(telemetryData, workDir) diff --git a/internal/commands/agenthooks/guardrails/secrets/secrets.go b/internal/commands/agenthooks/guardrails/secrets/secrets.go index b3e486527..105d9f3bf 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets.go @@ -95,8 +95,8 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w for i := range findings { ids = append(ids, findings[i].Title) } - hooktelemetry.SetFindingIDs(ids) r, c := formatFindings(ev.FilePath, findings, ev.Agent, ev.WorkDir, ev.SessionID) + hooktelemetry.SetRemediationFindings(ids, len(findings)) return true, r, c, highestSeverity(findings) } @@ -132,6 +132,7 @@ func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sess return } + severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) telemetryData := &wrappers.DataForAITelemetry{ Agent: hostenv.TelemetryAgent(agent), AIProvider: agent, @@ -141,7 +142,8 @@ func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sess Type: "hooks-detect", SubType: "scan", ScanType: "secrets", - StatusResult: hooktelemetry.SeverityCounts(severities), + ProblemSeverity: severity, + StatusResult: statusResult, AiAgentSessionId: sessionID, } hooktelemetry.Enrich(telemetryData, workDir) diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go index 9aa17b739..20ded1409 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -22,6 +22,8 @@ import ( const ( // StatusSuccess is the status sent for an event whose operation completed. StatusSuccess = "success" + // EngineOSS identifies dependency scan, remediation, and ignore events. + EngineOSS = "oss" // RemediationModeSelfHealing marks a remediation driven by a hook deny (the agent fixes its own edit). RemediationModeSelfHealing = "SelfHealing" @@ -39,15 +41,13 @@ var ( repoURLMu sync.Mutex repoURLCache = map[string]string{} - findingIDsMu sync.Mutex - findingIDs []string + remediationMu sync.Mutex + remediationIDs string + remediationCount int ) -// SetFindingIDs records the IDs (CVE, rule id, ...) of the findings a guardrail is about to deny, so -// the remediation event for that deny can report them as eventAttributes.vulnerabilityId. `cx hooks` -// handles one hook event per process, so the last recorded set always belongs to the current deny. -// Empty IDs and duplicates are dropped; at most maxFindingIDs are kept. -func SetFindingIDs(ids []string) { +// FormatFindingIDs returns a comma-separated list of up to maxFindingIDs unique, nonempty IDs. +func FormatFindingIDs(ids []string) string { seen := make(map[string]bool, len(ids)) kept := make([]string, 0, len(ids)) for _, id := range ids { @@ -61,19 +61,26 @@ func SetFindingIDs(ids []string) { break } } - findingIDsMu.Lock() - findingIDs = kept - findingIDsMu.Unlock() + return strings.Join(kept, ",") } -// TakeFindingIDs returns the IDs recorded by SetFindingIDs, comma-separated ("" when none), and clears -// them so a later event in the same process never reuses them. -func TakeFindingIDs() string { - findingIDsMu.Lock() - defer findingIDsMu.Unlock() - ids := strings.Join(findingIDs, ",") - findingIDs = nil - return ids +// SetRemediationFindings records the findings covered by the current hook's remediation instructions. +// The count includes every covered finding even if its ID is missing, repeated, or omitted by the cap. +func SetRemediationFindings(ids []string, count int) { + formattedIDs := FormatFindingIDs(ids) + remediationMu.Lock() + defer remediationMu.Unlock() + remediationIDs = formattedIDs + remediationCount = count +} + +// TakeRemediationFindings returns and clears the recorded IDs and count. +func TakeRemediationFindings() (ids string, count int) { + remediationMu.Lock() + defer remediationMu.Unlock() + ids, count = remediationIDs, remediationCount + remediationIDs, remediationCount = "", 0 + return ids, count } // ignoreFlagValue keeps values safe in the optional flag parser and in generated shell commands. @@ -115,9 +122,9 @@ func Enrich(data *wrappers.DataForAITelemetry, workDir string) { } } -// SeverityCounts renders severities as "Critical=n,High=n,Medium=n,Low=n,Info=n", the scan event's -// statusResult. Severities outside the known five are not counted. -func SeverityCounts(severities []string) string { +// ScanSeveritySummary returns the highest detected severity and the counts for statusResult. +// Severities outside the known five are not counted. +func ScanSeveritySummary(severities []string) (highest, statusResult string) { counts := make(map[string]int, len(severityOrder)) for _, s := range severities { for _, known := range severityOrder { @@ -129,9 +136,13 @@ func SeverityCounts(severities []string) string { } parts := make([]string, 0, len(severityOrder)) for _, s := range severityOrder { - parts = append(parts, fmt.Sprintf("%s=%d", s, counts[s])) + count := counts[s] + if highest == "" && count > 0 { + highest = s + } + parts = append(parts, fmt.Sprintf("%s=%d", s, count)) } - return strings.Join(parts, ",") + return highest, strings.Join(parts, ",") } // RepoURL returns the credential-free "origin" URL of the git repository containing workDir, or "" when diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go index 3f50acf6b..03299a462 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -44,10 +44,14 @@ func TestSanitizeRepoURL(t *testing.T) { } } -func TestSeverityCounts(t *testing.T) { - got := SeverityCounts([]string{"High", "critical", "High", "Low", "unknown"}) - assert.Equal(t, got, "Critical=1,High=2,Medium=0,Low=1,Info=0") - assert.Equal(t, SeverityCounts(nil), "Critical=0,High=0,Medium=0,Low=0,Info=0") +func TestScanSeveritySummary(t *testing.T) { + highest, counts := ScanSeveritySummary([]string{"High", "critical", "High", "Low", "unknown"}) + assert.Equal(t, highest, "Critical") + assert.Equal(t, counts, "Critical=1,High=2,Medium=0,Low=1,Info=0") + + highest, counts = ScanSeveritySummary(nil) + assert.Equal(t, highest, "") + assert.Equal(t, counts, "Critical=0,High=0,Medium=0,Low=0,Info=0") } func TestEnrich(t *testing.T) { @@ -75,17 +79,24 @@ func TestEnrich(t *testing.T) { assert.Equal(t, data.Status, StatusSuccess) } -func TestFindingIDs(t *testing.T) { - SetFindingIDs([]string{"CVE-1", " ", "CVE-2", "CVE-1"}) - assert.Equal(t, TakeFindingIDs(), "CVE-1,CVE-2", "blanks and duplicates are dropped") - assert.Equal(t, TakeFindingIDs(), "", "taking clears the recorded ids") +func TestRemediationFindings(t *testing.T) { + SetRemediationFindings([]string{"CVE-1", " ", "CVE-2", "CVE-1"}, 4) + ids, count := TakeRemediationFindings() + assert.Equal(t, ids, "CVE-1,CVE-2") + assert.Equal(t, count, 4) + + ids, count = TakeRemediationFindings() + assert.Equal(t, ids, "") + assert.Equal(t, count, 0) many := make([]string, 0, maxFindingIDs+5) for i := 0; i < maxFindingIDs+5; i++ { many = append(many, "id"+string(rune('a'+i))) } - SetFindingIDs(many) - assert.Equal(t, len(strings.Split(TakeFindingIDs(), ",")), maxFindingIDs, "capped at maxFindingIDs") + SetRemediationFindings(many, len(many)) + ids, count = TakeRemediationFindings() + assert.Equal(t, len(strings.Split(ids, ",")), maxFindingIDs) + assert.Equal(t, count, len(many)) } func TestEnrichToleratesMissingContext(t *testing.T) { diff --git a/internal/commands/agenthooks/sca/sca.go b/internal/commands/agenthooks/sca/sca.go index ede379346..5c2bdb190 100644 --- a/internal/commands/agenthooks/sca/sca.go +++ b/internal/commands/agenthooks/sca/sca.go @@ -80,14 +80,15 @@ func (s *Scanner) CheckManifestEdit(filePath string, afterContent []byte, workDi func denyFrom(malicious, vulnerable []ossrealtime.OssPackage, workDir, agent, sessionID string) (finding, remediation, severity string) { tag := provenanceTag(agent) if len(malicious) > 0 { - hooktelemetry.SetFindingIDs(maliciousPackageIDs(malicious)) f, r := DenyMalicious(malicious, agent) + hooktelemetry.SetRemediationFindings(maliciousPackageIDs(malicious), len(malicious)) return tag + " " + f, tag + " " + r, statusMalicious } vulnerable = aboveThreshold(vulnerable) if len(vulnerable) > 0 { - hooktelemetry.SetFindingIDs(vulnerableCVEs(vulnerable)) f, r := DenyVulnerable(vulnerable, workDir, agent, sessionID) + ids := vulnerableCVEs(vulnerable) + hooktelemetry.SetRemediationFindings(ids, len(ids)) return tag + " " + f, tag + " " + r, highestVulnSeverity(vulnerable) } return "", "", "" @@ -112,16 +113,18 @@ func (s *Scanner) logScan(agent, sessionID, workDir string, malicious, vulnerabl if len(severities) == 0 { return } + severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) data := &wrappers.DataForAITelemetry{ Agent: hostenv.TelemetryAgent(agent), AIProvider: agent, - Engine: "Oss", + Engine: hooktelemetry.EngineOSS, TotalCount: len(severities), UniqueID: wrappers.GetUniqueID(), Type: "hooks-detect", SubType: "scan", - ScanType: "oss", - StatusResult: hooktelemetry.SeverityCounts(severities), + ScanType: hooktelemetry.EngineOSS, + ProblemSeverity: severity, + StatusResult: statusResult, AiAgentSessionId: sessionID, } hooktelemetry.Enrich(data, workDir) diff --git a/internal/commands/agenthooks/sca/telemetry_ids_test.go b/internal/commands/agenthooks/sca/telemetry_ids_test.go index daf833536..7e99736b7 100644 --- a/internal/commands/agenthooks/sca/telemetry_ids_test.go +++ b/internal/commands/agenthooks/sca/telemetry_ids_test.go @@ -11,19 +11,19 @@ import ( "github.com/checkmarx/ast-cli/internal/wrappers/mock" ) -func TestDenyFrom_RecordsVulnerabilityIDs(t *testing.T) { +func TestDenyFrom_RecordsRemediationFindings(t *testing.T) { old := BelowThreshold t.Cleanup(func() { BelowThreshold = old }) - BelowThreshold = nil - hooktelemetry.TakeFindingIDs() // start clean + BelowThreshold = func(severity string) bool { return severity == "Medium" } + hooktelemetry.TakeRemediationFindings() // start clean vuln := []ossrealtime.OssPackage{{PackageName: "lodash", PackageVersion: "4.17.20", Vulnerabilities: []ossrealtime.Vulnerability{{CVE: "CVE-2021-23337", Severity: "High"}, {CVE: "CVE-2020-28500", Severity: "Medium"}}}} if f, _, _ := denyFrom(nil, vuln, "", "Claude", "s"); f == "" { t.Fatal("vulnerable package must deny") } - if got := hooktelemetry.TakeFindingIDs(); got != "CVE-2021-23337,CVE-2020-28500" { - t.Fatalf("vulnerable deny must record its CVEs, got %q", got) + if ids, count := hooktelemetry.TakeRemediationFindings(); ids != "CVE-2021-23337" || count != 1 { + t.Fatalf("vulnerable deny must record CVEs above the threshold, got %q with count %d", ids, count) } mal := []ossrealtime.OssPackage{ @@ -33,8 +33,8 @@ func TestDenyFrom_RecordsVulnerabilityIDs(t *testing.T) { if f, _, _ := denyFrom(mal, nil, "", "Claude", "s"); f == "" { t.Fatal("malicious package must deny") } - if got := hooktelemetry.TakeFindingIDs(); got != "evil-pkg@1.0.0,no-version" { - t.Fatalf("malicious deny must record name@version, got %q", got) + if ids, count := hooktelemetry.TakeRemediationFindings(); ids != "evil-pkg@1.0.0,no-version" || count != 2 { + t.Fatalf("malicious deny must record name@version, got %q with count %d", ids, count) } } @@ -58,9 +58,12 @@ func TestLogScan_SendsDetectedCounts(t *testing.T) { t.Fatalf("expected one scan event, got %d", len(sent)) } d := sent[0] - if d.Type != "hooks-detect" || d.Engine != "Oss" || d.Agent != "Claude-cli" || d.TotalCount != 3 { + if d.Type != "hooks-detect" || d.Engine != "oss" || d.ScanType != "oss" || d.Agent != "Claude-cli" || d.TotalCount != 3 { t.Fatalf("unexpected event: %+v", d) } + if d.ProblemSeverity != "Critical" { + t.Fatalf("unexpected problemSeverity %q", d.ProblemSeverity) + } if d.StatusResult != "Critical=1,High=1,Medium=0,Low=1,Info=0" { t.Fatalf("unexpected statusResult %q", d.StatusResult) } diff --git a/internal/commands/auth.go b/internal/commands/auth.go index 613d3065f..4502c265e 100644 --- a/internal/commands/auth.go +++ b/internal/commands/auth.go @@ -114,7 +114,7 @@ func NewAuthCommand(authWrapper wrappers.AuthWrapper, telemetryWrapper wrappers. }, RunE: validLogin(telemetryWrapper), } - authCmd.AddCommand(createClientCmd, validLoginCmd, newAuthLoginCommand(), newAuthLogoutCommand()) + authCmd.AddCommand(createClientCmd, validLoginCmd, newAuthLoginCommand(telemetryWrapper), newAuthLogoutCommand()) return authCmd } @@ -136,19 +136,18 @@ func validLogin(telemetryWrapper wrappers.TelemetryWrapper) func(cmd *cobra.Comm authWrapper.SetPath(viper.GetString(params.ScansPathKey)) err := authWrapper.ValidateLogin() - // Send telemetry only for CLI agents 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()) - } + // telemetryErr := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{ + // UniqueID: uniqueID, + // Type: "authentication", + // SubType: "authentication", + // }) + // if telemetryErr != nil { + // logger.PrintIfVerbose("Failed to send telemetry data: " + telemetryErr.Error()) + // } } } diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index da85c0695..6f70683c9 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "os" + "strings" "github.com/MakeNowJust/heredoc" "github.com/checkmarx/ast-cli/internal/credentialstore" @@ -23,20 +24,27 @@ const defaultLoginClientID = "ide-integration" // configFilePerm: owner-only, since the file holds a long-lived refresh token. const configFilePerm = 0o600 -func newAuthLoginCommand() *cobra.Command { +func newAuthLoginCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Command { + if transport, ok := telemetryWrapper.(*wrappers.TelemetryHTTPWrapper); ok { + telemetryWrapper = transport.ForAgentHooks() + } cmd := &cobra.Command{ Use: "login", - Short: "Authenticate to Checkmarx One via browser-based OAuth", + Short: "Authenticate to Checkmarx One via browser-based OAuth or API key", Long: "Opens the default browser, walks the user through the Checkmarx One IAM login " + "(including MFA), and stores the resulting refresh token securely in the OS keyring " + "under the api-key credential slot — the same slot cx configure writes to, so every " + "other command picks it up automatically.\n\n" + - "Requires --tenant and --base-uri (or --base-auth-uri). Pass them as flags, or run " + - "cx auth login with none and it prompts for the missing ones like cx configure.", + "Browser sign-in requires --tenant and --base-uri (or --base-auth-uri). Pass them as flags, or run " + + "cx auth login with none and it prompts for the missing ones like cx configure.\n\n" + + "Use --apikey for API-key sign-in. A successful login with a supported --agent sends authentication telemetry.", Example: heredoc.Doc(` # With flags — stores the refresh token in the OS keyring $ cx auth login --base-uri https://.ast.checkmarx.net --tenant my-tenant + # Sign in with an API key + $ cx auth login --apikey --agent=copilot-cli + # No flags — prompts for base URI / tenant, then opens the browser $ cx auth login @@ -48,14 +56,28 @@ func newAuthLoginCommand() *cobra.Command { https://checkmarx.com/resource/documents/en/34965-68627-auth.html `), }, - RunE: runAuthLogin, + RunE: func(cmd *cobra.Command, _ []string) error { + return runAuthLogin(cmd, telemetryWrapper) + }, } cmd.Flags().Int(params.LoginPortFlag, 0, params.LoginPortFlagUsage) cmd.Flags().Bool(params.LoginNoBrowserFlag, false, params.LoginNoBrowserFlagUsage) return cmd } -func runAuthLogin(cmd *cobra.Command, _ []string) error { +func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper) error { + if cmd.Flags().Changed(params.AstAPIKeyFlag) { + apiKey, err := cmd.Flags().GetString(params.AstAPIKeyFlag) + if err != nil || strings.TrimSpace(apiKey) == "" { + return errors.New("--apikey requires a nonempty API key") + } + accessToken, err := wrappers.ExchangeLoginAPIKey(apiKey) + if err != nil { + return err + } + return completeAuthLogin(cmd, telemetryWrapper, apiKey, accessToken, "APIKey") + } + // Prompt for connection details like cx configure when none were passed as // flags, so a re-login can still review/change base-uri / tenant. if !connectionFlagsProvided(cmd) { @@ -64,9 +86,10 @@ func runAuthLogin(cmd *cobra.Command, _ []string) error { // Force explicit --tenant/--base-* to win over the realm in any stored key. // Set after the prompt so the prompt's write isn't persisted here. + previousOverride := viper.GetBool(params.ApikeyOverrideFlag) viper.Set(params.ApikeyOverrideFlag, true) - realmURL, err := wrappers.GetRealmURL() + viper.Set(params.ApikeyOverrideFlag, previousOverride) if err != nil { return errors.Wrap(err, "failed to resolve IAM realm URL") } @@ -84,7 +107,57 @@ func runAuthLogin(cmd *cobra.Command, _ []string) error { return err } - return persistLogin(cmd, tokens.RefreshToken) + return completeAuthLogin(cmd, telemetryWrapper, tokens.RefreshToken, tokens.AccessToken, "OAuth") +} + +func loginTelemetryAgent(cmd *cobra.Command) string { + if !cmd.Flags().Changed(params.AgentFlag) { + return "" + } + agent, _ := cmd.Flags().GetString(params.AgentFlag) + switch strings.ToLower(strings.TrimSpace(agent)) { + case "copilot-cli": + return "Copilot-cli" + case "claude-cli": + return "Claude-cli" + case "cursor-cli": + return "Cursor-cli" + case "gemini-cli": + return "Gemini-cli" + case "codex-cli": + return "Codex-cli" + default: + return "" + } +} + +func completeAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, credential, accessToken, authMethod string) error { + if err := persistLogin(cmd, credential); err != nil { + return err + } + agent := loginTelemetryAgent(cmd) + if telemetryWrapper == nil || agent == "" || accessToken == "" || os.Getenv("CX_TELEMETRY_DISABLE") == "1" { + return nil + } + wrappers.CacheAuthenticatedAccessToken(accessToken) + attrs := wrappers.EventAttributes{"authMethod": authMethod} + data := &wrappers.DataForAITelemetry{ + Type: authenticationEventType, + SubType: authenticationEventType, + Status: telemetrySuccessStatus, + StatusResult: "Authentication successful.", + Agent: agent, + AgentVersion: strings.TrimSpace(os.Getenv(params.AgentVersionEnv)), + CxPluginVersion: strings.TrimSpace(os.Getenv(params.CxPluginVersionEnv)), + PluginType: "CLI", + UniqueID: wrappers.GetUniqueID(), + SessionID: wrappers.GetSessionID(), + EventAttributes: &attrs, + } + if err := telemetryWrapper.SendAIDataToLog(data); err != nil { + logger.PrintIfVerbose("Failed to send authentication telemetry: " + err.Error()) + } + return nil } // connectionFlagsProvided reports whether any connection detail was passed as a flag. @@ -94,11 +167,10 @@ func connectionFlagsProvided(cmd *cobra.Command) bool { cmd.Flags().Changed(params.TenantFlag) } -// persistLogin stores the refresh token under the api-key credential slot; -// never echoes it to stdout. -func persistLogin(cmd *cobra.Command, refreshToken string) error { - if err := credentialstore.Default().Store(context.Background(), credentialstore.CredentialAPIKey, refreshToken); err != nil { - return errors.Wrap(err, "failed to save refresh token") +// persistLogin stores the credential without echoing it to stdout. +func persistLogin(cmd *cobra.Command, credential string) error { + if err := credentialstore.Default().Store(context.Background(), credentialstore.CredentialAPIKey, credential); err != nil { + return errors.Wrap(err, "failed to save login credential") } if !credentialstore.Default().StoresInConfigFile() { if removeErr := credentialstore.Default().RemoveConfigFileEntry(credentialstore.CredentialAPIKey); removeErr != nil { diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index cdb514cce..0a87024b7 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -4,12 +4,14 @@ package commands import ( "bytes" + "errors" "path/filepath" "strings" "testing" "github.com/checkmarx/ast-cli/internal/credentialstore" "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/wrappers" "github.com/checkmarx/ast-cli/internal/wrappers/configuration" "github.com/checkmarx/ast-cli/internal/wrappers/mock" @@ -239,3 +241,92 @@ func TestPersistLogin_PrintsSuccessMessage(t *testing.T) { t.Errorf("expected success message in output, got: %q", output) } } + +func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { + const credential = "test-login-credential" + cases := []struct { + name string + agent *string + want string + }{ + {name: "omitted"}, + {name: "blank", agent: testLoginAgent(" ")}, + {name: "default", agent: testLoginAgent("ASTCLI")}, + {name: "other", agent: testLoginAgent("Copilot-VSCode")}, + {name: "copilot", agent: testLoginAgent(" Copilot-CLI "), want: "Copilot-cli"}, + {name: "claude", agent: testLoginAgent("claude-cli"), want: "Claude-cli"}, + {name: "cursor", agent: testLoginAgent("cursor-cli"), want: "Cursor-cli"}, + {name: "gemini", agent: testLoginAgent("gemini-cli"), want: "Gemini-cli"}, + {name: "codex", agent: testLoginAgent("codex-cli"), want: "Codex-cli"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + withTempConfigDir(t) + store := swapCredentialResolver(t) + t.Setenv("CX_TELEMETRY_DISABLE", "") + oldExpiry, oldSession := viper.Get(params.TokenExpirySecondsKey), viper.Get(params.SessionIDConfigKey) + t.Cleanup(func() { + viper.Set(params.TokenExpirySecondsKey, oldExpiry) + viper.Set(params.SessionIDConfigKey, oldSession) + wrappers.InvalidateAccessTokenCache() + }) + viper.Set(params.TokenExpirySecondsKey, 120) + viper.Set(params.SessionIDConfigKey, "") + cmd, _, _ := newBufferedCmd() + cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") + if tc.agent != nil { + if err := cmd.Flags().Set(params.AgentFlag, *tc.agent); err != nil { + t.Fatal(err) + } + } + calls := 0 + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + calls++ + if store.Store[credentialstore.CredentialAPIKey] != credential { + t.Fatal("telemetry sent before credential was saved") + } + if data.Agent != tc.want || data.Type != authenticationEventType || + data.SubType != authenticationEventType || data.Status != telemetrySuccessStatus || + data.SessionID == "" || (*data.EventAttributes)["authMethod"] != "OAuth" { + t.Fatalf("unexpected authentication telemetry: %+v", data) + } + return errors.New("telemetry unavailable") + }} + if err := completeAuthLogin(cmd, telemetry, credential, "test-access-token", "OAuth"); err != nil { + t.Fatal(err) + } + if tc.want == "" { + if calls != 0 || viper.GetString(params.SessionIDConfigKey) != "" { + t.Fatal("non-eligible login sent telemetry or generated a session ID") + } + } else if calls != 1 || readYamlKey(t, params.SessionIDConfigKey) == "" { + t.Fatal("eligible login should send one event and persist a session ID") + } + if store.Store[credentialstore.CredentialAPIKey] != credential { + t.Fatal("login credential was not saved") + } + }) + } +} + +func testLoginAgent(agent string) *string { + return &agent +} + +func TestRunAuthLogin_InvalidAPIKeyKeepsCredential(t *testing.T) { + withTempConfigDir(t) + store := swapCredentialResolver(t) + const oldCredential = "existing-credential" + store.Store[credentialstore.CredentialAPIKey] = oldCredential + cmd, _, _ := newBufferedCmd() + cmd.Flags().String(params.AstAPIKeyFlag, "", "") + if err := cmd.Flags().Set(params.AstAPIKeyFlag, "not-a-token"); err != nil { + t.Fatal(err) + } + if err := runAuthLogin(cmd, nil); err == nil { + t.Fatal("expected API-key verification to fail") + } + if store.Store[credentialstore.CredentialAPIKey] != oldCredential { + t.Fatal("invalid API key replaced the existing credential") + } +} diff --git a/internal/commands/ignore_vulnerability.go b/internal/commands/ignore_vulnerability.go index 3eb84cab1..611d6de55 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -166,8 +166,7 @@ func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType str for _, e := range entries { ids = append(ids, ignoreEntryID(e)) } - hooktelemetry.SetFindingIDs(ids) - if v := hooktelemetry.TakeFindingIDs(); v != "" { + if v := hooktelemetry.FormatFindingIDs(ids); v != "" { attrs["vulnerabilityId"] = v } if sessionID != "" { @@ -228,14 +227,11 @@ func ignoreEntryID(entry any) string { } } -// engineName maps a --scan-type value to the capitalized engine label used in telemetry -// (matching the convention in agenthooks/cx/hooks.go, e.g. "Oss", "Asca", "Sca"). +// engineName maps a --scan-type value to its telemetry engine label. func engineName(scanType string) string { switch strings.ToLower(strings.TrimSpace(scanType)) { - case ignore.ScanTypeOSS: - return "Oss" - case ignore.ScanTypeSCA: - return "Sca" + case ignore.ScanTypeOSS, ignore.ScanTypeSCA: + return hooktelemetry.EngineOSS case ignore.ScanTypeSecrets: return "Secrets" case ignore.ScanTypeContainers: diff --git a/internal/commands/ignore_vulnerability_telemetry_test.go b/internal/commands/ignore_vulnerability_telemetry_test.go index ce2b97f6e..69dbdaef0 100644 --- a/internal/commands/ignore_vulnerability_telemetry_test.go +++ b/internal/commands/ignore_vulnerability_telemetry_test.go @@ -74,10 +74,11 @@ func TestIgnoreTelemetryOnlyReportsNewBatchEntries(t *testing.T) { events = append(events, data) return nil }} - for _, payload := range []string{existing, "[" + existing + "," + added + "]"} { + scanTypes := []string{"oss", "sca"} + for i, payload := range []string{existing, "[" + existing + "," + added + "]"} { cmd := NewIgnoreVulnerabilityCommand(telemetry) cmd.SetOut(io.Discard) - cmd.SetArgs([]string{"--scan-type", "oss", "--data", payload, "--ignored-file-path", path}) + cmd.SetArgs([]string{"--scan-type", scanTypes[i], "--data", payload, "--ignored-file-path", path}) if err := cmd.Execute(); err != nil { t.Fatal(err) } @@ -85,6 +86,11 @@ func TestIgnoreTelemetryOnlyReportsNewBatchEntries(t *testing.T) { if len(events) != 2 { t.Fatalf("got %d ignore events, want 2", len(events)) } + for _, event := range events { + if event.Engine != "oss" || event.ScanType != "oss" { + t.Fatalf("Engine/ScanType = %q/%q, want oss/oss", event.Engine, event.ScanType) + } + } if attrs := events[1].EventAttributes; attrs == nil || (*attrs)["vulnerabilityId"] != "added@2.0.0" { t.Fatalf("mixed batch should report only the new entry, got %v", attrs) } diff --git a/internal/wrappers/client.go b/internal/wrappers/client.go index abfc0293b..0c44c8aa6 100644 --- a/internal/wrappers/client.go +++ b/internal/wrappers/client.go @@ -705,6 +705,30 @@ func InvalidateAccessTokenCache() { cachedAccessTime = time.Time{} } +// ExchangeLoginAPIKey verifies the supplied key with IAM without using the access-token cache. +func ExchangeLoginAPIKey(apiKey string) (string, error) { + logger.RegisterSensitiveValue(apiKey) + realmURL, err := ExtractFromTokenClaims(apiKey, audienceClaimKey) + if err != nil { + return "", err + } + parsedRealm, err := url.Parse(realmURL) + if err != nil || parsedRealm.Hostname() == "" || parsedRealm.User != nil || + (parsedRealm.Scheme != "https" && parsedRealm.Scheme != "http") || parsedRealm.RawQuery != "" || parsedRealm.Fragment != "" { + return "", errors.New("API key has an invalid IAM realm URL") + } + accessToken, err := getNewToken(getAPIKeyPayload(apiKey), strings.TrimRight(realmURL, "/")+"/"+BaseAuthURLSuffix) + if err == nil && accessToken == "" { + return "", errors.New("API key sign-in returned no access token") + } + return accessToken, err +} + +// CacheAuthenticatedAccessToken reuses the token from a successful login for same-process requests. +func CacheAuthenticatedAccessToken(accessToken string) { + writeCredentialsToCache(accessToken) +} + func writeCredentialsToCache(accessToken string) { credentialsMutex.Lock() defer credentialsMutex.Unlock() diff --git a/internal/wrappers/client_test.go b/internal/wrappers/client_test.go index 6a072c885..0e58a1503 100644 --- a/internal/wrappers/client_test.go +++ b/internal/wrappers/client_test.go @@ -612,3 +612,39 @@ func TestGetClient_UnrecognizedProxyAuthTypeIsLoggedWhenVerbose(t *testing.T) { } assert.NotContains(t, logBuffer.String(), "falling back to basic") } + +func TestExchangeLoginAPIKey_VerifiesSuppliedCredential(t *testing.T) { + var apiKey string + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + calls++ + if req.URL.Path != "/auth/realms/organization/"+BaseAuthURLSuffix { + t.Errorf("unexpected request path: %s", req.URL.Path) + } + if err := req.ParseForm(); err != nil { + t.Error(err) + } + if req.Form.Get("refresh_token") != apiKey { + t.Error("request did not use the supplied API key") + } + if calls == 1 { + w.WriteHeader(http.StatusUnauthorized) + return + } + _, _ = w.Write([]byte(`{"access_token":"verified-access-token"}`)) + })) + defer server.Close() + apiKey = unsignedJWT(map[string]interface{}{"aud": server.URL + "/auth/realms/organization"}) + SetCachedAccessTokenForTest("different-cached-token") + t.Cleanup(InvalidateAccessTokenCache) + + if token, err := ExchangeLoginAPIKey(apiKey); err == nil || token != "" { + t.Fatal("IAM rejected the supplied key, so login must fail") + } + if token, err := ExchangeLoginAPIKey(apiKey); err != nil || token != "verified-access-token" { + t.Fatalf("IAM accepted the supplied key, got error %v", err) + } + if calls != 2 { + t.Fatalf("expected two fresh token requests, got %d", calls) + } +} From 8da49a87cfac2a253dda2d5876ee6b8d05c83804 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Mon, 30 Nov 2026 10:54:52 +0530 Subject: [PATCH 05/19] AST-195928 - Report Dev Assist CLI operation failures --- internal/commands/agenthooks/cx/hooks.go | 18 +++++--- internal/commands/agenthooks/cx/hooks_test.go | 26 +++++++++--- .../agenthooks/guardrails/asca/asca.go | 12 ++++-- .../agenthooks/guardrails/kics/kics.go | 4 ++ .../agenthooks/guardrails/secrets/secrets.go | 2 + .../agenthooks/hooktelemetry/hooktelemetry.go | 42 +++++++++++++++++++ .../hooktelemetry/hooktelemetry_test.go | 23 ++++++++++ internal/commands/agenthooks/sca/sca.go | 2 + internal/commands/auth_login.go | 42 ++++++++++++++----- internal/commands/auth_login_test.go | 37 +++++++++++++++- internal/commands/ignore_vulnerability.go | 22 +++++++++- .../ignore_vulnerability_telemetry_test.go | 25 +++++++++++ 12 files changed, 228 insertions(+), 27 deletions(-) diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index ad004dd9c..3278dc2e6 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -89,7 +89,7 @@ func cxBeforeToolCall(ev agenthooks.ToolCallEvent) agenthooks.ToolVerdict { sid := sessionIDFromToolCall(&ev) if finding, remediation, severity := scaScanner.CheckBashInstall(ev.Command, ev.WorkDir, agent, sid); finding != "" && !belowThreshold(ev.Agent, severity) { sessiontally.Add(sid, engineSca, 1, 1) - logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, sid, ev.WorkDir) + logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, sid, ev.WorkDir, remediation) return agenthooks.DenyWithContext(finding, remediation) } } @@ -145,7 +145,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { if scannerOn(ev.Agent, scannerconfig.ASCA) { if blocked, reason, context, severity := asca.ScanFileEdit(&ev, telemetryWrapper, agent); blocked && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineAsca, 1, 1) - logRemediationTelemetry(agent, "Asca", severity, ev.SessionID, ev.WorkDir) + logRemediationTelemetry(agent, "Asca", severity, ev.SessionID, ev.WorkDir, context) return agenthooks.RejectEditWithContext(reason, context) } } @@ -154,7 +154,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { blocked, reason, context, note, severity := kics.ScanFileEdit(&ev, kicsScanner, telemetryWrapper, agent) if blocked && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineKics, 1, 1) - logRemediationTelemetry(agent, "IaC", severity, ev.SessionID, ev.WorkDir) + logRemediationTelemetry(agent, "IaC", severity, ev.SessionID, ev.WorkDir, context) return agenthooks.RejectEditWithContext(reason, context) } kicsNote = note @@ -163,7 +163,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { for _, diff := range ev.Changes { if finding, remediation, severity := scaScanner.CheckManifestEdit(ev.FilePath, fullAfterContent(ev.FilePath, diff), ev.WorkDir, agent, ev.SessionID); finding != "" && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineSca, 1, 1) - logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, ev.SessionID, ev.WorkDir) + logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, ev.SessionID, ev.WorkDir, remediation) return agenthooks.RejectEditWithContext(finding, remediation) } } @@ -171,7 +171,7 @@ func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { if secretsScanner != nil && secretsApply(ev.Agent) && scannerOn(ev.Agent, scannerconfig.Secrets) { if blocked, reason, context, severity := secrets.ScanFileEdit(&ev, secretsScanner, telemetryWrapper, agent); blocked && !belowThreshold(ev.Agent, severity) { sessiontally.Add(ev.SessionID, engineSecrets, 1, 1) - logRemediationTelemetry(agent, "Secrets", severity, ev.SessionID, ev.WorkDir) + logRemediationTelemetry(agent, "Secrets", severity, ev.SessionID, ev.WorkDir, context) return agenthooks.RejectEditWithContext(reason, context) } } @@ -292,7 +292,7 @@ func RegisterPassThrough() { } // logRemediationTelemetry sends telemetry when remediation context is delivered to the agent. -func logRemediationTelemetry(agent, engine, severity, sessionID, workDir string) { +func logRemediationTelemetry(agent, engine, severity, sessionID, workDir, guidance string) { ids, count := hooktelemetry.TakeRemediationFindings() if telemetryWrapper == nil { return @@ -319,6 +319,12 @@ func logRemediationTelemetry(agent, engine, severity, sessionID, workDir string) AiAgentSessionId: sessionID, EventAttributes: &attrs, } + if strings.TrimSpace(guidance) == "" { + telemetryData.Status = hooktelemetry.StatusFailure + telemetryData.StatusResult = "Remediation instructions were unavailable." + telemetryData.TotalCount = 0 + attrs["reasonCode"] = "remediation_instructions_missing" + } hooktelemetry.Enrich(telemetryData, workDir) if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { diff --git a/internal/commands/agenthooks/cx/hooks_test.go b/internal/commands/agenthooks/cx/hooks_test.go index edf8a833a..2dcc3e95c 100644 --- a/internal/commands/agenthooks/cx/hooks_test.go +++ b/internal/commands/agenthooks/cx/hooks_test.go @@ -629,7 +629,7 @@ func TestLogRemediationTelemetry(t *testing.T) { t.Run("nil_wrapper_noop", func(t *testing.T) { telemetryWrapper = nil - logRemediationTelemetry("Claude", "SCA", "High", "s1", "") // must not panic + logRemediationTelemetry("Claude", "SCA", "High", "s1", "", "guidance") // must not panic }) t.Run("sends_payload", func(t *testing.T) { @@ -637,7 +637,7 @@ func TestLogRemediationTelemetry(t *testing.T) { telemetryWrapper = tel const ruleID = "1027" hooktelemetry.SetRemediationFindings([]string{ruleID, ruleID}, 2) - logRemediationTelemetry("Cursor", "Asca", "Critical", "sess-9", "") + logRemediationTelemetry("Cursor", "Asca", "Critical", "sess-9", "", "guidance") if len(tel.calls) != 1 { t.Fatalf("got %d calls, want 1", len(tel.calls)) } @@ -664,7 +664,7 @@ func TestLogRemediationTelemetry(t *testing.T) { t.Run("send_error_fail_open", func(t *testing.T) { tel := &recordingTelemetry{err: os.ErrPermission} telemetryWrapper = tel - logRemediationTelemetry("Claude", "SCA", "High", "s2", "") // must not panic + logRemediationTelemetry("Claude", "SCA", "High", "s2", "", "guidance") // must not panic if len(tel.calls) != 1 { t.Fatalf("got %d calls, want 1", len(tel.calls)) } @@ -866,7 +866,7 @@ func TestLogRemediationTelemetry_NilWrapper_NoOp(t *testing.T) { telemetryWrapper = nil assert.NotPanics(t, func() { - logRemediationTelemetry("Claude", "SCA", "finding", "remediation", "") + logRemediationTelemetry("Claude", "SCA", "finding", "remediation", "", "guidance") }) } @@ -876,7 +876,7 @@ func TestLogRemediationTelemetry_WithWrapper_Sends(t *testing.T) { telemetryWrapper = mock.TelemetryMockWrapper{} assert.NotPanics(t, func() { - logRemediationTelemetry("Claude", "SCA", "finding", "remediation", "") + logRemediationTelemetry("Claude", "SCA", "finding", "remediation", "", "guidance") }) } @@ -972,3 +972,19 @@ func TestCodexApplyPatch_KICSFinding_DeniesEndToEnd(t *testing.T) { assert.Contains(t, out, `"permissionDecision":"deny"`) assert.Contains(t, out, "KICS") } + +func TestLogRemediationTelemetry_MissingGuidance(t *testing.T) { + resetHookGlobals(t) + tel := &recordingTelemetry{} + telemetryWrapper = tel + hooktelemetry.SetRemediationFindings([]string{"rule-id"}, 1) + logRemediationTelemetry("Copilot", "Asca", "High", "session", "", "") + if len(tel.calls) != 1 { + t.Fatalf("got %d events, want 1", len(tel.calls)) + } + event := tel.calls[0] + if event.Status != "failure" || event.TotalCount != 0 || + (*event.EventAttributes)["reasonCode"] != "remediation_instructions_missing" { + t.Fatalf("unexpected remediation failure: %+v", event) + } +} diff --git a/internal/commands/agenthooks/guardrails/asca/asca.go b/internal/commands/agenthooks/guardrails/asca/asca.go index 85b114b1d..a56511c98 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca.go +++ b/internal/commands/agenthooks/guardrails/asca/asca.go @@ -1,6 +1,7 @@ package asca import ( + "errors" "os" "path/filepath" "strconv" @@ -82,16 +83,18 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme // Stage and scan the proposed (new) content stagedNew, cleanupNew, err := stageForScan(ev.FilePath, newContent, ev.SessionID, ev.Agent) if err != nil { + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "Asca", ev.SessionID, ev.WorkDir, err) return false, "", "", "" } defer cleanupNew() ascaParams.FilePath = stagedNew newResult, err := services.CreateASCAScanRequest(ascaParams, wrapperParams) - if err != nil || newResult == nil { - return false, "", "", "" + if err == nil && (newResult == nil || newResult.Error != nil) { + err = errors.New("ASCA did not return successful results") } - if newResult.Error != nil { + if err != nil { + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "Asca", ev.SessionID, ev.WorkDir, err) return false, "", "", "" } if len(newResult.ScanDetails) == 0 { @@ -104,7 +107,8 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme var err error newFindings, err = deltaFindings(ev, originalContent, ascaParams, wrapperParams, newResult.ScanDetails) if err != nil { - newFindings = nil + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "Asca", ev.SessionID, ev.WorkDir, err) + return false, "", "", "" } } // Telemetry reports what was DETECTED; the threshold only decides what is denied. diff --git a/internal/commands/agenthooks/guardrails/kics/kics.go b/internal/commands/agenthooks/guardrails/kics/kics.go index a0ff66668..b60999642 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics.go +++ b/internal/commands/agenthooks/guardrails/kics/kics.go @@ -85,6 +85,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w // Stage and scan the proposed (new) content stagedNew, cleanupNew, err := stageForScan(ev.FilePath, newContent, ev.SessionID) if err != nil { + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "IaC", ev.SessionID, ev.WorkDir, err) return false, "", "", skippedNote(ev.FilePath, err), "" } defer cleanupNew() @@ -94,6 +95,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w if err != nil { // Fail open: Docker unavailable, image pull failure, feature flag disabled, etc. logger.PrintfIfVerbose("kics guardrail: scan of proposed content failed, failing open: %v", err) + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "IaC", ev.SessionID, ev.WorkDir, err) return false, "", "", skippedNote(ev.FilePath, err), "" } if len(newResults) == 0 { @@ -117,6 +119,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w // Delta: scan original content and find only newly introduced findings stagedOrig, cleanupOrig, err := stageForScan(ev.FilePath, originalContent, ev.SessionID) if err != nil { + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "IaC", ev.SessionID, ev.WorkDir, err) return false, "", "", skippedNote(ev.FilePath, err), "" } defer cleanupOrig() @@ -125,6 +128,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w if err != nil { // Fail open on original scan error logger.PrintfIfVerbose("kics guardrail: scan of original content failed, failing open: %v", err) + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "IaC", ev.SessionID, ev.WorkDir, err) return false, "", "", skippedNote(ev.FilePath, err), "" } diff --git a/internal/commands/agenthooks/guardrails/secrets/secrets.go b/internal/commands/agenthooks/guardrails/secrets/secrets.go index 105d9f3bf..09152f8b8 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets.go @@ -60,6 +60,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w ignoreFilePath := existingIgnoreFilePath(ev.WorkDir) newResults, err := svc.scan(ev.FilePath, newContent, ignoreFilePath) if err != nil { + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "Secrets", ev.SessionID, ev.WorkDir, err) logger.PrintfIfVerbose("secrets guardrail: scan of proposed content failed, failing open: %v", err) return false, "", "", "" } @@ -71,6 +72,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w if originalContent != "" { origResults, origErr := svc.scan(ev.FilePath, originalContent, ignoreFilePath) if origErr != nil { + hooktelemetry.LogScanFailure(telemetryWrapper, agent, "Secrets", ev.SessionID, ev.WorkDir, origErr) logger.PrintfIfVerbose("secrets guardrail: scan of original content failed, failing open: %v", origErr) return false, "", "", "" } diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go index 20ded1409..20d98d304 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -5,7 +5,10 @@ package hooktelemetry import ( + "context" + "errors" "fmt" + "net" "os" "regexp" "strings" @@ -13,8 +16,11 @@ import ( gogit "github.com/go-git/go-git/v5" "github.com/spf13/viper" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" + errorconstants "github.com/checkmarx/ast-cli/internal/constants/errors" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/wrappers" ) @@ -22,6 +28,8 @@ import ( const ( // StatusSuccess is the status sent for an event whose operation completed. StatusSuccess = "success" + // StatusFailure is the status of an operation that could not complete. + StatusFailure = "failure" // EngineOSS identifies dependency scan, remediation, and ignore events. EngineOSS = "oss" // RemediationModeSelfHealing marks a remediation driven by a hook deny (the agent fixes its own edit). @@ -122,6 +130,40 @@ func Enrich(data *wrappers.DataForAITelemetry, workDir string) { } } +// LogScanFailure reports an attempted scan that did not produce results. V2 scan events can +// carry a failure status without a finding count or severity. +func LogScanFailure(telemetry wrappers.TelemetryWrapper, agent, engine, sessionID, workDir string, err error) { + if telemetry == nil || err == nil { + return + } + // Realtime services represent tenant feature switches and missing licenses as errors. + // These represent skipped scans in the hook. + if strings.Contains(err.Error(), errorconstants.RealtimeEngineNotAvailable) || + strings.Contains(err.Error(), errorconstants.ErrMissingAIFeatureLicense) { + return + } + reason := "scanner_error" + var networkError net.Error + if errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || + (errors.As(err, &networkError) && networkError.Timeout()) { + reason = "scanner_timeout" + } + attrs := wrappers.EventAttributes{"reasonCode": reason} + if sessionID != "" { + attrs["aiAgentSessionId"] = sessionID + } + data := &wrappers.DataForAITelemetry{ + Type: "hooks-detect", SubType: "scan", APIVersion: "v2", + AIProvider: agent, Agent: hostenv.TelemetryAgent(agent), + Engine: engine, ScanType: strings.ToLower(engine), + Status: StatusFailure, StatusResult: "Scanner did not complete.", + UniqueID: wrappers.GetUniqueID(), AiAgentSessionId: sessionID, + EventAttributes: &attrs, + } + Enrich(data, workDir) + _ = telemetry.SendAIDataToLog(data) +} + // ScanSeveritySummary returns the highest detected severity and the counts for statusResult. // Severities outside the known five are not counted. func ScanSeveritySummary(severities []string) (highest, statusResult string) { diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go index 03299a462..6739f7fee 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -3,6 +3,8 @@ package hooktelemetry import ( + "context" + "errors" "os" "strings" "testing" @@ -12,8 +14,10 @@ import ( "github.com/spf13/viper" "gotest.tools/assert" + errorconstants "github.com/checkmarx/ast-cli/internal/constants/errors" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/wrappers" + "github.com/checkmarx/ast-cli/internal/wrappers/mock" ) // testRemotePassword is the password embedded in a credentialed remote URL fixture. It is read from the @@ -122,3 +126,22 @@ func TestIgnoreFlags(t *testing.T) { assert.Equal(t, IgnoreFlags("Cursor", "invalid session"), " --optional-flags \"aiProvider=Cursor;agent=Cursor-cli;pluginType=CLI\"") assert.Equal(t, IgnoreFlags("", ""), "") } + +func TestLogScanFailure(t *testing.T) { + var events []*wrappers.DataForAITelemetry + tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + events = append(events, data) + return nil + }} + LogScanFailure(tel, "Copilot", "Secrets", "session", "", context.DeadlineExceeded) + LogScanFailure(tel, "Copilot", "Secrets", "session", "", errors.New(errorconstants.RealtimeEngineNotAvailable)) + assert.Equal(t, len(events), 1) + event := events[0] + assert.Equal(t, event.Type, "hooks-detect") + assert.Equal(t, event.Status, StatusFailure) + assert.Equal(t, event.APIVersion, "v2") + assert.Equal(t, event.TotalCount, 0) + assert.Equal(t, event.ProblemSeverity, "") + assert.Equal(t, event.Agent, "Copilot-cli") + assert.Equal(t, (*event.EventAttributes)["reasonCode"], "scanner_timeout") +} diff --git a/internal/commands/agenthooks/sca/sca.go b/internal/commands/agenthooks/sca/sca.go index 5c2bdb190..9f7627bf5 100644 --- a/internal/commands/agenthooks/sca/sca.go +++ b/internal/commands/agenthooks/sca/sca.go @@ -25,6 +25,7 @@ func (s *Scanner) CheckBashInstall(command, workDir, agent, sessionID string) (f for _, req := range ParseInstall(command) { mal, vuln, err := s.scanRequest(req, workDir) if err != nil { + hooktelemetry.LogScanFailure(s.Telemetry, agent, hooktelemetry.EngineOSS, sessionID, workDir, err) continue } s.logScan(agent, sessionID, workDir, mal, vuln) @@ -68,6 +69,7 @@ func (s *Scanner) CheckManifestEdit(filePath string, afterContent []byte, workDi } mal, vuln, err := s.ScanPackages(format, added) if err != nil { + hooktelemetry.LogScanFailure(s.Telemetry, agent, hooktelemetry.EngineOSS, sessionID, workDir, err) return "", "", "" } s.logScan(agent, sessionID, workDir, mal, vuln) diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index 6f70683c9..024d0b737 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/MakeNowJust/heredoc" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/credentialstore" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/params" @@ -65,8 +66,17 @@ func newAuthLoginCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Comm return cmd } -func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper) error { +func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper) (resultErr error) { + method, failureReason := "OAuth", "browser_authentication_failed" + defer func() { + if resultErr != nil { + if agent := loginTelemetryAgent(cmd); agent != "" { + logger.PrintfIfVerbose("Login failure: agent=%s authMethod=%s reasonCode=%s", agent, method, failureReason) + } + } + }() if cmd.Flags().Changed(params.AstAPIKeyFlag) { + method, failureReason = "APIKey", "api_key_authentication_failed" apiKey, err := cmd.Flags().GetString(params.AstAPIKeyFlag) if err != nil || strings.TrimSpace(apiKey) == "" { return errors.New("--apikey requires a nonempty API key") @@ -75,7 +85,8 @@ func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper if err != nil { return err } - return completeAuthLogin(cmd, telemetryWrapper, apiKey, accessToken, "APIKey") + failureReason = loginCredentialSaveFailed + return completeAuthLogin(cmd, telemetryWrapper, apiKey, accessToken, method) } // Prompt for connection details like cx configure when none were passed as @@ -107,7 +118,8 @@ func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper return err } - return completeAuthLogin(cmd, telemetryWrapper, tokens.RefreshToken, tokens.AccessToken, "OAuth") + failureReason = loginCredentialSaveFailed + return completeAuthLogin(cmd, telemetryWrapper, tokens.RefreshToken, tokens.AccessToken, method) } func loginTelemetryAgent(cmd *cobra.Command) string { @@ -131,13 +143,18 @@ func loginTelemetryAgent(cmd *cobra.Command) string { } } +const loginCredentialSaveFailed = "credential_save_failed" + func completeAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, credential, accessToken, authMethod string) error { - if err := persistLogin(cmd, credential); err != nil { - return err - } + err := persistLogin(cmd, credential) + sendLoginTelemetry(cmd, telemetryWrapper, accessToken, authMethod, err != nil) + return err +} + +func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, accessToken, authMethod string, saveFailed bool) { agent := loginTelemetryAgent(cmd) - if telemetryWrapper == nil || agent == "" || accessToken == "" || os.Getenv("CX_TELEMETRY_DISABLE") == "1" { - return nil + if telemetryWrapper == nil || agent == "" || accessToken == "" { + return } wrappers.CacheAuthenticatedAccessToken(accessToken) attrs := wrappers.EventAttributes{"authMethod": authMethod} @@ -151,13 +168,18 @@ func completeAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWr CxPluginVersion: strings.TrimSpace(os.Getenv(params.CxPluginVersionEnv)), PluginType: "CLI", UniqueID: wrappers.GetUniqueID(), - SessionID: wrappers.GetSessionID(), EventAttributes: &attrs, } + if saveFailed { + data.Status = hooktelemetry.StatusFailure + data.StatusResult = "Authenticated but could not save the credential." + attrs["reasonCode"] = loginCredentialSaveFailed + } else { + data.SessionID = wrappers.GetSessionID() + } if err := telemetryWrapper.SendAIDataToLog(data); err != nil { logger.PrintIfVerbose("Failed to send authentication telemetry: " + err.Error()) } - return nil } // connectionFlagsProvided reports whether any connection detail was passed as a flag. diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index 0a87024b7..e84e16ae0 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -263,7 +263,6 @@ func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { t.Run(tc.name, func(t *testing.T) { withTempConfigDir(t) store := swapCredentialResolver(t) - t.Setenv("CX_TELEMETRY_DISABLE", "") oldExpiry, oldSession := viper.Get(params.TokenExpirySecondsKey), viper.Get(params.SessionIDConfigKey) t.Cleanup(func() { viper.Set(params.TokenExpirySecondsKey, oldExpiry) @@ -330,3 +329,39 @@ func TestRunAuthLogin_InvalidAPIKeyKeepsCredential(t *testing.T) { t.Fatal("invalid API key replaced the existing credential") } } + +func TestCompleteAuthLogin_CredentialSaveFailure(t *testing.T) { + path := filepath.Join(withTempConfigDir(t), "checkmarxcli.yaml") + store := mock.NewCredentialStoreMock() + store.SetErr = errors.New("mock credential store failure") + credentialstore.SetDefaultResolverForTest(credentialstore.NewResolver(path, credentialstore.PolicyRequired, store)) + t.Cleanup(credentialstore.ResetForTest) + oldExpiry, oldSession := viper.Get(params.TokenExpirySecondsKey), viper.Get(params.SessionIDConfigKey) + t.Cleanup(func() { + viper.Set(params.TokenExpirySecondsKey, oldExpiry) + viper.Set(params.SessionIDConfigKey, oldSession) + wrappers.InvalidateAccessTokenCache() + }) + viper.Set(params.TokenExpirySecondsKey, 120) + viper.Set(params.SessionIDConfigKey, "previous-session") + cmd, _, _ := newBufferedCmd() + cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") + if err := cmd.Flags().Set(params.AgentFlag, "copilot-cli"); err != nil { + t.Fatal(err) + } + var event *wrappers.DataForAITelemetry + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + event = data + return nil + }} + if err := completeAuthLogin(cmd, telemetry, "test-credential", "test-access-token", "APIKey"); err == nil { + t.Fatal("expected credential save to fail") + } + if event == nil || event.Status != "failure" || event.SessionID != "" || + (*event.EventAttributes)["reasonCode"] != loginCredentialSaveFailed { + t.Fatalf("unexpected login failure: %+v", event) + } + if got := viper.GetString(params.SessionIDConfigKey); got != "previous-session" { + t.Fatalf("existing session changed: %q", got) + } +} diff --git a/internal/commands/ignore_vulnerability.go b/internal/commands/ignore_vulnerability.go index 611d6de55..31d8617a6 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -57,7 +57,7 @@ func NewIgnoreVulnerabilityCommand(telemetryWrapper wrappers.TelemetryWrapper) * } func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd *cobra.Command, args []string) error { - return func(cmd *cobra.Command, _ []string) error { + return func(cmd *cobra.Command, _ []string) (resultErr error) { scanType, _ := cmd.Flags().GetString(commonParams.ScanTypeFlag) dataArg, _ := cmd.Flags().GetString(commonParams.IgnoreDataFlag) remove, _ := cmd.Flags().GetBool(commonParams.IgnoreRemoveFlag) @@ -67,6 +67,13 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd return errors.Errorf("invalid --scan-type %q; expected one of: oss, sca, secrets, containers, iac, asca", scanType) } + failureReason := "invalid_ignore_input" + defer func() { + if resultErr != nil && !remove && utils.GetOptionalParam("agent") != "" { + sendIgnoreTelemetry(telemetryWrapper, scanType, nil, failureReason) + } + }() + data, err := readIgnoreData(cmd, dataArg) if err != nil { return err @@ -77,11 +84,13 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd return err } + failureReason = "ignore_read_failed" list, err := ignore.Load(ignoredFilePath) if err != nil { return errors.Wrapf(err, "failed to read ignore file %s", ignoredFilePath) } + failureReason = "ignore_update_failed" changed := 0 var addedEntries []any for _, entry := range entries { @@ -102,6 +111,7 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd } } + failureReason = "ignore_write_failed" if err = ignore.Save(ignoredFilePath, list); err != nil { return errors.Wrapf(err, "failed to write ignore file %s", ignoredFilePath) } @@ -152,6 +162,10 @@ func plural(n int) string { // logIgnoreTelemetry sends telemetry when an agent ignores a finding via the realtime ignore file. func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType string, entries []any) { + sendIgnoreTelemetry(telemetryWrapper, scanType, entries, "") +} + +func sendIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType string, entries []any, failureReason string) { if telemetryWrapper == nil { return } @@ -180,8 +194,14 @@ func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType str UniqueID: wrappers.GetUniqueID(), Type: "hooks-ignore", SubType: "ignorePackage", + TotalCount: len(entries), AiAgentSessionId: sessionID, } + if failureReason != "" { + attrs["reasonCode"] = failureReason + telemetryData.Status = hooktelemetry.StatusFailure + telemetryData.StatusResult = "Unable to save the requested ignore." + } if len(attrs) > 0 { telemetryData.EventAttributes = &attrs } diff --git a/internal/commands/ignore_vulnerability_telemetry_test.go b/internal/commands/ignore_vulnerability_telemetry_test.go index 69dbdaef0..d6efef3ed 100644 --- a/internal/commands/ignore_vulnerability_telemetry_test.go +++ b/internal/commands/ignore_vulnerability_telemetry_test.go @@ -126,3 +126,28 @@ func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { t.Fatalf("missing session attribute: %+v", sent.EventAttributes) } } + +func TestIgnoreTelemetry_AttributedInvalidFinding(t *testing.T) { + previous := utils.GetOptionalParam("agent") + t.Cleanup(func() { _ = utils.SetOptionalParam("agent", previous) }) + if err := utils.SetOptionalParam("agent", "Copilot-cli"); err != nil { + t.Fatal(err) + } + var event *wrappers.DataForAITelemetry + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + event = data + return nil + }} + cmd := NewIgnoreVulnerabilityCommand(telemetry) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs([]string{"--scan-type", "sca", "--data", "not-json", "--ignored-file-path", filepath.Join(t.TempDir(), "ignore.json")}) + if err := cmd.Execute(); err == nil { + t.Fatal("invalid finding should fail the command") + } + if event == nil || event.Type != "hooks-ignore" || event.Agent != "Copilot-cli" || + event.Engine != "oss" || event.Status != "failure" || event.TotalCount != 0 || + (*event.EventAttributes)["reasonCode"] != "invalid_ignore_input" { + t.Fatalf("unexpected ignore failure: %+v", event) + } +} From 2a799a99971a2096fa8163f8d6a962a843c0f3fa Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Mon, 30 Nov 2026 12:30:55 +0530 Subject: [PATCH 06/19] AST-195928 Normalize OSS remediation severity --- internal/commands/agenthooks/sca/sca.go | 14 +++++--------- .../commands/agenthooks/sca/threshold_test.go | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/internal/commands/agenthooks/sca/sca.go b/internal/commands/agenthooks/sca/sca.go index 9f7627bf5..d05206de8 100644 --- a/internal/commands/agenthooks/sca/sca.go +++ b/internal/commands/agenthooks/sca/sca.go @@ -183,16 +183,12 @@ func aboveThreshold(pkgs []ossrealtime.OssPackage) []ossrealtime.OssPackage { // highestVulnSeverity returns the highest CVE severity across all vulnerable packages. func highestVulnSeverity(pkgs []ossrealtime.OssPackage) string { - rank := map[string]int{"Critical": 4, "High": 3, "Medium": 2, "Low": 1} - best := "" - bestRank := -1 + var severities []string for i := range pkgs { - for _, v := range pkgs[i].Vulnerabilities { - if r, ok := rank[v.Severity]; ok && r > bestRank { - bestRank = r - best = v.Severity - } + for _, vulnerability := range pkgs[i].Vulnerabilities { + severities = append(severities, vulnerability.Severity) } } - return best + highest, _ := hooktelemetry.ScanSeveritySummary(severities) + return highest } diff --git a/internal/commands/agenthooks/sca/threshold_test.go b/internal/commands/agenthooks/sca/threshold_test.go index 320a45521..79a694635 100644 --- a/internal/commands/agenthooks/sca/threshold_test.go +++ b/internal/commands/agenthooks/sca/threshold_test.go @@ -30,6 +30,24 @@ func TestAboveThreshold_DropsLowCVEsAndEmptyPackages(t *testing.T) { } } +func TestHighestVulnSeverityUsesScanSeverityRules(t *testing.T) { + for _, tc := range []struct { + name string + findings []ossrealtime.Vulnerability + want string + }{ + {name: "info", findings: []ossrealtime.Vulnerability{{Severity: "Info"}}, want: "Info"}, + {name: "mixed case", findings: []ossrealtime.Vulnerability{{Severity: "Medium"}, {Severity: "high"}}, want: "High"}, + } { + t.Run(tc.name, func(t *testing.T) { + packages := []ossrealtime.OssPackage{{Vulnerabilities: tc.findings}} + if got := highestVulnSeverity(packages); got != tc.want { + t.Fatalf("highestVulnSeverity() = %q, want %q", got, tc.want) + } + }) + } +} + func TestDenyFrom_MaliciousIgnoresThreshold(t *testing.T) { old := BelowThreshold t.Cleanup(func() { BelowThreshold = old }) From ef14f03506733c4b753e9782c14d177612cde146 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:53:41 +0530 Subject: [PATCH 07/19] AST-195928 Emit verification telemetry for realtime hook fixes --- internal/commands/root.go | 1 + internal/commands/scan_verification.go | 349 ++++++++++++++++++++ internal/commands/scan_verification_test.go | 234 +++++++++++++ internal/wrappers/utils/utils.go | 3 + 4 files changed, 587 insertions(+) create mode 100644 internal/commands/scan_verification.go create mode 100644 internal/commands/scan_verification_test.go diff --git a/internal/commands/root.go b/internal/commands/root.go index 479c9c026..b42e5c95e 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -211,6 +211,7 @@ func NewAstCLI( realTimeWrapper, tenantWrapper, ) + enableScanVerification(scanCmd, telemetryWrapper) projectCmd := NewProjectCommand(applicationsWrapper, projectsWrapper, groupsWrapper, accessManagementWrapper, featureFlagsWrapper) dastEnvironmentsCmd := dast.NewDastEnvironmentsCommand(dastEnvironmentsWrapper) diff --git a/internal/commands/scan_verification.go b/internal/commands/scan_verification.go new file mode 100644 index 000000000..ff2f4646d --- /dev/null +++ b/internal/commands/scan_verification.go @@ -0,0 +1,349 @@ +package commands + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" + + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" + "github.com/checkmarx/ast-cli/internal/logger" + "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" + "github.com/checkmarx/ast-cli/internal/wrappers" + "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" + "github.com/checkmarx/ast-cli/internal/wrappers/utils" + "github.com/spf13/cobra" +) + +const verifyFindingFlag = "verify-finding" + +func enableScanVerification(scan *cobra.Command, telemetry wrappers.TelemetryWrapper) { + if transport, ok := telemetry.(*wrappers.TelemetryHTTPWrapper); ok { + telemetry = transport.ForAgentHooks() + } + engines := map[string]string{ + "asca": "Asca", "iac-realtime": "IaC", "oss-realtime": hooktelemetry.EngineOSS, "secrets-realtime": "Secrets", + } + for _, cmd := range scan.Commands() { + if engine, ok := engines[cmd.Name()]; ok { + addScanVerification(cmd, engine, telemetry) + } + } +} + +func addScanVerification(cmd *cobra.Command, engine string, telemetry wrappers.TelemetryWrapper) { + cmd.Flags().StringArray(verifyFindingFlag, nil, "Verify a prior Dev Assist hook finding in this realtime re-scan. Repeat for multiple findings") + run := cmd.RunE + cmd.RunE = func(cmd *cobra.Command, args []string) error { + if !cmd.Flags().Changed(verifyFindingFlag) { + return run(cmd, args) + } + agent := loginTelemetryAgent(cmd) + rawAgent, _ := cmd.Flags().GetString(params.AgentFlag) + switch { + case cmd.Flags().Changed(params.AgentFlag) && strings.EqualFold(strings.TrimSpace(rawAgent), "copilot-vscode"): + agent = "Copilot-VSCode" + case agent == "Copilot-cli" && hostenv.InVSCode(): + agent = hostenv.TelemetryAgent("Copilot") + case agent == "": + return fmt.Errorf("--%s requires --agent with a supported Dev Assist hook client", verifyFindingFlag) + } + ignoredPath, _ := cmd.Flags().GetString(params.IgnoredFilePathFlag) + if ignoredPath != "" { + return fmt.Errorf("--%s requires a scan without --%s", verifyFindingFlag, params.IgnoredFilePathFlag) + } + raw, err := cmd.Flags().GetStringArray(verifyFindingFlag) + if err != nil { + return err + } + findings, err := verificationFindings(engine, raw) + if err != nil { + return err + } + + var scanOutput bytes.Buffer + stdout := cmd.OutOrStdout() + cmd.SetOut(io.MultiWriter(stdout, &scanOutput)) + defer cmd.SetOut(stdout) + err = run(cmd, args) + var result any + if err == nil { + result = decodeVerificationResult(engine, scanOutput.Bytes()) + } + reportVerification(cmd, telemetry, agent, engine, findings, result, err) + return err + } +} + +// decodeVerificationResult reads the existing JSON output of the opt-in realtime re-scan. +func decodeVerificationResult(engine string, output []byte) any { + switch engine { + case "Asca": + return decodeVerificationJSON[*grpcs.ScanResult](output) + case "IaC": + return decodeVerificationJSON[[]iacrealtime.IacRealtimeResult](output) + case hooktelemetry.EngineOSS: + return decodeVerificationJSON[*ossrealtime.OssPackageResults](output) + case "Secrets": + return decodeVerificationJSON[[]secretsrealtime.SecretsRealtimeResult](output) + default: + return nil + } +} + +func decodeVerificationJSON[T any](output []byte) any { + var result T + if err := json.Unmarshal(output, &result); err != nil { + return nil + } + return result +} + +func verificationFindings(engine string, raw []string) (map[string]struct{}, error) { + findings := make(map[string]struct{}, len(raw)) + for _, id := range raw { + id = strings.TrimSpace(id) + switch engine { + case "Asca": + rule, err := strconv.ParseUint(id, 10, 32) + if err != nil || rule == 0 { + return nil, fmt.Errorf("--%s requires a positive ASCA rule ID", verifyFindingFlag) + } + id = strconv.FormatUint(rule, 10) + case hooktelemetry.EngineOSS: + separator := strings.LastIndexByte(id, '@') + if separator <= 0 || separator == len(id)-1 { + return nil, fmt.Errorf("--%s requires package-name@CVE or package-name@malicious for OSS", verifyFindingFlag) + } + id = strings.ToLower(id) + } + if id == "" { + return nil, fmt.Errorf("--%s requires the finding identifier or title from the original scan", verifyFindingFlag) + } + findings[id] = struct{}{} + } + if len(findings) == 0 { + return nil, fmt.Errorf("--%s requires at least one finding from the original scan", verifyFindingFlag) + } + return findings, nil +} + +func verificationResults(result any) (map[string]struct{}, map[string]struct{}, bool) { + present := make(map[string]struct{}) + unknownPackages := make(map[string]struct{}) + switch scan := result.(type) { + case *grpcs.ScanResult: + if scan == nil || !scan.Status || scan.Error != nil { + return nil, nil, false + } + for _, finding := range scan.ScanDetails { + if finding.RuleID == 0 { + return nil, nil, false + } + present[strconv.FormatUint(uint64(finding.RuleID), 10)] = struct{}{} + } + case []iacrealtime.IacRealtimeResult: + if scan == nil { + return nil, nil, false + } + for _, finding := range scan { + if strings.TrimSpace(finding.Title) == "" { + return nil, nil, false + } + present[strings.TrimSpace(finding.Title)] = struct{}{} + } + case []secretsrealtime.SecretsRealtimeResult: + if scan == nil { + return nil, nil, false + } + for _, finding := range scan { + if strings.TrimSpace(finding.Title) == "" { + return nil, nil, false + } + present[strings.TrimSpace(finding.Title)] = struct{}{} + } + case *ossrealtime.OssPackageResults: + if scan == nil || scan.Packages == nil { + return nil, nil, false + } + for _, pkg := range scan.Packages { + name := strings.ToLower(strings.TrimSpace(pkg.PackageName)) + if name == "" { + return nil, nil, false + } + switch strings.ToLower(strings.TrimSpace(pkg.Status)) { + case "malicious": + present[name+"@malicious"] = struct{}{} + unknownPackages[name] = struct{}{} + case "ok": + default: + if len(pkg.Vulnerabilities) == 0 { + unknownPackages[name] = struct{}{} + } + } + for _, vulnerability := range pkg.Vulnerabilities { + advisory := strings.ToLower(strings.TrimSpace(vulnerability.CVE)) + if advisory == "" { + unknownPackages[name] = struct{}{} + continue + } + present[name+"@"+advisory] = struct{}{} + } + } + default: + return nil, nil, false + } + return present, unknownPackages, true +} + +func applyVerificationVersions(event *wrappers.DataForAITelemetry) { + if version := strings.TrimSpace(utils.GetOptionalParam("agentVersion")); version != "" { + event.AgentVersion = version + } + if version := strings.TrimSpace(utils.GetOptionalParam("cxPluginVersion")); version != "" { + event.CxPluginVersion = version + } + if event.AgentVersion != "" && event.CxPluginVersion != "" { + return + } + + dir := os.Getenv("CX_LOG_DIR") + if dir == "" { + home, err := os.UserHomeDir() + if err != nil { + return + } + agentDir := strings.ToLower(strings.TrimSuffix(event.Agent, "-cli")) + switch event.Agent { + case "Copilot-cli", "Copilot-VSCode": + agentDir = "copilot-cli" + case "Gemini-cli": + agentDir = "gemini-cli" + } + dir = filepath.Join(home, ".checkmarx", "agent-logs", agentDir) + } + path := filepath.Join(dir, "cx_telemetry_context") + info, err := os.Stat(path) + if err != nil || !info.Mode().IsRegular() || info.Size() > 4096 || time.Since(info.ModTime()) >= 24*time.Hour { + return + } + file, err := os.Open(path) + if err != nil { + return + } + defer file.Close() + + scan := bufio.NewScanner(file) + for scan.Scan() { + key, version, ok := strings.Cut(scan.Text(), "=") + if !ok || !validVerificationVersion(version) { + continue + } + switch key { + case params.AgentVersionEnv: + if event.AgentVersion == "" { + event.AgentVersion = version + } + case params.CxPluginVersionEnv: + if event.CxPluginVersion == "" { + event.CxPluginVersion = version + } + } + } +} + +func validVerificationVersion(version string) bool { + return version != "" && strings.IndexFunc(version, func(r rune) bool { + return !(r >= '0' && r <= '9' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || strings.ContainsRune("._+-", r)) + }) == -1 +} + +func reportVerification(cmd *cobra.Command, telemetry wrappers.TelemetryWrapper, agent, engine string, + findings map[string]struct{}, result any, scanErr error, +) { + if telemetry == nil { + return + } + present, unknownPackages, completed := verificationResults(result) + completed = completed && scanErr == nil + ids := make([]string, 0, len(findings)) + for finding := range findings { + ids = append(ids, finding) + } + sort.Strings(ids) + var verified, stillPresent, inconclusive []string + for _, finding := range ids { + _, remains := present[finding] + packageName := finding + if separator := strings.LastIndexByte(finding, '@'); separator > 0 { + packageName = finding[:separator] + } + _, unclassified := unknownPackages[packageName] + switch { + case !completed || (!remains && unclassified): + inconclusive = append(inconclusive, finding) + case remains: + stillPresent = append(stillPresent, finding) + default: + verified = append(verified, finding) + } + } + + attrs := wrappers.EventAttributes{ + "remediationMode": hooktelemetry.RemediationModeSelfHealing, + "requestedCount": strconv.Itoa(len(ids)), "stillPresentCount": strconv.Itoa(len(stillPresent)), + "inconclusiveCount": strconv.Itoa(len(inconclusive)), + } + for key, group := range map[string][]string{ + "vulnerabilityId": ids, "verifiedFindingIds": verified, + "stillPresentFindingIds": stillPresent, "inconclusiveFindingIds": inconclusive, + } { + if value := hooktelemetry.FormatFindingIDs(group); value != "" { + attrs[key] = value + } + } + for _, key := range []string{"vulnerabilityId", "aiAgentSessionId", "machineUniqueId"} { + if value := strings.TrimSpace(utils.GetOptionalParam(key)); value != "" { + attrs[key] = value + } + } + severity, _ := hooktelemetry.ScanSeveritySummary([]string{strings.TrimSpace(utils.GetOptionalParam("problemSeverity"))}) + event := &wrappers.DataForAITelemetry{ + Type: "hooks-verify", SubType: "verifyFix", Agent: agent, + AIProvider: strings.SplitN(agent, "-", 2)[0], + Engine: engine, ScanType: strings.ToLower(engine), TotalCount: len(verified), ProblemSeverity: severity, + AiAgentSessionId: attrs["aiAgentSessionId"], UniqueID: wrappers.GetUniqueID(), EventAttributes: &attrs, + StatusResult: fmt.Sprintf("Verified=%d,StillPresent=%d,Inconclusive=%d", len(verified), len(stillPresent), len(inconclusive)), + } + if len(inconclusive) != 0 { + event.Status = hooktelemetry.StatusFailure + if !completed { + attrs["reasonCode"] = "verification_scan_failed" + } else { + attrs["reasonCode"] = "verification_incomplete" + } + } + dir, _ := os.Getwd() + if source, _ := cmd.Flags().GetString(params.SourcesFlag); source != "" { + if file, err := filepath.Abs(source); err == nil { + dir = filepath.Dir(file) + } + } + hooktelemetry.Enrich(event, dir) + event.PluginType = "CLI" + applyVerificationVersions(event) + if err := telemetry.SendAIDataToLog(event); err != nil { + logger.PrintIfVerbose("Failed to send verification telemetry: " + err.Error()) + } +} diff --git a/internal/commands/scan_verification_test.go b/internal/commands/scan_verification_test.go new file mode 100644 index 000000000..5944d2115 --- /dev/null +++ b/internal/commands/scan_verification_test.go @@ -0,0 +1,234 @@ +//go:build !integration + +package commands + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" + "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" + "github.com/checkmarx/ast-cli/internal/wrappers" + "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" + "github.com/checkmarx/ast-cli/internal/wrappers/utils" + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type verificationTelemetryRecorder struct { + events []*wrappers.DataForAITelemetry +} + +func (recorder *verificationTelemetryRecorder) SendAIDataToLog(event *wrappers.DataForAITelemetry) error { + recorder.events = append(recorder.events, event) + return nil +} + +func TestHookVerificationForCLIAgents(t *testing.T) { + t.Setenv("PLUGIN_ROOT", "") + t.Setenv("CX_COPILOT_HOST", "") + t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") + + agents := map[string]string{ + "copilot-cli": "Copilot-cli", + "claude-cli": "Claude-cli", + "cursor-cli": "Cursor-cli", + "gemini-cli": "Gemini-cli", + "codex-cli": "Codex-cli", + "copilot-vscode": "Copilot-VSCode", + } + for flag, label := range agents { + t.Run(flag, func(t *testing.T) { + recorder := &verificationTelemetryRecorder{} + cmd := verificationTestCommand(recorder, &grpcs.ScanResult{ + Status: true, ScanDetails: []grpcs.ScanDetail{{RuleID: 1027}}, + }) + var stdout bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetArgs([]string{"--agent", flag, "--verify-finding", "1027", "--verify-finding", "4059"}) + require.NoError(t, cmd.Execute()) + var output grpcs.ScanResult + require.NoError(t, json.Unmarshal(stdout.Bytes(), &output)) + assert.Equal(t, []grpcs.ScanDetail{{RuleID: 1027}}, output.ScanDetails) + require.Len(t, recorder.events, 1) + event := recorder.events[0] + assert.Equal(t, "hooks-verify", event.Type) + assert.Equal(t, "verifyFix", event.SubType) + assert.Equal(t, label, event.Agent) + assert.Equal(t, "CLI", event.PluginType) + assert.Equal(t, 1, event.TotalCount) + assert.Equal(t, "Verified=1,StillPresent=1,Inconclusive=0", event.StatusResult) + assert.Equal(t, "1027,4059", (*event.EventAttributes)["vulnerabilityId"]) + assert.Equal(t, "4059", (*event.EventAttributes)["verifiedFindingIds"]) + assert.Equal(t, "1027", (*event.EventAttributes)["stillPresentFindingIds"]) + assert.Equal(t, hooktelemetry.RemediationModeSelfHealing, (*event.EventAttributes)["remediationMode"]) + }) + } +} + +func TestHookVerificationPreservesOriginalMetadata(t *testing.T) { + metadata := map[string]string{ + "vulnerabilityId": "finding-1027", "problemSeverity": "high", "aiAgentSessionId": "agent-session", + "machineUniqueId": "device-id", "agentVersion": "1.0.117", "cxPluginVersion": "1.0.5", + } + for key := range metadata { + previous := utils.GetOptionalParam(key) + t.Cleanup(func() { _ = utils.SetOptionalParam(key, previous) }) + } + previous := viper.Get(params.OptionalFlagsKey) + t.Cleanup(func() { viper.Set(params.OptionalFlagsKey, previous) }) + viper.Set(params.OptionalFlagsKey, "vulnerabilityId=finding-1027;problemSeverity=high;aiAgentSessionId=agent-session;machineUniqueId=device-id;agentVersion=1.0.117;cxPluginVersion=1.0.5") + require.NoError(t, extractOptionalFlags(&cobra.Command{})) + recorder := &verificationTelemetryRecorder{} + cmd := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) + cmd.SetArgs([]string{"--agent", "codex-cli", "--verify-finding", "1027"}) + require.NoError(t, cmd.Execute()) + require.Len(t, recorder.events, 1) + event := recorder.events[0] + assert.Equal(t, "High", event.ProblemSeverity) + assert.Equal(t, metadata["agentVersion"], event.AgentVersion) + assert.Equal(t, metadata["cxPluginVersion"], event.CxPluginVersion) + assert.Equal(t, metadata["aiAgentSessionId"], event.AiAgentSessionId) + for _, key := range []string{"vulnerabilityId", "aiAgentSessionId", "machineUniqueId"} { + assert.Equal(t, metadata[key], (*event.EventAttributes)[key], key) + } +} + +func TestHookVerificationReadsPluginVersionsFromHookContext(t *testing.T) { + dir := t.TempDir() + t.Setenv("CX_LOG_DIR", dir) + content := "CX_AGENT_VERSION=1.0.117\nCX_PLUGIN_VERSION=1.0.5\nUNRELATED=value\n" + require.NoError(t, os.WriteFile(filepath.Join(dir, "cx_telemetry_context"), []byte(content), 0600)) + event := &wrappers.DataForAITelemetry{Agent: "Copilot-VSCode", AgentVersion: "1.0.118"} + applyVerificationVersions(event) + assert.Equal(t, "1.0.118", event.AgentVersion) + assert.Equal(t, "1.0.5", event.CxPluginVersion) +} + +func TestHookVerificationStaysPendingWhenScanIsInconclusive(t *testing.T) { + t.Setenv("PLUGIN_ROOT", "") + t.Setenv("CX_COPILOT_HOST", "") + t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") + + recorder := &verificationTelemetryRecorder{} + cmd := verificationTestCommand(recorder, &grpcs.ScanResult{Error: &grpcs.Error{Description: "scanner unavailable"}}) + cmd.SetArgs([]string{"--agent", "claude-cli", "--verify-finding", "1027"}) + require.NoError(t, cmd.Execute()) + require.Len(t, recorder.events, 1) + event := recorder.events[0] + assert.Equal(t, hooktelemetry.StatusFailure, event.Status) + assert.Zero(t, event.TotalCount) + assert.Equal(t, "1", (*event.EventAttributes)["inconclusiveCount"]) +} + +func TestHookVerificationSkipsOrdinaryScansAndRejectsUnsupportedClients(t *testing.T) { + t.Setenv("PLUGIN_ROOT", "") + t.Setenv("CX_COPILOT_HOST", "") + t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") + + recorder := &verificationTelemetryRecorder{} + ordinary := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) + ordinary.SetArgs([]string{"--agent", "copilot-cli"}) + require.NoError(t, ordinary.Execute()) + for _, args := range [][]string{ + {"--verify-finding", "1027"}, + {"--agent", "ast-cli", "--verify-finding", "1027"}, + {"--agent", "vscode", "--verify-finding", "1027"}, + {"--agent", "windsurf-cli", "--verify-finding", "1027"}, + } { + unsupported := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) + unsupported.SetArgs(args) + require.ErrorContains(t, unsupported.Execute(), "supported Dev Assist hook client") + } + assert.Empty(t, recorder.events) +} + +func TestHookVerificationDetectsCopilotVSCodeHost(t *testing.T) { + t.Setenv("PLUGIN_ROOT", "") + t.Setenv("CX_COPILOT_HOST", "vscode") + t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") + + recorder := &verificationTelemetryRecorder{} + cmd := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) + cmd.SetArgs([]string{"--agent", "copilot-cli", "--verify-finding", "1027"}) + require.NoError(t, cmd.Execute()) + require.Len(t, recorder.events, 1) + assert.Equal(t, "Copilot-VSCode", recorder.events[0].Agent) + assert.Equal(t, "CLI", recorder.events[0].PluginType) +} + +func TestHookVerificationKeepsUnclassifiedOSSPackagesPending(t *testing.T) { + result := &ossrealtime.OssPackageResults{Packages: []ossrealtime.OssPackage{ + {PackageName: "@example/module", Status: "Unknown"}, + {PackageName: "example", Status: "Vulnerable", Vulnerabilities: []ossrealtime.Vulnerability{{CVE: "CVE-example"}}}, + }} + present, unknown, completed := verificationResults(result) + assert.True(t, completed) + assert.Contains(t, present, "example@cve-example") + assert.Contains(t, unknown, "@example/module") +} + +func TestHookVerificationDecodesRealtimeScanResults(t *testing.T) { + for _, tc := range []struct { + engine string + output string + identifier string + }{ + {"Asca", `{"status":true,"scan_details":[{"rule_id":1027}]}`, "1027"}, + {"IaC", `[{"Title":"Example IaC query"}]`, "Example IaC query"}, + {hooktelemetry.EngineOSS, `{"Packages":[{"PackageName":"example","Status":"Malicious"}]}`, "example@malicious"}, + {"Secrets", `[{"Title":"Example credential rule"}]`, "Example credential rule"}, + } { + t.Run(tc.engine, func(t *testing.T) { + present, _, complete := verificationResults(decodeVerificationResult(tc.engine, []byte(tc.output))) + assert.True(t, complete) + assert.Contains(t, present, tc.identifier) + }) + } + for engine, output := range map[string]string{"Asca": `{}`, "IaC": `null`, hooktelemetry.EngineOSS: `{}`, "Secrets": `null`} { + present, _, complete := verificationResults(decodeVerificationResult(engine, []byte(output))) + assert.False(t, complete, engine) + assert.Empty(t, present, engine) + } +} + +func TestHookVerificationTreatsMalformedScanOutputAsInconclusive(t *testing.T) { + t.Setenv("PLUGIN_ROOT", "") + t.Setenv("CX_COPILOT_HOST", "") + t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") + + recorder := &verificationTelemetryRecorder{} + cmd := &cobra.Command{ + Use: "asca", + RunE: func(cmd *cobra.Command, _ []string) error { + _, err := cmd.OutOrStdout().Write([]byte("invalid scan output")) + return err + }, + } + cmd.Flags().String(params.AgentFlag, "", "") + addScanVerification(cmd, "Asca", recorder) + cmd.SetArgs([]string{"--agent", "claude-cli", "--verify-finding", "1027"}) + require.NoError(t, cmd.Execute()) + require.Len(t, recorder.events, 1) + assert.Equal(t, hooktelemetry.StatusFailure, recorder.events[0].Status) + assert.Zero(t, recorder.events[0].TotalCount) + assert.Equal(t, "1", (*recorder.events[0].EventAttributes)["inconclusiveCount"]) +} + +func verificationTestCommand(recorder *verificationTelemetryRecorder, result *grpcs.ScanResult) *cobra.Command { + cmd := &cobra.Command{ + Use: "asca", + RunE: func(cmd *cobra.Command, _ []string) error { + return json.NewEncoder(cmd.OutOrStdout()).Encode(result) + }, + } + cmd.Flags().String(params.AgentFlag, "", "") + addScanVerification(cmd, "Asca", recorder) + return cmd +} diff --git a/internal/wrappers/utils/utils.go b/internal/wrappers/utils/utils.go index b48b70bc8..e6bcc8df4 100644 --- a/internal/wrappers/utils/utils.go +++ b/internal/wrappers/utils/utils.go @@ -23,6 +23,9 @@ var allowedOptionalKeys = map[string]bool{ "agentVersion": true, "cxPluginVersion": true, "pluginType": true, + "machineUniqueId": true, + "problemSeverity": true, + "vulnerabilityId": true, "use-gitignore": true, "exclude-git-folder": true, } From 1258b7fa7a20f75c6a4c3d71810722f2ccf13d74 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:09:37 +0530 Subject: [PATCH 08/19] AST-195928 Use skill-driven verification telemetry --- internal/commands/root.go | 1 - internal/commands/scan_verification.go | 349 -------------------- internal/commands/scan_verification_test.go | 234 ------------- internal/commands/telemetry.go | 14 +- internal/commands/telemetry_test.go | 40 +++ internal/wrappers/utils/utils.go | 3 - 6 files changed, 53 insertions(+), 588 deletions(-) delete mode 100644 internal/commands/scan_verification.go delete mode 100644 internal/commands/scan_verification_test.go diff --git a/internal/commands/root.go b/internal/commands/root.go index b42e5c95e..479c9c026 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -211,7 +211,6 @@ func NewAstCLI( realTimeWrapper, tenantWrapper, ) - enableScanVerification(scanCmd, telemetryWrapper) projectCmd := NewProjectCommand(applicationsWrapper, projectsWrapper, groupsWrapper, accessManagementWrapper, featureFlagsWrapper) dastEnvironmentsCmd := dast.NewDastEnvironmentsCommand(dastEnvironmentsWrapper) diff --git a/internal/commands/scan_verification.go b/internal/commands/scan_verification.go deleted file mode 100644 index ff2f4646d..000000000 --- a/internal/commands/scan_verification.go +++ /dev/null @@ -1,349 +0,0 @@ -package commands - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "sort" - "strconv" - "strings" - "time" - - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" - "github.com/checkmarx/ast-cli/internal/logger" - "github.com/checkmarx/ast-cli/internal/params" - "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" - "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" - "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" - "github.com/checkmarx/ast-cli/internal/wrappers/utils" - "github.com/spf13/cobra" -) - -const verifyFindingFlag = "verify-finding" - -func enableScanVerification(scan *cobra.Command, telemetry wrappers.TelemetryWrapper) { - if transport, ok := telemetry.(*wrappers.TelemetryHTTPWrapper); ok { - telemetry = transport.ForAgentHooks() - } - engines := map[string]string{ - "asca": "Asca", "iac-realtime": "IaC", "oss-realtime": hooktelemetry.EngineOSS, "secrets-realtime": "Secrets", - } - for _, cmd := range scan.Commands() { - if engine, ok := engines[cmd.Name()]; ok { - addScanVerification(cmd, engine, telemetry) - } - } -} - -func addScanVerification(cmd *cobra.Command, engine string, telemetry wrappers.TelemetryWrapper) { - cmd.Flags().StringArray(verifyFindingFlag, nil, "Verify a prior Dev Assist hook finding in this realtime re-scan. Repeat for multiple findings") - run := cmd.RunE - cmd.RunE = func(cmd *cobra.Command, args []string) error { - if !cmd.Flags().Changed(verifyFindingFlag) { - return run(cmd, args) - } - agent := loginTelemetryAgent(cmd) - rawAgent, _ := cmd.Flags().GetString(params.AgentFlag) - switch { - case cmd.Flags().Changed(params.AgentFlag) && strings.EqualFold(strings.TrimSpace(rawAgent), "copilot-vscode"): - agent = "Copilot-VSCode" - case agent == "Copilot-cli" && hostenv.InVSCode(): - agent = hostenv.TelemetryAgent("Copilot") - case agent == "": - return fmt.Errorf("--%s requires --agent with a supported Dev Assist hook client", verifyFindingFlag) - } - ignoredPath, _ := cmd.Flags().GetString(params.IgnoredFilePathFlag) - if ignoredPath != "" { - return fmt.Errorf("--%s requires a scan without --%s", verifyFindingFlag, params.IgnoredFilePathFlag) - } - raw, err := cmd.Flags().GetStringArray(verifyFindingFlag) - if err != nil { - return err - } - findings, err := verificationFindings(engine, raw) - if err != nil { - return err - } - - var scanOutput bytes.Buffer - stdout := cmd.OutOrStdout() - cmd.SetOut(io.MultiWriter(stdout, &scanOutput)) - defer cmd.SetOut(stdout) - err = run(cmd, args) - var result any - if err == nil { - result = decodeVerificationResult(engine, scanOutput.Bytes()) - } - reportVerification(cmd, telemetry, agent, engine, findings, result, err) - return err - } -} - -// decodeVerificationResult reads the existing JSON output of the opt-in realtime re-scan. -func decodeVerificationResult(engine string, output []byte) any { - switch engine { - case "Asca": - return decodeVerificationJSON[*grpcs.ScanResult](output) - case "IaC": - return decodeVerificationJSON[[]iacrealtime.IacRealtimeResult](output) - case hooktelemetry.EngineOSS: - return decodeVerificationJSON[*ossrealtime.OssPackageResults](output) - case "Secrets": - return decodeVerificationJSON[[]secretsrealtime.SecretsRealtimeResult](output) - default: - return nil - } -} - -func decodeVerificationJSON[T any](output []byte) any { - var result T - if err := json.Unmarshal(output, &result); err != nil { - return nil - } - return result -} - -func verificationFindings(engine string, raw []string) (map[string]struct{}, error) { - findings := make(map[string]struct{}, len(raw)) - for _, id := range raw { - id = strings.TrimSpace(id) - switch engine { - case "Asca": - rule, err := strconv.ParseUint(id, 10, 32) - if err != nil || rule == 0 { - return nil, fmt.Errorf("--%s requires a positive ASCA rule ID", verifyFindingFlag) - } - id = strconv.FormatUint(rule, 10) - case hooktelemetry.EngineOSS: - separator := strings.LastIndexByte(id, '@') - if separator <= 0 || separator == len(id)-1 { - return nil, fmt.Errorf("--%s requires package-name@CVE or package-name@malicious for OSS", verifyFindingFlag) - } - id = strings.ToLower(id) - } - if id == "" { - return nil, fmt.Errorf("--%s requires the finding identifier or title from the original scan", verifyFindingFlag) - } - findings[id] = struct{}{} - } - if len(findings) == 0 { - return nil, fmt.Errorf("--%s requires at least one finding from the original scan", verifyFindingFlag) - } - return findings, nil -} - -func verificationResults(result any) (map[string]struct{}, map[string]struct{}, bool) { - present := make(map[string]struct{}) - unknownPackages := make(map[string]struct{}) - switch scan := result.(type) { - case *grpcs.ScanResult: - if scan == nil || !scan.Status || scan.Error != nil { - return nil, nil, false - } - for _, finding := range scan.ScanDetails { - if finding.RuleID == 0 { - return nil, nil, false - } - present[strconv.FormatUint(uint64(finding.RuleID), 10)] = struct{}{} - } - case []iacrealtime.IacRealtimeResult: - if scan == nil { - return nil, nil, false - } - for _, finding := range scan { - if strings.TrimSpace(finding.Title) == "" { - return nil, nil, false - } - present[strings.TrimSpace(finding.Title)] = struct{}{} - } - case []secretsrealtime.SecretsRealtimeResult: - if scan == nil { - return nil, nil, false - } - for _, finding := range scan { - if strings.TrimSpace(finding.Title) == "" { - return nil, nil, false - } - present[strings.TrimSpace(finding.Title)] = struct{}{} - } - case *ossrealtime.OssPackageResults: - if scan == nil || scan.Packages == nil { - return nil, nil, false - } - for _, pkg := range scan.Packages { - name := strings.ToLower(strings.TrimSpace(pkg.PackageName)) - if name == "" { - return nil, nil, false - } - switch strings.ToLower(strings.TrimSpace(pkg.Status)) { - case "malicious": - present[name+"@malicious"] = struct{}{} - unknownPackages[name] = struct{}{} - case "ok": - default: - if len(pkg.Vulnerabilities) == 0 { - unknownPackages[name] = struct{}{} - } - } - for _, vulnerability := range pkg.Vulnerabilities { - advisory := strings.ToLower(strings.TrimSpace(vulnerability.CVE)) - if advisory == "" { - unknownPackages[name] = struct{}{} - continue - } - present[name+"@"+advisory] = struct{}{} - } - } - default: - return nil, nil, false - } - return present, unknownPackages, true -} - -func applyVerificationVersions(event *wrappers.DataForAITelemetry) { - if version := strings.TrimSpace(utils.GetOptionalParam("agentVersion")); version != "" { - event.AgentVersion = version - } - if version := strings.TrimSpace(utils.GetOptionalParam("cxPluginVersion")); version != "" { - event.CxPluginVersion = version - } - if event.AgentVersion != "" && event.CxPluginVersion != "" { - return - } - - dir := os.Getenv("CX_LOG_DIR") - if dir == "" { - home, err := os.UserHomeDir() - if err != nil { - return - } - agentDir := strings.ToLower(strings.TrimSuffix(event.Agent, "-cli")) - switch event.Agent { - case "Copilot-cli", "Copilot-VSCode": - agentDir = "copilot-cli" - case "Gemini-cli": - agentDir = "gemini-cli" - } - dir = filepath.Join(home, ".checkmarx", "agent-logs", agentDir) - } - path := filepath.Join(dir, "cx_telemetry_context") - info, err := os.Stat(path) - if err != nil || !info.Mode().IsRegular() || info.Size() > 4096 || time.Since(info.ModTime()) >= 24*time.Hour { - return - } - file, err := os.Open(path) - if err != nil { - return - } - defer file.Close() - - scan := bufio.NewScanner(file) - for scan.Scan() { - key, version, ok := strings.Cut(scan.Text(), "=") - if !ok || !validVerificationVersion(version) { - continue - } - switch key { - case params.AgentVersionEnv: - if event.AgentVersion == "" { - event.AgentVersion = version - } - case params.CxPluginVersionEnv: - if event.CxPluginVersion == "" { - event.CxPluginVersion = version - } - } - } -} - -func validVerificationVersion(version string) bool { - return version != "" && strings.IndexFunc(version, func(r rune) bool { - return !(r >= '0' && r <= '9' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || strings.ContainsRune("._+-", r)) - }) == -1 -} - -func reportVerification(cmd *cobra.Command, telemetry wrappers.TelemetryWrapper, agent, engine string, - findings map[string]struct{}, result any, scanErr error, -) { - if telemetry == nil { - return - } - present, unknownPackages, completed := verificationResults(result) - completed = completed && scanErr == nil - ids := make([]string, 0, len(findings)) - for finding := range findings { - ids = append(ids, finding) - } - sort.Strings(ids) - var verified, stillPresent, inconclusive []string - for _, finding := range ids { - _, remains := present[finding] - packageName := finding - if separator := strings.LastIndexByte(finding, '@'); separator > 0 { - packageName = finding[:separator] - } - _, unclassified := unknownPackages[packageName] - switch { - case !completed || (!remains && unclassified): - inconclusive = append(inconclusive, finding) - case remains: - stillPresent = append(stillPresent, finding) - default: - verified = append(verified, finding) - } - } - - attrs := wrappers.EventAttributes{ - "remediationMode": hooktelemetry.RemediationModeSelfHealing, - "requestedCount": strconv.Itoa(len(ids)), "stillPresentCount": strconv.Itoa(len(stillPresent)), - "inconclusiveCount": strconv.Itoa(len(inconclusive)), - } - for key, group := range map[string][]string{ - "vulnerabilityId": ids, "verifiedFindingIds": verified, - "stillPresentFindingIds": stillPresent, "inconclusiveFindingIds": inconclusive, - } { - if value := hooktelemetry.FormatFindingIDs(group); value != "" { - attrs[key] = value - } - } - for _, key := range []string{"vulnerabilityId", "aiAgentSessionId", "machineUniqueId"} { - if value := strings.TrimSpace(utils.GetOptionalParam(key)); value != "" { - attrs[key] = value - } - } - severity, _ := hooktelemetry.ScanSeveritySummary([]string{strings.TrimSpace(utils.GetOptionalParam("problemSeverity"))}) - event := &wrappers.DataForAITelemetry{ - Type: "hooks-verify", SubType: "verifyFix", Agent: agent, - AIProvider: strings.SplitN(agent, "-", 2)[0], - Engine: engine, ScanType: strings.ToLower(engine), TotalCount: len(verified), ProblemSeverity: severity, - AiAgentSessionId: attrs["aiAgentSessionId"], UniqueID: wrappers.GetUniqueID(), EventAttributes: &attrs, - StatusResult: fmt.Sprintf("Verified=%d,StillPresent=%d,Inconclusive=%d", len(verified), len(stillPresent), len(inconclusive)), - } - if len(inconclusive) != 0 { - event.Status = hooktelemetry.StatusFailure - if !completed { - attrs["reasonCode"] = "verification_scan_failed" - } else { - attrs["reasonCode"] = "verification_incomplete" - } - } - dir, _ := os.Getwd() - if source, _ := cmd.Flags().GetString(params.SourcesFlag); source != "" { - if file, err := filepath.Abs(source); err == nil { - dir = filepath.Dir(file) - } - } - hooktelemetry.Enrich(event, dir) - event.PluginType = "CLI" - applyVerificationVersions(event) - if err := telemetry.SendAIDataToLog(event); err != nil { - logger.PrintIfVerbose("Failed to send verification telemetry: " + err.Error()) - } -} diff --git a/internal/commands/scan_verification_test.go b/internal/commands/scan_verification_test.go deleted file mode 100644 index 5944d2115..000000000 --- a/internal/commands/scan_verification_test.go +++ /dev/null @@ -1,234 +0,0 @@ -//go:build !integration - -package commands - -import ( - "bytes" - "encoding/json" - "os" - "path/filepath" - "testing" - - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" - "github.com/checkmarx/ast-cli/internal/params" - "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" - "github.com/checkmarx/ast-cli/internal/wrappers/utils" - "github.com/spf13/cobra" - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type verificationTelemetryRecorder struct { - events []*wrappers.DataForAITelemetry -} - -func (recorder *verificationTelemetryRecorder) SendAIDataToLog(event *wrappers.DataForAITelemetry) error { - recorder.events = append(recorder.events, event) - return nil -} - -func TestHookVerificationForCLIAgents(t *testing.T) { - t.Setenv("PLUGIN_ROOT", "") - t.Setenv("CX_COPILOT_HOST", "") - t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") - - agents := map[string]string{ - "copilot-cli": "Copilot-cli", - "claude-cli": "Claude-cli", - "cursor-cli": "Cursor-cli", - "gemini-cli": "Gemini-cli", - "codex-cli": "Codex-cli", - "copilot-vscode": "Copilot-VSCode", - } - for flag, label := range agents { - t.Run(flag, func(t *testing.T) { - recorder := &verificationTelemetryRecorder{} - cmd := verificationTestCommand(recorder, &grpcs.ScanResult{ - Status: true, ScanDetails: []grpcs.ScanDetail{{RuleID: 1027}}, - }) - var stdout bytes.Buffer - cmd.SetOut(&stdout) - cmd.SetArgs([]string{"--agent", flag, "--verify-finding", "1027", "--verify-finding", "4059"}) - require.NoError(t, cmd.Execute()) - var output grpcs.ScanResult - require.NoError(t, json.Unmarshal(stdout.Bytes(), &output)) - assert.Equal(t, []grpcs.ScanDetail{{RuleID: 1027}}, output.ScanDetails) - require.Len(t, recorder.events, 1) - event := recorder.events[0] - assert.Equal(t, "hooks-verify", event.Type) - assert.Equal(t, "verifyFix", event.SubType) - assert.Equal(t, label, event.Agent) - assert.Equal(t, "CLI", event.PluginType) - assert.Equal(t, 1, event.TotalCount) - assert.Equal(t, "Verified=1,StillPresent=1,Inconclusive=0", event.StatusResult) - assert.Equal(t, "1027,4059", (*event.EventAttributes)["vulnerabilityId"]) - assert.Equal(t, "4059", (*event.EventAttributes)["verifiedFindingIds"]) - assert.Equal(t, "1027", (*event.EventAttributes)["stillPresentFindingIds"]) - assert.Equal(t, hooktelemetry.RemediationModeSelfHealing, (*event.EventAttributes)["remediationMode"]) - }) - } -} - -func TestHookVerificationPreservesOriginalMetadata(t *testing.T) { - metadata := map[string]string{ - "vulnerabilityId": "finding-1027", "problemSeverity": "high", "aiAgentSessionId": "agent-session", - "machineUniqueId": "device-id", "agentVersion": "1.0.117", "cxPluginVersion": "1.0.5", - } - for key := range metadata { - previous := utils.GetOptionalParam(key) - t.Cleanup(func() { _ = utils.SetOptionalParam(key, previous) }) - } - previous := viper.Get(params.OptionalFlagsKey) - t.Cleanup(func() { viper.Set(params.OptionalFlagsKey, previous) }) - viper.Set(params.OptionalFlagsKey, "vulnerabilityId=finding-1027;problemSeverity=high;aiAgentSessionId=agent-session;machineUniqueId=device-id;agentVersion=1.0.117;cxPluginVersion=1.0.5") - require.NoError(t, extractOptionalFlags(&cobra.Command{})) - recorder := &verificationTelemetryRecorder{} - cmd := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) - cmd.SetArgs([]string{"--agent", "codex-cli", "--verify-finding", "1027"}) - require.NoError(t, cmd.Execute()) - require.Len(t, recorder.events, 1) - event := recorder.events[0] - assert.Equal(t, "High", event.ProblemSeverity) - assert.Equal(t, metadata["agentVersion"], event.AgentVersion) - assert.Equal(t, metadata["cxPluginVersion"], event.CxPluginVersion) - assert.Equal(t, metadata["aiAgentSessionId"], event.AiAgentSessionId) - for _, key := range []string{"vulnerabilityId", "aiAgentSessionId", "machineUniqueId"} { - assert.Equal(t, metadata[key], (*event.EventAttributes)[key], key) - } -} - -func TestHookVerificationReadsPluginVersionsFromHookContext(t *testing.T) { - dir := t.TempDir() - t.Setenv("CX_LOG_DIR", dir) - content := "CX_AGENT_VERSION=1.0.117\nCX_PLUGIN_VERSION=1.0.5\nUNRELATED=value\n" - require.NoError(t, os.WriteFile(filepath.Join(dir, "cx_telemetry_context"), []byte(content), 0600)) - event := &wrappers.DataForAITelemetry{Agent: "Copilot-VSCode", AgentVersion: "1.0.118"} - applyVerificationVersions(event) - assert.Equal(t, "1.0.118", event.AgentVersion) - assert.Equal(t, "1.0.5", event.CxPluginVersion) -} - -func TestHookVerificationStaysPendingWhenScanIsInconclusive(t *testing.T) { - t.Setenv("PLUGIN_ROOT", "") - t.Setenv("CX_COPILOT_HOST", "") - t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") - - recorder := &verificationTelemetryRecorder{} - cmd := verificationTestCommand(recorder, &grpcs.ScanResult{Error: &grpcs.Error{Description: "scanner unavailable"}}) - cmd.SetArgs([]string{"--agent", "claude-cli", "--verify-finding", "1027"}) - require.NoError(t, cmd.Execute()) - require.Len(t, recorder.events, 1) - event := recorder.events[0] - assert.Equal(t, hooktelemetry.StatusFailure, event.Status) - assert.Zero(t, event.TotalCount) - assert.Equal(t, "1", (*event.EventAttributes)["inconclusiveCount"]) -} - -func TestHookVerificationSkipsOrdinaryScansAndRejectsUnsupportedClients(t *testing.T) { - t.Setenv("PLUGIN_ROOT", "") - t.Setenv("CX_COPILOT_HOST", "") - t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") - - recorder := &verificationTelemetryRecorder{} - ordinary := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) - ordinary.SetArgs([]string{"--agent", "copilot-cli"}) - require.NoError(t, ordinary.Execute()) - for _, args := range [][]string{ - {"--verify-finding", "1027"}, - {"--agent", "ast-cli", "--verify-finding", "1027"}, - {"--agent", "vscode", "--verify-finding", "1027"}, - {"--agent", "windsurf-cli", "--verify-finding", "1027"}, - } { - unsupported := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) - unsupported.SetArgs(args) - require.ErrorContains(t, unsupported.Execute(), "supported Dev Assist hook client") - } - assert.Empty(t, recorder.events) -} - -func TestHookVerificationDetectsCopilotVSCodeHost(t *testing.T) { - t.Setenv("PLUGIN_ROOT", "") - t.Setenv("CX_COPILOT_HOST", "vscode") - t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") - - recorder := &verificationTelemetryRecorder{} - cmd := verificationTestCommand(recorder, &grpcs.ScanResult{Status: true}) - cmd.SetArgs([]string{"--agent", "copilot-cli", "--verify-finding", "1027"}) - require.NoError(t, cmd.Execute()) - require.Len(t, recorder.events, 1) - assert.Equal(t, "Copilot-VSCode", recorder.events[0].Agent) - assert.Equal(t, "CLI", recorder.events[0].PluginType) -} - -func TestHookVerificationKeepsUnclassifiedOSSPackagesPending(t *testing.T) { - result := &ossrealtime.OssPackageResults{Packages: []ossrealtime.OssPackage{ - {PackageName: "@example/module", Status: "Unknown"}, - {PackageName: "example", Status: "Vulnerable", Vulnerabilities: []ossrealtime.Vulnerability{{CVE: "CVE-example"}}}, - }} - present, unknown, completed := verificationResults(result) - assert.True(t, completed) - assert.Contains(t, present, "example@cve-example") - assert.Contains(t, unknown, "@example/module") -} - -func TestHookVerificationDecodesRealtimeScanResults(t *testing.T) { - for _, tc := range []struct { - engine string - output string - identifier string - }{ - {"Asca", `{"status":true,"scan_details":[{"rule_id":1027}]}`, "1027"}, - {"IaC", `[{"Title":"Example IaC query"}]`, "Example IaC query"}, - {hooktelemetry.EngineOSS, `{"Packages":[{"PackageName":"example","Status":"Malicious"}]}`, "example@malicious"}, - {"Secrets", `[{"Title":"Example credential rule"}]`, "Example credential rule"}, - } { - t.Run(tc.engine, func(t *testing.T) { - present, _, complete := verificationResults(decodeVerificationResult(tc.engine, []byte(tc.output))) - assert.True(t, complete) - assert.Contains(t, present, tc.identifier) - }) - } - for engine, output := range map[string]string{"Asca": `{}`, "IaC": `null`, hooktelemetry.EngineOSS: `{}`, "Secrets": `null`} { - present, _, complete := verificationResults(decodeVerificationResult(engine, []byte(output))) - assert.False(t, complete, engine) - assert.Empty(t, present, engine) - } -} - -func TestHookVerificationTreatsMalformedScanOutputAsInconclusive(t *testing.T) { - t.Setenv("PLUGIN_ROOT", "") - t.Setenv("CX_COPILOT_HOST", "") - t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", "") - - recorder := &verificationTelemetryRecorder{} - cmd := &cobra.Command{ - Use: "asca", - RunE: func(cmd *cobra.Command, _ []string) error { - _, err := cmd.OutOrStdout().Write([]byte("invalid scan output")) - return err - }, - } - cmd.Flags().String(params.AgentFlag, "", "") - addScanVerification(cmd, "Asca", recorder) - cmd.SetArgs([]string{"--agent", "claude-cli", "--verify-finding", "1027"}) - require.NoError(t, cmd.Execute()) - require.Len(t, recorder.events, 1) - assert.Equal(t, hooktelemetry.StatusFailure, recorder.events[0].Status) - assert.Zero(t, recorder.events[0].TotalCount) - assert.Equal(t, "1", (*recorder.events[0].EventAttributes)["inconclusiveCount"]) -} - -func verificationTestCommand(recorder *verificationTelemetryRecorder, result *grpcs.ScanResult) *cobra.Command { - cmd := &cobra.Command{ - Use: "asca", - RunE: func(cmd *cobra.Command, _ []string) error { - return json.NewEncoder(cmd.OutOrStdout()).Encode(result) - }, - } - cmd.Flags().String(params.AgentFlag, "", "") - addScanVerification(cmd, "Asca", recorder) - return cmd -} diff --git a/internal/commands/telemetry.go b/internal/commands/telemetry.go index 6f2a82728..8c0f278ea 100644 --- a/internal/commands/telemetry.go +++ b/internal/commands/telemetry.go @@ -15,6 +15,7 @@ import ( const ( keyValuePairsSplit = 2 authenticationEventType = "authentication" + verificationEventType = "hooks-verify" telemetrySuccessStatus = "success" ) @@ -118,6 +119,17 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm eventAttributesStr, _ := cmd.Flags().GetString(params.EventAttributesFlag) apiVersion, _ := cmd.Flags().GetString(params.ApiVersionFlag) + sender := telemetryWrapper + if strings.EqualFold(strings.TrimSpace(eventType), verificationEventType) { + if transport, ok := telemetryWrapper.(*wrappers.TelemetryHTTPWrapper); ok { + // The skill starts a separate CLI process, so warm its access token before using the short hook send. + if _, err := wrappers.GetAccessToken(); err != nil { + return errors.Wrap(err, "Failed to authenticate verification telemetry") + } + sender = transport.ForAgentHooks() + } + } + uniqueID := wrappers.GetUniqueID() var sessionID string @@ -129,7 +141,7 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm eventAttrs := parseEventAttributes(eventAttributesStr) - err := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{ + err := sender.SendAIDataToLog(&wrappers.DataForAITelemetry{ AIProvider: aiProvider, ProblemSeverity: problemSeverity, Type: eventType, diff --git a/internal/commands/telemetry_test.go b/internal/commands/telemetry_test.go index e0848d46a..0e601a528 100644 --- a/internal/commands/telemetry_test.go +++ b/internal/commands/telemetry_test.go @@ -3,7 +3,12 @@ package commands import ( + "encoding/base64" + "encoding/json" "io" + "net/http" + "net/http/httptest" + "strings" "testing" "github.com/checkmarx/ast-cli/internal/params" @@ -116,6 +121,41 @@ func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { "telemetry", "ai", "--ai-provider", "Cursor", "--problem-severity", "Critical", "--type", "click", "--sub-type", "ast-results.viewPackageDetails", "--agent", "Cursor", "--engine", "secrets") } +func TestRunTelemetryAI_VerificationReportsHTTPFailure(t *testing.T) { + t.Setenv("CX_TELEMETRY_DEV_URL", "") + previousExpiry := viper.Get(params.TokenExpirySecondsKey) + previousOverride := viper.Get(params.ApikeyOverrideFlag) + t.Cleanup(func() { + viper.Set(params.TokenExpirySecondsKey, previousExpiry) + viper.Set(params.ApikeyOverrideFlag, previousOverride) + wrappers.InvalidateAccessTokenCache() + }) + viper.Set(params.TokenExpirySecondsKey, 300) + viper.Set(params.ApikeyOverrideFlag, false) + + received := make(chan string, 4) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + received <- r.URL.Path + w.WriteHeader(http.StatusForbidden) + })) + t.Cleanup(server.Close) + + header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none","typ":"JWT"}`)) + claims, err := json.Marshal(map[string]string{wrappers.BaseURLKey: server.URL}) + assert.NilError(t, err) + wrappers.CacheAuthenticatedAccessToken(header + "." + base64.RawURLEncoding.EncodeToString(claims) + ".sig") + + cmd := NewTelemetryCommand(wrappers.NewHTTPTelemetryAIWrapper("telemetry")) + cmd.SetOut(io.Discard) + cmd.SetArgs([]string{"ai", "--type", "hooks-verify", "--agent", "Copilot-VSCode", "--sub-type", "verifyFix"}) + err = cmd.Execute() + if err == nil || !strings.Contains(err.Error(), "403 Forbidden") { + t.Fatalf("expected the telemetry HTTP rejection, got %v", err) + } + assert.Equal(t, len(received), 1) + assert.Equal(t, <-received, "/telemetry/log") +} + func TestTelemetryHelp(t *testing.T) { execCmdNilAssertion(t, "help", "telemetry", "ai") } diff --git a/internal/wrappers/utils/utils.go b/internal/wrappers/utils/utils.go index e6bcc8df4..b48b70bc8 100644 --- a/internal/wrappers/utils/utils.go +++ b/internal/wrappers/utils/utils.go @@ -23,9 +23,6 @@ var allowedOptionalKeys = map[string]bool{ "agentVersion": true, "cxPluginVersion": true, "pluginType": true, - "machineUniqueId": true, - "problemSeverity": true, - "vulnerabilityId": true, "use-gitignore": true, "exclude-git-folder": true, } From 37b409c91c8f9ea1ae3310c4eea8356ae9501fcd Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:45:48 +0530 Subject: [PATCH 09/19] AST-195928 Attach login metadata and confirm verification publish Signed-off-by: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> --- internal/commands/auth_login.go | 41 ++++++++++++++++++------ internal/commands/auth_login_test.go | 16 +++++++++- internal/params/flags.go | 1 + internal/wrappers/client_test.go | 47 ++++++++++++++++++++++++++++ internal/wrappers/telemetry-http.go | 7 ++++- 5 files changed, 100 insertions(+), 12 deletions(-) diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index 024d0b737..613a03793 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -63,6 +63,10 @@ func newAuthLoginCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Comm } cmd.Flags().Int(params.LoginPortFlag, 0, params.LoginPortFlagUsage) cmd.Flags().Bool(params.LoginNoBrowserFlag, false, params.LoginNoBrowserFlagUsage) + cmd.Flags().String(params.AgentVersionFlag, "", "Agent version attached to login telemetry") + cmd.Flags().String(params.CxPluginVersionFlag, "", "Checkmarx plugin version attached to login telemetry") + cmd.Flags().String(params.AIAgentSessionIDFlag, "", "Current agent session ID attached to login telemetry") + return cmd } @@ -158,17 +162,34 @@ func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryW } wrappers.CacheAuthenticatedAccessToken(accessToken) attrs := wrappers.EventAttributes{"authMethod": authMethod} + agentSessionID, _ := cmd.Flags().GetString(params.AIAgentSessionIDFlag) + agentSessionID = strings.TrimSpace(agentSessionID) + if agentSessionID != "" { + attrs["aiAgentSessionId"] = agentSessionID + } + agentVersion, _ := cmd.Flags().GetString(params.AgentVersionFlag) + agentVersion = strings.TrimSpace(agentVersion) + if agentVersion == "" { + agentVersion = strings.TrimSpace(os.Getenv(params.AgentVersionEnv)) + } + pluginVersion, _ := cmd.Flags().GetString(params.CxPluginVersionFlag) + pluginVersion = strings.TrimSpace(pluginVersion) + if pluginVersion == "" { + pluginVersion = strings.TrimSpace(os.Getenv(params.CxPluginVersionEnv)) + } data := &wrappers.DataForAITelemetry{ - Type: authenticationEventType, - SubType: authenticationEventType, - Status: telemetrySuccessStatus, - StatusResult: "Authentication successful.", - Agent: agent, - AgentVersion: strings.TrimSpace(os.Getenv(params.AgentVersionEnv)), - CxPluginVersion: strings.TrimSpace(os.Getenv(params.CxPluginVersionEnv)), - PluginType: "CLI", - UniqueID: wrappers.GetUniqueID(), - EventAttributes: &attrs, + Type: authenticationEventType, + SubType: authenticationEventType, + Status: telemetrySuccessStatus, + StatusResult: "Authentication successful.", + Agent: agent, + AgentVersion: agentVersion, + CxPluginVersion: pluginVersion, + AIProvider: strings.TrimSuffix(agent, "-cli"), + AiAgentSessionId: agentSessionID, + PluginType: "CLI", + UniqueID: wrappers.GetUniqueID(), + EventAttributes: &attrs, } if saveFailed { data.Status = hooktelemetry.StatusFailure diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index e84e16ae0..c5e8a7363 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -244,6 +244,8 @@ func TestPersistLogin_PrintsSuccessMessage(t *testing.T) { func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { const credential = "test-login-credential" + t.Setenv(params.AgentVersionEnv, "fallback-agent") + t.Setenv(params.CxPluginVersionEnv, "fallback-plugin") cases := []struct { name string agent *string @@ -271,7 +273,14 @@ func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { }) viper.Set(params.TokenExpirySecondsKey, 120) viper.Set(params.SessionIDConfigKey, "") - cmd, _, _ := newBufferedCmd() + cmd := newAuthLoginCommand(nil) + for flag, value := range map[string]string{ + params.AgentVersionFlag: "1.2.3", params.CxPluginVersionFlag: "4.5.6", params.AIAgentSessionIDFlag: "current-session", + } { + if err := cmd.Flags().Set(flag, value); err != nil { + t.Fatal(err) + } + } cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") if tc.agent != nil { if err := cmd.Flags().Set(params.AgentFlag, *tc.agent); err != nil { @@ -289,6 +298,11 @@ func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { data.SessionID == "" || (*data.EventAttributes)["authMethod"] != "OAuth" { t.Fatalf("unexpected authentication telemetry: %+v", data) } + if data.AgentVersion != "1.2.3" || data.CxPluginVersion != "4.5.6" || + data.AIProvider == "" || data.AiAgentSessionId != "current-session" || + (*data.EventAttributes)["aiAgentSessionId"] != "current-session" { + t.Fatalf("missing login metadata: %+v", data) + } return errors.New("telemetry unavailable") }} if err := completeAuthLogin(cmd, telemetry, credential, "test-access-token", "OAuth"); err != nil { diff --git a/internal/params/flags.go b/internal/params/flags.go index 1d4626417..a048114d7 100644 --- a/internal/params/flags.go +++ b/internal/params/flags.go @@ -21,6 +21,7 @@ const ( TotalCountFlag = "total-count" AgentVersionFlag = "agent-version" CxPluginVersionFlag = "cx-plugin-version" + AIAgentSessionIDFlag = "ai-agent-session-id" PluginTypeFlag = "plugin-type" RepoURLFlag = "repo-url" EventAttributesFlag = "event-attributes" diff --git a/internal/wrappers/client_test.go b/internal/wrappers/client_test.go index 0e58a1503..2c617035c 100644 --- a/internal/wrappers/client_test.go +++ b/internal/wrappers/client_test.go @@ -359,6 +359,53 @@ func TestAgentHookTelemetryTimesOutWithoutRetrying(t *testing.T) { } } +func TestVerificationTelemetryRequiresPublishAcknowledgement(t *testing.T) { + t.Setenv("CX_TELEMETRY_DEV_URL", "") + for key, value := range map[string]any{ + commonParams.IgnoreProxyKey: true, + commonParams.ApikeyOverrideFlag: false, + commonParams.TokenExpirySecondsKey: 300, + } { + previous := viper.Get(key) + t.Cleanup(func() { viper.Set(key, previous) }) + viper.Set(key, value) + } + credentialsMutex.Lock() + previousToken, previousTime := cachedAccessToken, cachedAccessTime + credentialsMutex.Unlock() + t.Cleanup(func() { + credentialsMutex.Lock() + defer credentialsMutex.Unlock() + cachedAccessToken, cachedAccessTime = previousToken, previousTime + }) + for _, tc := range []struct { + name string + status int + acknowledgement string + wantError bool + }{ + {name: "broker confirmed", status: http.StatusOK, acknowledgement: "true"}, + {name: "legacy HTTP success", status: http.StatusOK, wantError: true}, + {name: "publish failed", status: http.StatusInternalServerError, wantError: true}, + } { + t.Run(tc.name, func(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + if tc.acknowledgement != "" { + w.Header().Set("X-Cx-Telemetry-Published", tc.acknowledgement) + } + w.WriteHeader(tc.status) + })) + defer server.Close() + writeCredentialsToCache(unsignedJWT(map[string]any{BaseURLKey: server.URL})) + wrapper := NewHTTPTelemetryAIWrapper("api/realtime-scanner").ForAgentHooks() + err := wrapper.SendAIDataToLog(&DataForAITelemetry{Type: "hooks-verify"}) + if (err != nil) != tc.wantError { + t.Fatalf("SendAIDataToLog error = %v, want error: %t", err, tc.wantError) + } + }) + } +} + // TestExtractFromTokenClaims covers fix #10: the "aud" (and any) claim may be a // string or an array of strings. The array form must not panic. func TestExtractFromTokenClaims(t *testing.T) { diff --git a/internal/wrappers/telemetry-http.go b/internal/wrappers/telemetry-http.go index 10a3ad365..120d5919e 100644 --- a/internal/wrappers/telemetry-http.go +++ b/internal/wrappers/telemetry-http.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "net/http" + "strings" commonParams "github.com/checkmarx/ast-cli/internal/params" "github.com/pkg/errors" @@ -53,9 +54,13 @@ func (r *TelemetryHTTPWrapper) SendAIDataToLog(data *DataForAITelemetry) error { _ = resp.Body.Close() } }() - if r.agentHooks && (resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices) { + verification := strings.EqualFold(strings.TrimSpace(data.Type), "hooks-verify") + if (r.agentHooks || verification) && (resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices) { return errors.Errorf("failed to log hook telemetry, status code: %s", resp.Status) } + if verification && resp.Header.Get("X-Cx-Telemetry-Published") != "true" { + return errors.New("verification telemetry publish was not confirmed") + } switch resp.StatusCode { case http.StatusBadRequest, http.StatusInternalServerError: return errors.Errorf("Failed to log the data, status code: %s", resp.Status) From 336be647eed052f6ffe8bc4d0d90529853a99399 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Mon, 30 Nov 2026 20:59:49 +0530 Subject: [PATCH 10/19] AST-195928 Verify realtime fixes through a hidden scan flag Signed-off-by: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> --- internal/commands/root.go | 1 + internal/commands/scan_verification.go | 420 ++++++++++++++++++++ internal/commands/scan_verification_test.go | 105 +++++ internal/commands/telemetry.go | 24 +- 4 files changed, 535 insertions(+), 15 deletions(-) create mode 100644 internal/commands/scan_verification.go create mode 100644 internal/commands/scan_verification_test.go diff --git a/internal/commands/root.go b/internal/commands/root.go index 479c9c026..b42e5c95e 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -211,6 +211,7 @@ func NewAstCLI( realTimeWrapper, tenantWrapper, ) + enableScanVerification(scanCmd, telemetryWrapper) projectCmd := NewProjectCommand(applicationsWrapper, projectsWrapper, groupsWrapper, accessManagementWrapper, featureFlagsWrapper) dastEnvironmentsCmd := dast.NewDastEnvironmentsCommand(dastEnvironmentsWrapper) diff --git a/internal/commands/scan_verification.go b/internal/commands/scan_verification.go new file mode 100644 index 000000000..365ea4c3d --- /dev/null +++ b/internal/commands/scan_verification.go @@ -0,0 +1,420 @@ +package commands + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "strings" + "unicode" + + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" + "github.com/checkmarx/ast-cli/internal/params" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" + "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" + "github.com/checkmarx/ast-cli/internal/wrappers" + "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" + "github.com/spf13/cobra" +) + +const ( + verifyFixFlag = "verify-fix" + verificationContextLimit = 64 * 1024 +) + +type verificationFinding struct { + RuleID uint32 `json:"ruleId,omitempty"` + Title string `json:"title,omitempty"` + SimilarityID string `json:"similarityId,omitempty"` + PackageName string `json:"packageName,omitempty"` + PackageVersion string `json:"packageVersion,omitempty"` + CVE string `json:"cve,omitempty"` + Malicious bool `json:"malicious,omitempty"` + VulnerabilityID string `json:"vulnerabilityId,omitempty"` + Severity string `json:"severity,omitempty"` +} + +type verificationContext struct { + Findings []verificationFinding `json:"findings"` + AIAgentSessionID string `json:"aiAgentSessionId,omitempty"` + AgentVersion string `json:"agentVersion,omitempty"` + PluginVersion string `json:"cxPluginVersion,omitempty"` + MachineUniqueID string `json:"machineUniqueId,omitempty"` +} + +type verificationKey struct { + name string + detail string +} + +type verificationOutcome string + +const ( + findingVerified verificationOutcome = "verified" + findingStillPresent verificationOutcome = "stillPresent" + findingInconclusive verificationOutcome = "inconclusive" +) + +func enableScanVerification(scan *cobra.Command, sender wrappers.TelemetryWrapper) { + engines := map[string]string{ + "asca": "Asca", "iac-realtime": "IaC", "oss-realtime": hooktelemetry.EngineOSS, "secrets-realtime": "Secrets", + } + for _, cmd := range scan.Commands() { + if engine, ok := engines[cmd.Name()]; ok { + addScanVerification(cmd, engine, sender) + } + } +} + +func addScanVerification(cmd *cobra.Command, engine string, sender wrappers.TelemetryWrapper) { + flags := cmd.Flags() + flags.String(verifyFixFlag, "", "Path to the original Dev Assist finding context") + _ = flags.MarkHidden(verifyFixFlag) + run := cmd.RunE + cmd.RunE = func(cmd *cobra.Command, args []string) error { + if !cmd.Flags().Changed(verifyFixFlag) { + return run(cmd, args) + } + agent := loginTelemetryAgent(cmd) + rawAgent, _ := cmd.Flags().GetString(params.AgentFlag) + if cmd.Flags().Changed(params.AgentFlag) && strings.EqualFold(strings.TrimSpace(rawAgent), "copilot-vscode") { + agent = "Copilot-VSCode" + } + if agent == "" { + return fmt.Errorf("--%s requires an explicit --agent for a supported Dev Assist hook client", verifyFixFlag) + } + if path, _ := cmd.Flags().GetString(params.IgnoredFilePathFlag); path != "" { + return fmt.Errorf("--%s requires a scan without --%s", verifyFixFlag, params.IgnoredFilePathFlag) + } + + path, _ := cmd.Flags().GetString(verifyFixFlag) + context, original, err := readVerificationContext(path) + if err != nil { + return fmt.Errorf("--%s: %w", verifyFixFlag, err) + } + if len(context.Findings) == 0 { + return run(cmd, args) + } + for _, finding := range context.Findings { + if finding.key(engine).name == "" { + return fmt.Errorf("--%s: context contains a finding without a valid %s identity", verifyFixFlag, engine) + } + } + source, _ := cmd.Flags().GetString(params.SourcesFlag) + if contextInfo, ctxErr := os.Stat(path); ctxErr == nil { + if sourceInfo, sourceErr := os.Stat(source); sourceErr == nil && os.SameFile(contextInfo, sourceInfo) { + return fmt.Errorf("--%s context must be separate from the file being scanned", verifyFixFlag) + } + } + + var output bytes.Buffer + stdout := cmd.OutOrStdout() + cmd.SetOut(io.MultiWriter(stdout, &output)) + defer cmd.SetOut(stdout) + scanErr := run(cmd, args) + pending, event := buildVerificationEvent(context, agent, engine, source, output.Bytes(), scanErr) + fmt.Fprintln(cmd.ErrOrStderr(), "Verification: "+event.StatusResult) + + if err := sendVerificationTelemetry(sender, event); err != nil { + fmt.Fprintln(cmd.ErrOrStderr(), "Verification telemetry was not confirmed.") + } else if len(pending) < len(context.Findings) { + context.Findings = pending + if err := saveVerificationContext(path, original, context); err != nil { + fmt.Fprintln(cmd.ErrOrStderr(), "Could not save pending findings for the next verification attempt.") + } + } + return scanErr + } +} + +func sendVerificationTelemetry(sender wrappers.TelemetryWrapper, event *wrappers.DataForAITelemetry) error { + if sender == nil { + return fmt.Errorf("verification telemetry sender is unavailable") + } + if transport, ok := sender.(*wrappers.TelemetryHTTPWrapper); ok { + if _, err := wrappers.GetAccessToken(); err != nil { + return fmt.Errorf("authenticate verification telemetry: %w", err) + } + sender = transport.ForAgentHooks() + } + return sender.SendAIDataToLog(event) +} + +func readVerificationContext(path string) (verificationContext, []byte, error) { + var context verificationContext + file, err := os.Open(path) + if err != nil { + return context, nil, err + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, verificationContextLimit+1)) + if err != nil { + return context, nil, err + } + if len(data) > verificationContextLimit { + return context, nil, fmt.Errorf("finding context exceeds 64 KiB") + } + if err := json.Unmarshal(bytes.TrimPrefix(data, []byte{0xef, 0xbb, 0xbf}), &context); err != nil { + return context, nil, fmt.Errorf("invalid finding context: %w", err) + } + if context.Findings == nil { + return context, nil, fmt.Errorf("finding context requires a findings array") + } + return context, data, nil +} + +func saveVerificationContext(path string, original []byte, context verificationContext) error { + _, current, err := readVerificationContext(path) + if err != nil { + return err + } + if !bytes.Equal(current, original) { + return fmt.Errorf("finding context changed during verification") + } + file, err := os.CreateTemp(filepath.Dir(path), ".cx-verification-*.json") + if err != nil { + return err + } + defer os.Remove(file.Name()) + writeErr := json.NewEncoder(file).Encode(context) + closeErr := file.Close() + if writeErr != nil { + return writeErr + } + if closeErr != nil { + return closeErr + } + return os.Rename(file.Name(), path) +} + +func verificationValue(value string) string { + value = strings.TrimSpace(value) + if len(value) > 256 || strings.ContainsRune(value, ';') || strings.IndexFunc(value, unicode.IsControl) >= 0 { + return "" + } + return value +} + +func (finding verificationFinding) key(engine string) verificationKey { + normalized := func(value string) string { return strings.ToLower(verificationValue(value)) } + switch engine { + case "Asca": + if finding.RuleID != 0 { + return verificationKey{name: strconv.FormatUint(uint64(finding.RuleID), 10)} + } + case "IaC": + return verificationKey{name: normalized(finding.Title), detail: normalized(finding.SimilarityID)} + case "Secrets": + return verificationKey{name: normalized(finding.Title)} + case hooktelemetry.EngineOSS: + advisory := normalized(finding.CVE) + if finding.Malicious { + advisory = "malicious" + } + if advisory != "" { + return verificationKey{name: normalized(finding.PackageName), detail: advisory} + } + } + return verificationKey{} +} + +func (finding verificationFinding) identifier(engine string, key verificationKey) string { + if engine != "Secrets" { + if id := verificationValue(finding.VulnerabilityID); id != "" { + return id + } + } + switch engine { + case "IaC", "Secrets": + return verificationValue(finding.Title) + case hooktelemetry.EngineOSS: + if version := verificationValue(finding.PackageVersion); finding.Malicious && version != "" { + return key.name + "@" + version + } + return key.name + "@" + key.detail + default: + return key.name + } +} + +func verificationMatcher(engine string, output []byte) func(verificationKey) verificationOutcome { + present := make(map[verificationKey]bool) + add := func(finding verificationFinding) bool { + key := finding.key(engine) + if key.name == "" { + return false + } + present[key] = true + return true + } + switch engine { + case "Asca": + var scan grpcs.ScanResult + if json.Unmarshal(output, &scan) != nil || !scan.Status || scan.Error != nil { + return nil + } + for _, finding := range scan.ScanDetails { + if !add(verificationFinding{RuleID: finding.RuleID}) { + return nil + } + } + case "IaC": + var findings []iacrealtime.IacRealtimeResult + if json.Unmarshal(output, &findings) != nil || findings == nil { + return nil + } + for _, finding := range findings { + if !add(verificationFinding{Title: finding.Title, SimilarityID: finding.SimilarityID}) { + return nil + } + } + case "Secrets": + var findings []secretsrealtime.SecretsRealtimeResult + if json.Unmarshal(output, &findings) != nil || findings == nil { + return nil + } + for _, finding := range findings { + if !add(verificationFinding{Title: finding.Title}) { + return nil + } + } + case hooktelemetry.EngineOSS: + return ossVerificationMatcher(output) + } + return func(key verificationKey) verificationOutcome { + if present[key] { + return findingStillPresent + } + if engine == "IaC" { + if key.detail != "" && present[verificationKey{name: key.name}] { + return findingInconclusive + } + if key.detail == "" { + for match := range present { + if match.name == key.name { + return findingStillPresent + } + } + } + } + return findingVerified + } +} + +func ossVerificationMatcher(output []byte) func(verificationKey) verificationOutcome { + var scan ossrealtime.OssPackageResults + if json.Unmarshal(output, &scan) != nil || scan.Packages == nil { + return nil + } + return func(key verificationKey) verificationOutcome { + matched, classified := false, true + for _, pkg := range scan.Packages { + if !strings.EqualFold(strings.TrimSpace(pkg.PackageName), key.name) { + continue + } + matched = true + status := strings.ToLower(strings.TrimSpace(pkg.Status)) + if key.detail == "malicious" { + if status == "malicious" { + return findingStillPresent + } + classified = classified && status == "ok" + continue + } + validAdvisories := len(pkg.Vulnerabilities) > 0 + for _, vulnerability := range pkg.Vulnerabilities { + advisory := strings.TrimSpace(vulnerability.CVE) + if strings.EqualFold(advisory, key.detail) { + return findingStillPresent + } + validAdvisories = validAdvisories && advisory != "" + } + classified = classified && (status == "ok" || (status == "vulnerable" && validAdvisories)) + } + if matched && classified { + return findingVerified + } + return findingInconclusive + } +} + +func buildVerificationEvent(context verificationContext, agent, engine, source string, output []byte, scanErr error) ([]verificationFinding, *wrappers.DataForAITelemetry) { + var match func(verificationKey) verificationOutcome + if scanErr == nil { + match = verificationMatcher(engine, output) + } + counts := make(map[verificationKey]int) + for _, finding := range context.Findings { + counts[finding.key(engine)]++ + } + pending := make([]verificationFinding, 0, len(context.Findings)) + results := make(map[verificationOutcome][]string) + ids := make([]string, 0, len(context.Findings)) + severities := make([]string, 0, len(context.Findings)) + for _, finding := range context.Findings { + key := finding.key(engine) + id := finding.identifier(engine, key) + ids = append(ids, id) + severities = append(severities, finding.Severity) + outcome := findingInconclusive + if match != nil { + outcome = match(key) + if outcome == findingStillPresent && counts[key] > 1 { + outcome = findingInconclusive + } + } + results[outcome] = append(results[outcome], id) + if outcome != findingVerified { + pending = append(pending, finding) + } + } + + verified, stillPresent, inconclusive := results[findingVerified], results[findingStillPresent], results[findingInconclusive] + attrs := wrappers.EventAttributes{ + "remediationMode": hooktelemetry.RemediationModeSelfHealing, + "requestedCount": strconv.Itoa(len(ids)), + "stillPresentCount": strconv.Itoa(len(stillPresent)), + "inconclusiveCount": strconv.Itoa(len(inconclusive)), + } + for key, group := range map[string][]string{ + "vulnerabilityId": ids, "verifiedFindingIds": verified, + "stillPresentFindingIds": stillPresent, "inconclusiveFindingIds": inconclusive, + } { + if value := hooktelemetry.FormatFindingIDs(group); value != "" { + attrs[key] = value + } + } + for key, field := range map[string]string{"aiAgentSessionId": context.AIAgentSessionID, "machineUniqueId": context.MachineUniqueID} { + if value := verificationValue(field); value != "" { + attrs[key] = value + } + } + severity, _ := hooktelemetry.ScanSeveritySummary(severities) + event := &wrappers.DataForAITelemetry{ + Type: verificationEventType, SubType: "verifyFix", Agent: agent, AIProvider: strings.SplitN(agent, "-", 2)[0], + Engine: engine, ScanType: strings.ToLower(engine), TotalCount: len(verified), ProblemSeverity: severity, + AiAgentSessionId: attrs["aiAgentSessionId"], UniqueID: wrappers.GetUniqueID(), EventAttributes: &attrs, + StatusResult: fmt.Sprintf("Verified=%d,StillPresent=%d,Inconclusive=%d", len(verified), len(stillPresent), len(inconclusive)), + } + if len(inconclusive) != 0 { + event.Status = hooktelemetry.StatusFailure + attrs["reasonCode"] = "verification_incomplete" + if match == nil { + attrs["reasonCode"] = "verification_scan_failed" + } + } + absolute, _ := filepath.Abs(source) + hooktelemetry.Enrich(event, filepath.Dir(absolute)) + event.PluginType = "CLI" + if version := verificationValue(context.AgentVersion); version != "" { + event.AgentVersion = version + } + if version := verificationValue(context.PluginVersion); version != "" { + event.CxPluginVersion = version + } + return pending, event +} diff --git a/internal/commands/scan_verification_test.go b/internal/commands/scan_verification_test.go new file mode 100644 index 000000000..60aea7834 --- /dev/null +++ b/internal/commands/scan_verification_test.go @@ -0,0 +1,105 @@ +package commands + +import ( + "bytes" + "errors" + "fmt" + "os" + "path/filepath" + "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/cobra" + "github.com/stretchr/testify/require" +) + +func TestVerifyFixRescansOnceAndHidesFlag(t *testing.T) { + for _, tc := range []struct { + command, engine, finding, output string + }{ + {"asca", "Asca", `{"ruleId":1027}`, `{"status":true,"scan_details":[]}`}, + {"iac-realtime", "IaC", `{"title":"Example rule","similarityId":"original"}`, `[{"Title":"Example rule","SimilarityID":"other"}]`}, + {"oss-realtime", "oss", `{"packageName":"example","cve":"CVE-EXAMPLE"}`, `{"Packages":[{"PackageName":"example","Status":"OK"}]}`}, + {"secrets-realtime", "Secrets", `{"title":"Example rule"}`, `[]`}, + } { + t.Run(tc.command, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "findings.json") + require.NoError(t, os.WriteFile(path, []byte(`{"findings":[`+tc.finding+`],"aiAgentSessionId":"agent-session"}`), 0600)) + scan := &cobra.Command{Use: "scan"} + scan.PersistentFlags().String(params.AgentFlag, params.DefaultAgent, "") + calls := 0 + child := &cobra.Command{Use: tc.command, RunE: func(cmd *cobra.Command, _ []string) error { + calls++ + _, err := fmt.Fprintln(cmd.OutOrStdout(), tc.output) + return err + }} + scan.AddCommand(child) + var event *wrappers.DataForAITelemetry + enableScanVerification(scan, mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + event = data + return nil + }}) + require.True(t, child.Flags().Lookup(verifyFixFlag).Hidden) + require.NotContains(t, child.UsageString(), "--verify-fix") + + var stdout, stderr bytes.Buffer + scan.SetOut(&stdout) + scan.SetErr(&stderr) + scan.SetArgs([]string{tc.command, "--agent", "copilot-cli", "--verify-fix", path}) + require.NoError(t, scan.Execute()) + require.Equal(t, 1, calls) + require.Equal(t, tc.output+"\n", stdout.String()) + require.Contains(t, stderr.String(), "Verified=1,StillPresent=0,Inconclusive=0") + require.NotNil(t, event) + require.Equal(t, tc.engine, event.Engine) + require.Equal(t, "hooks-verify", event.Type) + require.Equal(t, "verifyFix", event.SubType) + require.Equal(t, "agent-session", event.AiAgentSessionId) + require.Equal(t, 1, event.TotalCount) + context, _, err := readVerificationContext(path) + require.NoError(t, err) + require.Empty(t, context.Findings) + }) + } +} + +func TestVerifyFixKeepsPendingWhenPublishFails(t *testing.T) { + path := filepath.Join(t.TempDir(), "findings.json") + original := []byte(`{"findings":[{"ruleId":1027}]}`) + require.NoError(t, os.WriteFile(path, original, 0600)) + cmd := &cobra.Command{Use: "asca", RunE: func(cmd *cobra.Command, _ []string) error { + _, err := fmt.Fprint(cmd.OutOrStdout(), `{"status":true,"scan_details":[]}`) + return err + }} + cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") + sends := 0 + addScanVerification(cmd, "Asca", mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + sends++ + return errors.New("publish unconfirmed") + }}) + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + cmd.SetArgs([]string{"--agent=copilot-cli", "--verify-fix", path}) + require.NoError(t, cmd.Execute()) + require.Equal(t, 1, sends) + require.Contains(t, stderr.String(), "Verification telemetry was not confirmed") + actual, err := os.ReadFile(path) + require.NoError(t, err) + require.Equal(t, original, actual) +} + +func TestVerifyFixDoesNotCountAmbiguousOrMissingFindingsAsFixed(t *testing.T) { + ctx := verificationContext{Findings: []verificationFinding{{RuleID: 1027}, {RuleID: 1027}}} + pending, event := buildVerificationEvent(ctx, "Copilot-cli", "Asca", "Example.java", []byte(`{"status":true,"scan_details":[{"rule_id":1027}]}`), nil) + require.Len(t, pending, 2) + require.Equal(t, 0, event.TotalCount) + require.Equal(t, "Verified=0,StillPresent=0,Inconclusive=2", event.StatusResult) + + ctx.Findings = []verificationFinding{{PackageName: "example", CVE: "CVE-EXAMPLE"}} + pending, event = buildVerificationEvent(ctx, "Copilot-cli", "oss", "package.json", []byte(`{"Packages":[]}`), nil) + require.Len(t, pending, 1) + require.Equal(t, 0, event.TotalCount) +} diff --git a/internal/commands/telemetry.go b/internal/commands/telemetry.go index 8c0f278ea..18b06c18e 100644 --- a/internal/commands/telemetry.go +++ b/internal/commands/telemetry.go @@ -119,17 +119,6 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm eventAttributesStr, _ := cmd.Flags().GetString(params.EventAttributesFlag) apiVersion, _ := cmd.Flags().GetString(params.ApiVersionFlag) - sender := telemetryWrapper - if strings.EqualFold(strings.TrimSpace(eventType), verificationEventType) { - if transport, ok := telemetryWrapper.(*wrappers.TelemetryHTTPWrapper); ok { - // The skill starts a separate CLI process, so warm its access token before using the short hook send. - if _, err := wrappers.GetAccessToken(); err != nil { - return errors.Wrap(err, "Failed to authenticate verification telemetry") - } - sender = transport.ForAgentHooks() - } - } - uniqueID := wrappers.GetUniqueID() var sessionID string @@ -141,7 +130,7 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm eventAttrs := parseEventAttributes(eventAttributesStr) - err := sender.SendAIDataToLog(&wrappers.DataForAITelemetry{ + event := &wrappers.DataForAITelemetry{ AIProvider: aiProvider, ProblemSeverity: problemSeverity, Type: eventType, @@ -160,10 +149,15 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm UniqueID: uniqueID, SessionID: sessionID, EventAttributes: eventAttrs, - }) - + } + var err error + if strings.EqualFold(strings.TrimSpace(eventType), verificationEventType) { + err = sendVerificationTelemetry(telemetryWrapper, event) + } else { + err = telemetryWrapper.SendAIDataToLog(event) + } if err != nil { - return errors.Wrapf(err, "%s", "Failed logging the data") + return errors.Wrap(err, "Failed logging the data") } return nil From 8dc1a056cf60d5425ad9af86c62d76f8304b4a15 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:44:18 +0530 Subject: [PATCH 11/19] AST-195928 Remove realtime fix verification telemetry --- internal/commands/root.go | 1 - internal/commands/scan_verification.go | 420 -------------------- internal/commands/scan_verification_test.go | 105 ----- internal/commands/telemetry.go | 14 +- internal/commands/telemetry_test.go | 40 -- internal/wrappers/client_test.go | 47 --- internal/wrappers/telemetry-http.go | 7 +- 7 files changed, 5 insertions(+), 629 deletions(-) delete mode 100644 internal/commands/scan_verification.go delete mode 100644 internal/commands/scan_verification_test.go diff --git a/internal/commands/root.go b/internal/commands/root.go index b42e5c95e..479c9c026 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -211,7 +211,6 @@ func NewAstCLI( realTimeWrapper, tenantWrapper, ) - enableScanVerification(scanCmd, telemetryWrapper) projectCmd := NewProjectCommand(applicationsWrapper, projectsWrapper, groupsWrapper, accessManagementWrapper, featureFlagsWrapper) dastEnvironmentsCmd := dast.NewDastEnvironmentsCommand(dastEnvironmentsWrapper) diff --git a/internal/commands/scan_verification.go b/internal/commands/scan_verification.go deleted file mode 100644 index 365ea4c3d..000000000 --- a/internal/commands/scan_verification.go +++ /dev/null @@ -1,420 +0,0 @@ -package commands - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "path/filepath" - "strconv" - "strings" - "unicode" - - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" - "github.com/checkmarx/ast-cli/internal/params" - "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" - "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" - "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" - "github.com/spf13/cobra" -) - -const ( - verifyFixFlag = "verify-fix" - verificationContextLimit = 64 * 1024 -) - -type verificationFinding struct { - RuleID uint32 `json:"ruleId,omitempty"` - Title string `json:"title,omitempty"` - SimilarityID string `json:"similarityId,omitempty"` - PackageName string `json:"packageName,omitempty"` - PackageVersion string `json:"packageVersion,omitempty"` - CVE string `json:"cve,omitempty"` - Malicious bool `json:"malicious,omitempty"` - VulnerabilityID string `json:"vulnerabilityId,omitempty"` - Severity string `json:"severity,omitempty"` -} - -type verificationContext struct { - Findings []verificationFinding `json:"findings"` - AIAgentSessionID string `json:"aiAgentSessionId,omitempty"` - AgentVersion string `json:"agentVersion,omitempty"` - PluginVersion string `json:"cxPluginVersion,omitempty"` - MachineUniqueID string `json:"machineUniqueId,omitempty"` -} - -type verificationKey struct { - name string - detail string -} - -type verificationOutcome string - -const ( - findingVerified verificationOutcome = "verified" - findingStillPresent verificationOutcome = "stillPresent" - findingInconclusive verificationOutcome = "inconclusive" -) - -func enableScanVerification(scan *cobra.Command, sender wrappers.TelemetryWrapper) { - engines := map[string]string{ - "asca": "Asca", "iac-realtime": "IaC", "oss-realtime": hooktelemetry.EngineOSS, "secrets-realtime": "Secrets", - } - for _, cmd := range scan.Commands() { - if engine, ok := engines[cmd.Name()]; ok { - addScanVerification(cmd, engine, sender) - } - } -} - -func addScanVerification(cmd *cobra.Command, engine string, sender wrappers.TelemetryWrapper) { - flags := cmd.Flags() - flags.String(verifyFixFlag, "", "Path to the original Dev Assist finding context") - _ = flags.MarkHidden(verifyFixFlag) - run := cmd.RunE - cmd.RunE = func(cmd *cobra.Command, args []string) error { - if !cmd.Flags().Changed(verifyFixFlag) { - return run(cmd, args) - } - agent := loginTelemetryAgent(cmd) - rawAgent, _ := cmd.Flags().GetString(params.AgentFlag) - if cmd.Flags().Changed(params.AgentFlag) && strings.EqualFold(strings.TrimSpace(rawAgent), "copilot-vscode") { - agent = "Copilot-VSCode" - } - if agent == "" { - return fmt.Errorf("--%s requires an explicit --agent for a supported Dev Assist hook client", verifyFixFlag) - } - if path, _ := cmd.Flags().GetString(params.IgnoredFilePathFlag); path != "" { - return fmt.Errorf("--%s requires a scan without --%s", verifyFixFlag, params.IgnoredFilePathFlag) - } - - path, _ := cmd.Flags().GetString(verifyFixFlag) - context, original, err := readVerificationContext(path) - if err != nil { - return fmt.Errorf("--%s: %w", verifyFixFlag, err) - } - if len(context.Findings) == 0 { - return run(cmd, args) - } - for _, finding := range context.Findings { - if finding.key(engine).name == "" { - return fmt.Errorf("--%s: context contains a finding without a valid %s identity", verifyFixFlag, engine) - } - } - source, _ := cmd.Flags().GetString(params.SourcesFlag) - if contextInfo, ctxErr := os.Stat(path); ctxErr == nil { - if sourceInfo, sourceErr := os.Stat(source); sourceErr == nil && os.SameFile(contextInfo, sourceInfo) { - return fmt.Errorf("--%s context must be separate from the file being scanned", verifyFixFlag) - } - } - - var output bytes.Buffer - stdout := cmd.OutOrStdout() - cmd.SetOut(io.MultiWriter(stdout, &output)) - defer cmd.SetOut(stdout) - scanErr := run(cmd, args) - pending, event := buildVerificationEvent(context, agent, engine, source, output.Bytes(), scanErr) - fmt.Fprintln(cmd.ErrOrStderr(), "Verification: "+event.StatusResult) - - if err := sendVerificationTelemetry(sender, event); err != nil { - fmt.Fprintln(cmd.ErrOrStderr(), "Verification telemetry was not confirmed.") - } else if len(pending) < len(context.Findings) { - context.Findings = pending - if err := saveVerificationContext(path, original, context); err != nil { - fmt.Fprintln(cmd.ErrOrStderr(), "Could not save pending findings for the next verification attempt.") - } - } - return scanErr - } -} - -func sendVerificationTelemetry(sender wrappers.TelemetryWrapper, event *wrappers.DataForAITelemetry) error { - if sender == nil { - return fmt.Errorf("verification telemetry sender is unavailable") - } - if transport, ok := sender.(*wrappers.TelemetryHTTPWrapper); ok { - if _, err := wrappers.GetAccessToken(); err != nil { - return fmt.Errorf("authenticate verification telemetry: %w", err) - } - sender = transport.ForAgentHooks() - } - return sender.SendAIDataToLog(event) -} - -func readVerificationContext(path string) (verificationContext, []byte, error) { - var context verificationContext - file, err := os.Open(path) - if err != nil { - return context, nil, err - } - defer file.Close() - data, err := io.ReadAll(io.LimitReader(file, verificationContextLimit+1)) - if err != nil { - return context, nil, err - } - if len(data) > verificationContextLimit { - return context, nil, fmt.Errorf("finding context exceeds 64 KiB") - } - if err := json.Unmarshal(bytes.TrimPrefix(data, []byte{0xef, 0xbb, 0xbf}), &context); err != nil { - return context, nil, fmt.Errorf("invalid finding context: %w", err) - } - if context.Findings == nil { - return context, nil, fmt.Errorf("finding context requires a findings array") - } - return context, data, nil -} - -func saveVerificationContext(path string, original []byte, context verificationContext) error { - _, current, err := readVerificationContext(path) - if err != nil { - return err - } - if !bytes.Equal(current, original) { - return fmt.Errorf("finding context changed during verification") - } - file, err := os.CreateTemp(filepath.Dir(path), ".cx-verification-*.json") - if err != nil { - return err - } - defer os.Remove(file.Name()) - writeErr := json.NewEncoder(file).Encode(context) - closeErr := file.Close() - if writeErr != nil { - return writeErr - } - if closeErr != nil { - return closeErr - } - return os.Rename(file.Name(), path) -} - -func verificationValue(value string) string { - value = strings.TrimSpace(value) - if len(value) > 256 || strings.ContainsRune(value, ';') || strings.IndexFunc(value, unicode.IsControl) >= 0 { - return "" - } - return value -} - -func (finding verificationFinding) key(engine string) verificationKey { - normalized := func(value string) string { return strings.ToLower(verificationValue(value)) } - switch engine { - case "Asca": - if finding.RuleID != 0 { - return verificationKey{name: strconv.FormatUint(uint64(finding.RuleID), 10)} - } - case "IaC": - return verificationKey{name: normalized(finding.Title), detail: normalized(finding.SimilarityID)} - case "Secrets": - return verificationKey{name: normalized(finding.Title)} - case hooktelemetry.EngineOSS: - advisory := normalized(finding.CVE) - if finding.Malicious { - advisory = "malicious" - } - if advisory != "" { - return verificationKey{name: normalized(finding.PackageName), detail: advisory} - } - } - return verificationKey{} -} - -func (finding verificationFinding) identifier(engine string, key verificationKey) string { - if engine != "Secrets" { - if id := verificationValue(finding.VulnerabilityID); id != "" { - return id - } - } - switch engine { - case "IaC", "Secrets": - return verificationValue(finding.Title) - case hooktelemetry.EngineOSS: - if version := verificationValue(finding.PackageVersion); finding.Malicious && version != "" { - return key.name + "@" + version - } - return key.name + "@" + key.detail - default: - return key.name - } -} - -func verificationMatcher(engine string, output []byte) func(verificationKey) verificationOutcome { - present := make(map[verificationKey]bool) - add := func(finding verificationFinding) bool { - key := finding.key(engine) - if key.name == "" { - return false - } - present[key] = true - return true - } - switch engine { - case "Asca": - var scan grpcs.ScanResult - if json.Unmarshal(output, &scan) != nil || !scan.Status || scan.Error != nil { - return nil - } - for _, finding := range scan.ScanDetails { - if !add(verificationFinding{RuleID: finding.RuleID}) { - return nil - } - } - case "IaC": - var findings []iacrealtime.IacRealtimeResult - if json.Unmarshal(output, &findings) != nil || findings == nil { - return nil - } - for _, finding := range findings { - if !add(verificationFinding{Title: finding.Title, SimilarityID: finding.SimilarityID}) { - return nil - } - } - case "Secrets": - var findings []secretsrealtime.SecretsRealtimeResult - if json.Unmarshal(output, &findings) != nil || findings == nil { - return nil - } - for _, finding := range findings { - if !add(verificationFinding{Title: finding.Title}) { - return nil - } - } - case hooktelemetry.EngineOSS: - return ossVerificationMatcher(output) - } - return func(key verificationKey) verificationOutcome { - if present[key] { - return findingStillPresent - } - if engine == "IaC" { - if key.detail != "" && present[verificationKey{name: key.name}] { - return findingInconclusive - } - if key.detail == "" { - for match := range present { - if match.name == key.name { - return findingStillPresent - } - } - } - } - return findingVerified - } -} - -func ossVerificationMatcher(output []byte) func(verificationKey) verificationOutcome { - var scan ossrealtime.OssPackageResults - if json.Unmarshal(output, &scan) != nil || scan.Packages == nil { - return nil - } - return func(key verificationKey) verificationOutcome { - matched, classified := false, true - for _, pkg := range scan.Packages { - if !strings.EqualFold(strings.TrimSpace(pkg.PackageName), key.name) { - continue - } - matched = true - status := strings.ToLower(strings.TrimSpace(pkg.Status)) - if key.detail == "malicious" { - if status == "malicious" { - return findingStillPresent - } - classified = classified && status == "ok" - continue - } - validAdvisories := len(pkg.Vulnerabilities) > 0 - for _, vulnerability := range pkg.Vulnerabilities { - advisory := strings.TrimSpace(vulnerability.CVE) - if strings.EqualFold(advisory, key.detail) { - return findingStillPresent - } - validAdvisories = validAdvisories && advisory != "" - } - classified = classified && (status == "ok" || (status == "vulnerable" && validAdvisories)) - } - if matched && classified { - return findingVerified - } - return findingInconclusive - } -} - -func buildVerificationEvent(context verificationContext, agent, engine, source string, output []byte, scanErr error) ([]verificationFinding, *wrappers.DataForAITelemetry) { - var match func(verificationKey) verificationOutcome - if scanErr == nil { - match = verificationMatcher(engine, output) - } - counts := make(map[verificationKey]int) - for _, finding := range context.Findings { - counts[finding.key(engine)]++ - } - pending := make([]verificationFinding, 0, len(context.Findings)) - results := make(map[verificationOutcome][]string) - ids := make([]string, 0, len(context.Findings)) - severities := make([]string, 0, len(context.Findings)) - for _, finding := range context.Findings { - key := finding.key(engine) - id := finding.identifier(engine, key) - ids = append(ids, id) - severities = append(severities, finding.Severity) - outcome := findingInconclusive - if match != nil { - outcome = match(key) - if outcome == findingStillPresent && counts[key] > 1 { - outcome = findingInconclusive - } - } - results[outcome] = append(results[outcome], id) - if outcome != findingVerified { - pending = append(pending, finding) - } - } - - verified, stillPresent, inconclusive := results[findingVerified], results[findingStillPresent], results[findingInconclusive] - attrs := wrappers.EventAttributes{ - "remediationMode": hooktelemetry.RemediationModeSelfHealing, - "requestedCount": strconv.Itoa(len(ids)), - "stillPresentCount": strconv.Itoa(len(stillPresent)), - "inconclusiveCount": strconv.Itoa(len(inconclusive)), - } - for key, group := range map[string][]string{ - "vulnerabilityId": ids, "verifiedFindingIds": verified, - "stillPresentFindingIds": stillPresent, "inconclusiveFindingIds": inconclusive, - } { - if value := hooktelemetry.FormatFindingIDs(group); value != "" { - attrs[key] = value - } - } - for key, field := range map[string]string{"aiAgentSessionId": context.AIAgentSessionID, "machineUniqueId": context.MachineUniqueID} { - if value := verificationValue(field); value != "" { - attrs[key] = value - } - } - severity, _ := hooktelemetry.ScanSeveritySummary(severities) - event := &wrappers.DataForAITelemetry{ - Type: verificationEventType, SubType: "verifyFix", Agent: agent, AIProvider: strings.SplitN(agent, "-", 2)[0], - Engine: engine, ScanType: strings.ToLower(engine), TotalCount: len(verified), ProblemSeverity: severity, - AiAgentSessionId: attrs["aiAgentSessionId"], UniqueID: wrappers.GetUniqueID(), EventAttributes: &attrs, - StatusResult: fmt.Sprintf("Verified=%d,StillPresent=%d,Inconclusive=%d", len(verified), len(stillPresent), len(inconclusive)), - } - if len(inconclusive) != 0 { - event.Status = hooktelemetry.StatusFailure - attrs["reasonCode"] = "verification_incomplete" - if match == nil { - attrs["reasonCode"] = "verification_scan_failed" - } - } - absolute, _ := filepath.Abs(source) - hooktelemetry.Enrich(event, filepath.Dir(absolute)) - event.PluginType = "CLI" - if version := verificationValue(context.AgentVersion); version != "" { - event.AgentVersion = version - } - if version := verificationValue(context.PluginVersion); version != "" { - event.CxPluginVersion = version - } - return pending, event -} diff --git a/internal/commands/scan_verification_test.go b/internal/commands/scan_verification_test.go deleted file mode 100644 index 60aea7834..000000000 --- a/internal/commands/scan_verification_test.go +++ /dev/null @@ -1,105 +0,0 @@ -package commands - -import ( - "bytes" - "errors" - "fmt" - "os" - "path/filepath" - "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/cobra" - "github.com/stretchr/testify/require" -) - -func TestVerifyFixRescansOnceAndHidesFlag(t *testing.T) { - for _, tc := range []struct { - command, engine, finding, output string - }{ - {"asca", "Asca", `{"ruleId":1027}`, `{"status":true,"scan_details":[]}`}, - {"iac-realtime", "IaC", `{"title":"Example rule","similarityId":"original"}`, `[{"Title":"Example rule","SimilarityID":"other"}]`}, - {"oss-realtime", "oss", `{"packageName":"example","cve":"CVE-EXAMPLE"}`, `{"Packages":[{"PackageName":"example","Status":"OK"}]}`}, - {"secrets-realtime", "Secrets", `{"title":"Example rule"}`, `[]`}, - } { - t.Run(tc.command, func(t *testing.T) { - path := filepath.Join(t.TempDir(), "findings.json") - require.NoError(t, os.WriteFile(path, []byte(`{"findings":[`+tc.finding+`],"aiAgentSessionId":"agent-session"}`), 0600)) - scan := &cobra.Command{Use: "scan"} - scan.PersistentFlags().String(params.AgentFlag, params.DefaultAgent, "") - calls := 0 - child := &cobra.Command{Use: tc.command, RunE: func(cmd *cobra.Command, _ []string) error { - calls++ - _, err := fmt.Fprintln(cmd.OutOrStdout(), tc.output) - return err - }} - scan.AddCommand(child) - var event *wrappers.DataForAITelemetry - enableScanVerification(scan, mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - event = data - return nil - }}) - require.True(t, child.Flags().Lookup(verifyFixFlag).Hidden) - require.NotContains(t, child.UsageString(), "--verify-fix") - - var stdout, stderr bytes.Buffer - scan.SetOut(&stdout) - scan.SetErr(&stderr) - scan.SetArgs([]string{tc.command, "--agent", "copilot-cli", "--verify-fix", path}) - require.NoError(t, scan.Execute()) - require.Equal(t, 1, calls) - require.Equal(t, tc.output+"\n", stdout.String()) - require.Contains(t, stderr.String(), "Verified=1,StillPresent=0,Inconclusive=0") - require.NotNil(t, event) - require.Equal(t, tc.engine, event.Engine) - require.Equal(t, "hooks-verify", event.Type) - require.Equal(t, "verifyFix", event.SubType) - require.Equal(t, "agent-session", event.AiAgentSessionId) - require.Equal(t, 1, event.TotalCount) - context, _, err := readVerificationContext(path) - require.NoError(t, err) - require.Empty(t, context.Findings) - }) - } -} - -func TestVerifyFixKeepsPendingWhenPublishFails(t *testing.T) { - path := filepath.Join(t.TempDir(), "findings.json") - original := []byte(`{"findings":[{"ruleId":1027}]}`) - require.NoError(t, os.WriteFile(path, original, 0600)) - cmd := &cobra.Command{Use: "asca", RunE: func(cmd *cobra.Command, _ []string) error { - _, err := fmt.Fprint(cmd.OutOrStdout(), `{"status":true,"scan_details":[]}`) - return err - }} - cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") - sends := 0 - addScanVerification(cmd, "Asca", mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - sends++ - return errors.New("publish unconfirmed") - }}) - var stdout, stderr bytes.Buffer - cmd.SetOut(&stdout) - cmd.SetErr(&stderr) - cmd.SetArgs([]string{"--agent=copilot-cli", "--verify-fix", path}) - require.NoError(t, cmd.Execute()) - require.Equal(t, 1, sends) - require.Contains(t, stderr.String(), "Verification telemetry was not confirmed") - actual, err := os.ReadFile(path) - require.NoError(t, err) - require.Equal(t, original, actual) -} - -func TestVerifyFixDoesNotCountAmbiguousOrMissingFindingsAsFixed(t *testing.T) { - ctx := verificationContext{Findings: []verificationFinding{{RuleID: 1027}, {RuleID: 1027}}} - pending, event := buildVerificationEvent(ctx, "Copilot-cli", "Asca", "Example.java", []byte(`{"status":true,"scan_details":[{"rule_id":1027}]}`), nil) - require.Len(t, pending, 2) - require.Equal(t, 0, event.TotalCount) - require.Equal(t, "Verified=0,StillPresent=0,Inconclusive=2", event.StatusResult) - - ctx.Findings = []verificationFinding{{PackageName: "example", CVE: "CVE-EXAMPLE"}} - pending, event = buildVerificationEvent(ctx, "Copilot-cli", "oss", "package.json", []byte(`{"Packages":[]}`), nil) - require.Len(t, pending, 1) - require.Equal(t, 0, event.TotalCount) -} diff --git a/internal/commands/telemetry.go b/internal/commands/telemetry.go index 18b06c18e..6f2a82728 100644 --- a/internal/commands/telemetry.go +++ b/internal/commands/telemetry.go @@ -15,7 +15,6 @@ import ( const ( keyValuePairsSplit = 2 authenticationEventType = "authentication" - verificationEventType = "hooks-verify" telemetrySuccessStatus = "success" ) @@ -130,7 +129,7 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm eventAttrs := parseEventAttributes(eventAttributesStr) - event := &wrappers.DataForAITelemetry{ + err := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{ AIProvider: aiProvider, ProblemSeverity: problemSeverity, Type: eventType, @@ -149,15 +148,10 @@ func runTelemetryAI(telemetryWrapper wrappers.TelemetryWrapper) func(*cobra.Comm UniqueID: uniqueID, SessionID: sessionID, EventAttributes: eventAttrs, - } - var err error - if strings.EqualFold(strings.TrimSpace(eventType), verificationEventType) { - err = sendVerificationTelemetry(telemetryWrapper, event) - } else { - err = telemetryWrapper.SendAIDataToLog(event) - } + }) + if err != nil { - return errors.Wrap(err, "Failed logging the data") + return errors.Wrapf(err, "%s", "Failed logging the data") } return nil diff --git a/internal/commands/telemetry_test.go b/internal/commands/telemetry_test.go index 0e601a528..e0848d46a 100644 --- a/internal/commands/telemetry_test.go +++ b/internal/commands/telemetry_test.go @@ -3,12 +3,7 @@ package commands import ( - "encoding/base64" - "encoding/json" "io" - "net/http" - "net/http/httptest" - "strings" "testing" "github.com/checkmarx/ast-cli/internal/params" @@ -121,41 +116,6 @@ func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { "telemetry", "ai", "--ai-provider", "Cursor", "--problem-severity", "Critical", "--type", "click", "--sub-type", "ast-results.viewPackageDetails", "--agent", "Cursor", "--engine", "secrets") } -func TestRunTelemetryAI_VerificationReportsHTTPFailure(t *testing.T) { - t.Setenv("CX_TELEMETRY_DEV_URL", "") - previousExpiry := viper.Get(params.TokenExpirySecondsKey) - previousOverride := viper.Get(params.ApikeyOverrideFlag) - t.Cleanup(func() { - viper.Set(params.TokenExpirySecondsKey, previousExpiry) - viper.Set(params.ApikeyOverrideFlag, previousOverride) - wrappers.InvalidateAccessTokenCache() - }) - viper.Set(params.TokenExpirySecondsKey, 300) - viper.Set(params.ApikeyOverrideFlag, false) - - received := make(chan string, 4) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - received <- r.URL.Path - w.WriteHeader(http.StatusForbidden) - })) - t.Cleanup(server.Close) - - header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"none","typ":"JWT"}`)) - claims, err := json.Marshal(map[string]string{wrappers.BaseURLKey: server.URL}) - assert.NilError(t, err) - wrappers.CacheAuthenticatedAccessToken(header + "." + base64.RawURLEncoding.EncodeToString(claims) + ".sig") - - cmd := NewTelemetryCommand(wrappers.NewHTTPTelemetryAIWrapper("telemetry")) - cmd.SetOut(io.Discard) - cmd.SetArgs([]string{"ai", "--type", "hooks-verify", "--agent", "Copilot-VSCode", "--sub-type", "verifyFix"}) - err = cmd.Execute() - if err == nil || !strings.Contains(err.Error(), "403 Forbidden") { - t.Fatalf("expected the telemetry HTTP rejection, got %v", err) - } - assert.Equal(t, len(received), 1) - assert.Equal(t, <-received, "/telemetry/log") -} - func TestTelemetryHelp(t *testing.T) { execCmdNilAssertion(t, "help", "telemetry", "ai") } diff --git a/internal/wrappers/client_test.go b/internal/wrappers/client_test.go index 2c617035c..0e58a1503 100644 --- a/internal/wrappers/client_test.go +++ b/internal/wrappers/client_test.go @@ -359,53 +359,6 @@ func TestAgentHookTelemetryTimesOutWithoutRetrying(t *testing.T) { } } -func TestVerificationTelemetryRequiresPublishAcknowledgement(t *testing.T) { - t.Setenv("CX_TELEMETRY_DEV_URL", "") - for key, value := range map[string]any{ - commonParams.IgnoreProxyKey: true, - commonParams.ApikeyOverrideFlag: false, - commonParams.TokenExpirySecondsKey: 300, - } { - previous := viper.Get(key) - t.Cleanup(func() { viper.Set(key, previous) }) - viper.Set(key, value) - } - credentialsMutex.Lock() - previousToken, previousTime := cachedAccessToken, cachedAccessTime - credentialsMutex.Unlock() - t.Cleanup(func() { - credentialsMutex.Lock() - defer credentialsMutex.Unlock() - cachedAccessToken, cachedAccessTime = previousToken, previousTime - }) - for _, tc := range []struct { - name string - status int - acknowledgement string - wantError bool - }{ - {name: "broker confirmed", status: http.StatusOK, acknowledgement: "true"}, - {name: "legacy HTTP success", status: http.StatusOK, wantError: true}, - {name: "publish failed", status: http.StatusInternalServerError, wantError: true}, - } { - t.Run(tc.name, func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - if tc.acknowledgement != "" { - w.Header().Set("X-Cx-Telemetry-Published", tc.acknowledgement) - } - w.WriteHeader(tc.status) - })) - defer server.Close() - writeCredentialsToCache(unsignedJWT(map[string]any{BaseURLKey: server.URL})) - wrapper := NewHTTPTelemetryAIWrapper("api/realtime-scanner").ForAgentHooks() - err := wrapper.SendAIDataToLog(&DataForAITelemetry{Type: "hooks-verify"}) - if (err != nil) != tc.wantError { - t.Fatalf("SendAIDataToLog error = %v, want error: %t", err, tc.wantError) - } - }) - } -} - // TestExtractFromTokenClaims covers fix #10: the "aud" (and any) claim may be a // string or an array of strings. The array form must not panic. func TestExtractFromTokenClaims(t *testing.T) { diff --git a/internal/wrappers/telemetry-http.go b/internal/wrappers/telemetry-http.go index 120d5919e..10a3ad365 100644 --- a/internal/wrappers/telemetry-http.go +++ b/internal/wrappers/telemetry-http.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/json" "net/http" - "strings" commonParams "github.com/checkmarx/ast-cli/internal/params" "github.com/pkg/errors" @@ -54,13 +53,9 @@ func (r *TelemetryHTTPWrapper) SendAIDataToLog(data *DataForAITelemetry) error { _ = resp.Body.Close() } }() - verification := strings.EqualFold(strings.TrimSpace(data.Type), "hooks-verify") - if (r.agentHooks || verification) && (resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices) { + if r.agentHooks && (resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices) { return errors.Errorf("failed to log hook telemetry, status code: %s", resp.Status) } - if verification && resp.Header.Get("X-Cx-Telemetry-Published") != "true" { - return errors.New("verification telemetry publish was not confirmed") - } switch resp.StatusCode { case http.StatusBadRequest, http.StatusInternalServerError: return errors.Errorf("Failed to log the data, status code: %s", resp.Status) From 1d9754708ec5ebcbebdb11b8ce4256779016c9fc Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:49:53 +0530 Subject: [PATCH 12/19] AST-195928 Report CLI agent telemetry fields from the design Use -CLI labels with Success/Failure status and the design's statusResult messages, send zero-finding scans as v2 detection events, report login failures, attach agent session IDs to package-install events, map ignore subTypes per engine, and fill missing login versions from the plugin context file. Co-authored-by: Cursor --- internal/commands/agenthooks/cx/hooks.go | 37 ++++- internal/commands/agenthooks/cx/hooks_test.go | 7 +- .../agenthooks/guardrails/asca/asca.go | 38 +---- .../agenthooks/guardrails/asca/asca_test.go | 41 +----- .../agenthooks/guardrails/kics/kics.go | 41 +----- .../agenthooks/guardrails/kics/kics_test.go | 43 +----- .../agenthooks/guardrails/secrets/secrets.go | 37 +---- .../agenthooks/hooktelemetry/hooktelemetry.go | 137 ++++++++++++++++-- .../hooktelemetry/hooktelemetry_test.go | 74 +++++++++- .../commands/agenthooks/hostenv/hostenv.go | 9 +- .../agenthooks/hostenv/hostenv_test.go | 10 +- internal/commands/agenthooks/sca/sca.go | 50 ++----- internal/commands/agenthooks/sca/sca_test.go | 2 +- .../agenthooks/sca/telemetry_ids_test.go | 17 ++- internal/commands/auth_login.go | 86 ++++++++--- internal/commands/auth_login_test.go | 100 ++++++++++++- internal/commands/ignore_vulnerability.go | 32 +++- .../ignore_vulnerability_telemetry_test.go | 63 +++++++- 18 files changed, 534 insertions(+), 290 deletions(-) diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index 3278dc2e6..9e44267a1 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -7,7 +7,11 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/Checkmarx/ast-cx-hooks/claude" + "github.com/Checkmarx/ast-cx-hooks/codex" + "github.com/Checkmarx/ast-cx-hooks/copilot" + "github.com/Checkmarx/ast-cx-hooks/copilotcli" "github.com/Checkmarx/ast-cx-hooks/cursor" + "github.com/Checkmarx/ast-cx-hooks/gemini" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/asca" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/kics" @@ -70,6 +74,27 @@ func sessionIDFromToolCall(ev *agenthooks.ToolCallEvent) string { return "" } +// telemetrySessionIDFromToolCall is the agent's session id for a ToolCall event, from every agent's raw +// payload. Telemetry only: the session tally keeps sessionIDFromToolCall's bucket. +func telemetrySessionIDFromToolCall(ev *agenthooks.ToolCallEvent) string { + switch e := ev.Raw.(type) { + case *claude.PreToolUseEvent: + return e.SessionID + case *cursor.ShellPreEvent: + return e.ConversationID + case *copilotcli.PreToolUseEvent: + return e.SessionID + case *copilot.PreToolUseEvent: + return e.SessionID + case *codex.PreToolUseEvent: + return e.SessionID + case *gemini.BeforeToolEvent: + return e.SessionID + default: + return "" + } +} + // cxBeforeToolCall gates shell execution against the organization's blacklist, // tool rules, and the SCA guardrail (malicious / vulnerable package installs). func cxBeforeToolCall(ev agenthooks.ToolCallEvent) agenthooks.ToolVerdict { @@ -87,9 +112,10 @@ func cxBeforeToolCall(ev agenthooks.ToolCallEvent) agenthooks.ToolVerdict { if scaScanner != nil && scannerOn(ev.Agent, scannerconfig.SCA) { agent := agentToString(ev.Agent) sid := sessionIDFromToolCall(&ev) - if finding, remediation, severity := scaScanner.CheckBashInstall(ev.Command, ev.WorkDir, agent, sid); finding != "" && !belowThreshold(ev.Agent, severity) { + telemetrySID := telemetrySessionIDFromToolCall(&ev) + if finding, remediation, severity := scaScanner.CheckBashInstall(ev.Command, ev.WorkDir, agent, telemetrySID); finding != "" && !belowThreshold(ev.Agent, severity) { sessiontally.Add(sid, engineSca, 1, 1) - logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, sid, ev.WorkDir, remediation) + logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, telemetrySID, ev.WorkDir, remediation) return agenthooks.DenyWithContext(finding, remediation) } } @@ -313,7 +339,7 @@ func logRemediationTelemetry(agent, engine, severity, sessionID, workDir, guidan UniqueID: wrappers.GetUniqueID(), Type: "hooks-remediate", SubType: "fixWithAIAssist", - StatusResult: "Remediation instructions delivered.", + StatusResult: hooktelemetry.RemediationSucceeded, TotalCount: count, ProblemSeverity: severity, AiAgentSessionId: sessionID, @@ -321,7 +347,7 @@ func logRemediationTelemetry(agent, engine, severity, sessionID, workDir, guidan } if strings.TrimSpace(guidance) == "" { telemetryData.Status = hooktelemetry.StatusFailure - telemetryData.StatusResult = "Remediation instructions were unavailable." + telemetryData.StatusResult = hooktelemetry.FailureResult("Remediation", "remediation_instructions_missing", hooktelemetry.ErrorCodeNone) telemetryData.TotalCount = 0 attrs["reasonCode"] = "remediation_instructions_missing" } @@ -341,8 +367,9 @@ func switchesApply(agent agenthooks.AgentID) bool { switch agent { case agenthooks.AgentClaude, agenthooks.AgentCursor, agenthooks.AgentGemini, agenthooks.AgentCodex: return false + default: + return true } - return true } // secretsApply reports whether the secret-detection guardrail runs for this agent. Claude, Cursor, Gemini diff --git a/internal/commands/agenthooks/cx/hooks_test.go b/internal/commands/agenthooks/cx/hooks_test.go index 2dcc3e95c..95f5a2b7a 100644 --- a/internal/commands/agenthooks/cx/hooks_test.go +++ b/internal/commands/agenthooks/cx/hooks_test.go @@ -642,7 +642,7 @@ func TestLogRemediationTelemetry(t *testing.T) { t.Fatalf("got %d calls, want 1", len(tel.calls)) } got := tel.calls[0] - if got.AIProvider != "Cursor" || got.Agent != "Cursor-cli" { + if got.AIProvider != "Cursor" || got.Agent != "Cursor-CLI" { t.Errorf("AIProvider/Agent = %q/%q", got.AIProvider, got.Agent) } if got.Engine != "Asca" || got.ScanType != "asca" { @@ -653,7 +653,7 @@ func TestLogRemediationTelemetry(t *testing.T) { } assert.Equal(t, 2, got.TotalCount) assert.Equal(t, ruleID, (*got.EventAttributes)["vulnerabilityId"]) - if got.StatusResult != "Remediation instructions delivered." { + if got.StatusResult != "Remediation completed successfully." { t.Errorf("StatusResult = %q", got.StatusResult) } if got.ProblemSeverity != "Critical" || got.AiAgentSessionId != "sess-9" { @@ -983,7 +983,8 @@ func TestLogRemediationTelemetry_MissingGuidance(t *testing.T) { t.Fatalf("got %d events, want 1", len(tel.calls)) } event := tel.calls[0] - if event.Status != "failure" || event.TotalCount != 0 || + if event.Status != "Failure" || event.TotalCount != 0 || + event.StatusResult != "Remediation failed. Reason: remediation_instructions_missing, Error Code: None" || (*event.EventAttributes)["reasonCode"] != "remediation_instructions_missing" { t.Fatalf("unexpected remediation failure: %+v", event) } diff --git a/internal/commands/agenthooks/guardrails/asca/asca.go b/internal/commands/agenthooks/guardrails/asca/asca.go index a56511c98..505535106 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca.go +++ b/internal/commands/agenthooks/guardrails/asca/asca.go @@ -9,7 +9,6 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/services" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" @@ -44,7 +43,7 @@ var BelowThreshold func(severity string) bool // `cx ignore-vulnerability` (the realtime ignore file) are filtered out before the // verdict. Fail-open on infrastructure errors (ASCA install fail, engine unavailable, panic). func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.TelemetryWrapper, agent string) (blocked bool, reason, context, severity string) { - findingCount := 0 + scanned := false var severities []string defer func() { @@ -53,7 +52,9 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme reason = "" context = "" } - logASCATelemetry(telemetryWrapper, agent, ev.SessionID, ev.WorkDir, findingCount, severities) + if scanned { + hooktelemetry.LogScan(telemetryWrapper, agent, "Asca", ev.SessionID, ev.WorkDir, severities) + } }() if !isSupportedByASCA(ev.FilePath) { @@ -98,6 +99,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme return false, "", "", "" } if len(newResult.ScanDetails) == 0 { + scanned = true return false, "", "", "" } @@ -113,7 +115,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme } // Telemetry reports what was DETECTED; the threshold only decides what is denied. detected := newFindings - findingCount = len(detected) + scanned = true for i := range detected { severities = append(severities, detected[i].Severity) } @@ -200,31 +202,3 @@ func shouldUpdateVersion() bool { v := viper.GetString(params.DisableASCALatestVersionKey) return v != "true" } - -// logASCATelemetry sends a telemetry event for ASCA scan results. -// Called once after ASCA scan is performed with the actual finding count. -func logASCATelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID, workDir string, totalCount int, severities []string) { - if telemetryWrapper == nil || totalCount == 0 { - return - } - - severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) - telemetryData := &wrappers.DataForAITelemetry{ - Agent: hostenv.TelemetryAgent(agent), - AIProvider: agent, - Engine: "Asca", - TotalCount: totalCount, - UniqueID: wrappers.GetUniqueID(), - Type: "hooks-detect", - SubType: "scan", - ScanType: "asca", - ProblemSeverity: severity, - StatusResult: statusResult, - AiAgentSessionId: sessionID, - } - hooktelemetry.Enrich(telemetryData, workDir) - - if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { - // fail-open - } -} diff --git a/internal/commands/agenthooks/guardrails/asca/asca_test.go b/internal/commands/agenthooks/guardrails/asca/asca_test.go index 932f56952..6cb75184b 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca_test.go +++ b/internal/commands/agenthooks/guardrails/asca/asca_test.go @@ -12,9 +12,7 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" - "github.com/checkmarx/ast-cli/internal/wrappers" "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" - "github.com/checkmarx/ast-cli/internal/wrappers/mock" "github.com/spf13/viper" "github.com/stretchr/testify/assert" ) @@ -353,7 +351,7 @@ func TestAdditionalContext_EmitsProvenanceOptionalFlags(t *testing.T) { {FileName: "billing.py", Line: 5, RuleID: 4059}, } ctx := additionalContext("billing.py", "cx", findings, "", "Claude", "sess-123") - want := ` --optional-flags "aiProvider=Claude;agent=Claude-cli;aiAgentSessionId=sess-123"` + want := ` --optional-flags "aiProvider=Claude;agent=Claude-CLI;aiAgentSessionId=sess-123"` if !strings.Contains(ctx, want) { t.Errorf("expected provenance flags %q in ignore command, got %q", want, ctx) } @@ -564,43 +562,6 @@ func TestShouldUpdateVersion_DisabledReturnsFalse(t *testing.T) { assert.False(t, shouldUpdateVersion()) } -// ── logASCATelemetry ───────────────────────────────────────────────────────── - -func TestLogASCATelemetry_NilWrapper_NoOp(t *testing.T) { - assert.NotPanics(t, func() { - logASCATelemetry(nil, "Claude", "", "", 3, nil) - }) -} - -func TestLogASCATelemetry_ZeroCount_DoesNotSend(t *testing.T) { - sent := false - telemetry := mock.TelemetryMockWrapper{ - CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - sent = true - return nil - }, - } - logASCATelemetry(telemetry, "Claude", "", "", 0, nil) - assert.False(t, sent) -} - -func TestLogASCATelemetry_WithFindings_Sends(t *testing.T) { - var captured *wrappers.DataForAITelemetry - telemetry := mock.TelemetryMockWrapper{ - CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - captured = data - return nil - }, - } - logASCATelemetry(telemetry, "Claude", "", "", 2, []string{"HIGH", "Low"}) - assert.NotNil(t, captured) - assert.Equal(t, "Asca", captured.Engine) - assert.Equal(t, 2, captured.TotalCount) - assert.Equal(t, "High", captured.ProblemSeverity) - assert.Equal(t, "Critical=0,High=1,Medium=0,Low=1,Info=0", captured.StatusResult) - assert.Equal(t, "Claude", captured.AIProvider) -} - // ── findingsSummary / formatFindings ───────────────────────────────────────── func TestFindingsSummary_IncludesRemediation(t *testing.T) { diff --git a/internal/commands/agenthooks/guardrails/kics/kics.go b/internal/commands/agenthooks/guardrails/kics/kics.go index b60999642..6ecd8f3af 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics.go +++ b/internal/commands/agenthooks/guardrails/kics/kics.go @@ -8,7 +8,6 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" @@ -55,7 +54,7 @@ var BelowThreshold func(severity string) bool // verdict. Fail-open on infrastructure errors (Docker unavailable, image pull fail, panic), // returning a skippedNote so the skipped check is visible. func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper wrappers.TelemetryWrapper, agent string) (blocked bool, reason, context, note, severity string) { - findingCount := 0 + scanned := false var severities []string defer func() { @@ -67,7 +66,9 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w note = skippedNote(ev.FilePath, fmt.Errorf("internal error: %v", r)) severity = "" } - logKicsTelemetry(telemetryWrapper, agent, ev.SessionID, ev.WorkDir, findingCount, severities) + if scanned { + hooktelemetry.LogScan(telemetryWrapper, agent, "IaC", ev.SessionID, ev.WorkDir, severities) + } }() if !isSupportedByKICS(ev.FilePath) { @@ -99,13 +100,14 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w return false, "", "", skippedNote(ev.FilePath, err), "" } if len(newResults) == 0 { + scanned = true return false, "", "", "", "" } // For new files (no original content), every finding is new if originalContent == "" { detected := newResults - findingCount = len(detected) + scanned = true severities = resultSeverities(detected) newResults = aboveThreshold(newResults) if len(newResults) == 0 { @@ -134,7 +136,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w // Telemetry reports what was DETECTED; the threshold only decides what is denied. detected := NewFindings(origResults, newResults) - findingCount = len(detected) + scanned = true severities = resultSeverities(detected) newFindings := aboveThreshold(detected) if len(newFindings) == 0 { @@ -194,35 +196,6 @@ func highestSeverity(findings []iacrealtime.IacRealtimeResult) string { return best } -// logKicsTelemetry sends a telemetry event for KICS scan results. -// Called once after KICS scan is performed with the actual finding count. -func logKicsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID, workDir string, totalCount int, severities []string) { - if telemetryWrapper == nil || totalCount == 0 { - return - } - - severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) - telemetryData := &wrappers.DataForAITelemetry{ - Agent: hostenv.TelemetryAgent(agent), - AIProvider: agent, - Engine: "IaC", - TotalCount: totalCount, - UniqueID: wrappers.GetUniqueID(), - Type: "hooks-detect", - SubType: "scan", - ScanType: "iac", - ProblemSeverity: severity, - StatusResult: statusResult, - AiAgentSessionId: sessionID, - } - hooktelemetry.Enrich(telemetryData, workDir) - - if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { - // fail-open: telemetry is best-effort and must never block the guardrail - logger.PrintfIfVerbose("kics guardrail: failed to send telemetry: %v", err) - } -} - // skippedNote is what the user sees when the guardrail fails open. Without it a // file edited with no container engine running is indistinguishable from a file // that scanned clean — the edit is allowed either way, and nothing says why. diff --git a/internal/commands/agenthooks/guardrails/kics/kics_test.go b/internal/commands/agenthooks/guardrails/kics/kics_test.go index 4b6bcc848..f4c767d4b 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics_test.go +++ b/internal/commands/agenthooks/guardrails/kics/kics_test.go @@ -13,8 +13,6 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/checkmarx/ast-cli/internal/services/realtimeengine" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/mock" "github.com/stretchr/testify/assert" ) @@ -233,43 +231,4 @@ func TestScanFileEdit_EngineDownProducesNote(t *testing.T) { assert.False(t, res.blocked, "must fail open, not block the edit") assert.Contains(t, res.note, "main.tf") assert.Contains(t, res.note, "not running") -} - -// ── logKicsTelemetry ───────────────────────────────────────────────────────── - -func TestLogKicsTelemetry_NilWrapper_NoOp(t *testing.T) { - assert.NotPanics(t, func() { - logKicsTelemetry(nil, "Claude", "", "", 3, nil) - }) -} - -func TestLogKicsTelemetry_ZeroCount_DoesNotSend(t *testing.T) { - sent := false - telemetry := mock.TelemetryMockWrapper{ - CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - sent = true - return nil - }, - } - logKicsTelemetry(telemetry, "Claude", "", "", 0, nil) - assert.False(t, sent) -} - -func TestLogKicsTelemetry_WithFindings_Sends(t *testing.T) { - var captured *wrappers.DataForAITelemetry - telemetry := mock.TelemetryMockWrapper{ - CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - captured = data - return nil - }, - } - logKicsTelemetry(telemetry, "Claude", "sess-1", "", 2, nil) - assert.NotNil(t, captured) - assert.Equal(t, "IaC", captured.Engine) - assert.Equal(t, 2, captured.TotalCount) - assert.Equal(t, "Claude", captured.AIProvider) - assert.Equal(t, "hooks-detect", captured.Type) - assert.Equal(t, "scan", captured.SubType) - assert.Equal(t, "iac", captured.ScanType) - assert.Equal(t, "sess-1", captured.AiAgentSessionId) -} +} \ No newline at end of file diff --git a/internal/commands/agenthooks/guardrails/secrets/secrets.go b/internal/commands/agenthooks/guardrails/secrets/secrets.go index 09152f8b8..75e64c4b1 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets.go @@ -5,7 +5,6 @@ import ( agenthooks "github.com/Checkmarx/ast-cx-hooks" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" @@ -36,7 +35,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w return false, "", "", "" } - findingCount := 0 + scanned := false var severities []string defer func() { if r := recover(); r != nil { @@ -46,7 +45,9 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w context = "" severity = "" } - logSecretsTelemetry(telemetryWrapper, agent, ev.SessionID, ev.WorkDir, findingCount, severities) + if scanned { + hooktelemetry.LogScan(telemetryWrapper, agent, "Secrets", ev.SessionID, ev.WorkDir, severities) + } }() newContent, originalContent, ok := proposedContent(ev.FilePath, ev.Changes) @@ -65,6 +66,7 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w return false, "", "", "" } if len(newResults) == 0 { + scanned = true return false, "", "", "" } @@ -78,13 +80,14 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w } findings = NewFindings(origResults, newResults) if len(findings) == 0 { + scanned = true return false, "", "", "" } } // Telemetry reports what was DETECTED; the threshold only decides what is denied. detected := findings - findingCount = len(detected) + scanned = true for i := range detected { severities = append(severities, detected[i].Severity) } @@ -129,32 +132,6 @@ func highestSeverity(findings []secretsrealtime.SecretsRealtimeResult) string { return best } -func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID, workDir string, totalCount int, severities []string) { - if telemetryWrapper == nil || totalCount == 0 { - return - } - - severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) - telemetryData := &wrappers.DataForAITelemetry{ - Agent: hostenv.TelemetryAgent(agent), - AIProvider: agent, - Engine: "Secrets", - TotalCount: totalCount, - UniqueID: wrappers.GetUniqueID(), - Type: "hooks-detect", - SubType: "scan", - ScanType: "secrets", - ProblemSeverity: severity, - StatusResult: statusResult, - AiAgentSessionId: sessionID, - } - hooktelemetry.Enrich(telemetryData, workDir) - - if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { - logger.PrintfIfVerbose("secrets guardrail: failed to send telemetry: %v", err) - } -} - // existingIgnoreFilePath returns the realtime ignore-file path anchored at workDir only // when it exists on disk. A missing file means the user has not suppressed anything yet. func existingIgnoreFilePath(workDir string) string { diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go index 20d98d304..2c9b7fe39 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -8,8 +8,10 @@ import ( "context" "errors" "fmt" + "io" "net" "os" + "path/filepath" "regexp" "strings" "sync" @@ -27,16 +29,29 @@ import ( const ( // StatusSuccess is the status sent for an event whose operation completed. - StatusSuccess = "success" + StatusSuccess = "Success" // StatusFailure is the status of an operation that could not complete. - StatusFailure = "failure" + StatusFailure = "Failure" // EngineOSS identifies dependency scan, remediation, and ignore events. EngineOSS = "oss" // RemediationModeSelfHealing marks a remediation driven by a hook deny (the agent fixes its own edit). RemediationModeSelfHealing = "SelfHealing" + // RemediationSucceeded is the design's statusResult for a successful remediation event. + RemediationSucceeded = "Remediation completed successfully." + // ErrorCodeNone is the error code of a failure that has no underlying error. + ErrorCodeNone = "None" + // APIVersionV2 marks scan events whose severity counts are in statusResult. + APIVersionV2 = "v2" + + scanEventType = "hooks-detect" + scanEventSubType = "scan" + errorCodeUnknown = "Unknown" remoteName = "origin" schemeSeparator = "://" + + pluginContextFile = "cx_telemetry_context" + pluginContextMaxBytes = 4096 ) // severityOrder is the order severities appear in a scan event's statusResult. @@ -130,6 +145,57 @@ func Enrich(data *wrappers.DataForAITelemetry, workDir string) { } } +// FailureResult is the design's statusResult for a failed operation: +// " failed. Reason: , Error Code: ". +func FailureResult(operation, reason, code string) string { + return fmt.Sprintf("%s failed. Reason: %s, Error Code: %s", operation, reason, code) +} + +// ErrorCode names the cause of err for a failure statusResult: the gRPC status code when there is +// one, DeadlineExceeded for a timeout, otherwise Unknown. +func ErrorCode(err error) string { + if err == nil { + return ErrorCodeNone + } + var networkError net.Error + if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &networkError) && networkError.Timeout()) { + return codes.DeadlineExceeded.String() + } + if s, ok := status.FromError(err); ok && s.Code() != codes.Unknown { + return s.Code().String() + } + return errorCodeUnknown +} + +func scanAttributes(sessionID string) wrappers.EventAttributes { + attrs := wrappers.EventAttributes{"apiVersion": APIVersionV2} + if sessionID != "" { + attrs["aiAgentSessionId"] = sessionID + } + return attrs +} + +// LogScan reports a completed scan. Every completed scan is reported, a clean one too: the counts per +// severity go in statusResult ("Critical=0, High=0, ...") and the highest detected severity in +// problemSeverity. Fail-open. +func LogScan(telemetry wrappers.TelemetryWrapper, agent, engine, sessionID, workDir string, severities []string) { + if telemetry == nil { + return + } + severity, statusResult := ScanSeveritySummary(severities) + attrs := scanAttributes(sessionID) + data := &wrappers.DataForAITelemetry{ + Type: scanEventType, SubType: scanEventSubType, APIVersion: APIVersionV2, + AIProvider: agent, Agent: hostenv.TelemetryAgent(agent), + Engine: engine, ScanType: strings.ToLower(engine), + TotalCount: len(severities), ProblemSeverity: severity, StatusResult: statusResult, + UniqueID: wrappers.GetUniqueID(), AiAgentSessionId: sessionID, + EventAttributes: &attrs, + } + Enrich(data, workDir) + _ = telemetry.SendAIDataToLog(data) +} + // LogScanFailure reports an attempted scan that did not produce results. V2 scan events can // carry a failure status without a finding count or severity. func LogScanFailure(telemetry wrappers.TelemetryWrapper, agent, engine, sessionID, workDir string, err error) { @@ -142,21 +208,18 @@ func LogScanFailure(telemetry wrappers.TelemetryWrapper, agent, engine, sessionI strings.Contains(err.Error(), errorconstants.ErrMissingAIFeatureLicense) { return } + code := ErrorCode(err) reason := "scanner_error" - var networkError net.Error - if errors.Is(err, context.DeadlineExceeded) || status.Code(err) == codes.DeadlineExceeded || - (errors.As(err, &networkError) && networkError.Timeout()) { + if code == codes.DeadlineExceeded.String() { reason = "scanner_timeout" } - attrs := wrappers.EventAttributes{"reasonCode": reason} - if sessionID != "" { - attrs["aiAgentSessionId"] = sessionID - } + attrs := scanAttributes(sessionID) + attrs["reasonCode"] = reason data := &wrappers.DataForAITelemetry{ - Type: "hooks-detect", SubType: "scan", APIVersion: "v2", + Type: scanEventType, SubType: scanEventSubType, APIVersion: APIVersionV2, AIProvider: agent, Agent: hostenv.TelemetryAgent(agent), Engine: engine, ScanType: strings.ToLower(engine), - Status: StatusFailure, StatusResult: "Scanner did not complete.", + Status: StatusFailure, StatusResult: FailureResult("Scan", reason, code), UniqueID: wrappers.GetUniqueID(), AiAgentSessionId: sessionID, EventAttributes: &attrs, } @@ -184,7 +247,57 @@ func ScanSeveritySummary(severities []string) (highest, statusResult string) { } parts = append(parts, fmt.Sprintf("%s=%d", s, count)) } - return highest, strings.Join(parts, ",") + return highest, strings.Join(parts, ", ") +} + +// pluginStateDirs maps a telemetry agent label to the Dev Assist plugin's state directory under +// ~/.checkmarx/agent-logs, where the plugin keeps its cx_telemetry_context file. +var pluginStateDirs = map[string]string{ + "claude-cli": "claude", + "copilot-cli": "copilot-cli", + "copilot-vscode": "copilot-cli", + "cursor-cli": "cursor", + "codex-cli": "codex", + "gemini-cli": "gemini-cli", +} + +var pluginContextKeys = map[string]string{ + "CX_AGENT_VERSION": "agentVersion", + "CX_PLUGIN_VERSION": "cxPluginVersion", + "CX_PLUGIN_TYPE": "pluginType", +} + +// PluginContext reads the agent version, plugin version and plugin type that the Dev Assist plugin +// for agent (a telemetry agent label such as Claude-CLI) last recorded. Commands the agent runs from +// its own shell do not get them through the environment. Keys are agentVersion, cxPluginVersion and +// pluginType; an unknown agent, a missing file, or an unsafe value yields no entry. +func PluginContext(agent string) map[string]string { + values := map[string]string{} + leaf, ok := pluginStateDirs[strings.ToLower(strings.TrimSpace(agent))] + if !ok { + return values + } + home, err := os.UserHomeDir() + if err != nil { + return values + } + f, err := os.Open(filepath.Join(home, ".checkmarx", "agent-logs", leaf, pluginContextFile)) + if err != nil { + return values + } + defer f.Close() + raw, err := io.ReadAll(io.LimitReader(f, pluginContextMaxBytes+1)) + if err != nil || len(raw) > pluginContextMaxBytes { + return values + } + for _, line := range strings.Split(string(raw), "\n") { + key, value, found := strings.Cut(strings.TrimSpace(line), "=") + field, known := pluginContextKeys[key] + if found && known && ignoreFlagValue.MatchString(value) { + values[field] = value + } + } + return values } // RepoURL returns the credential-free "origin" URL of the git repository containing workDir, or "" when diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go index 6739f7fee..130bbd518 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -6,6 +6,7 @@ import ( "context" "errors" "os" + "path/filepath" "strings" "testing" @@ -51,11 +52,74 @@ func TestSanitizeRepoURL(t *testing.T) { func TestScanSeveritySummary(t *testing.T) { highest, counts := ScanSeveritySummary([]string{"High", "critical", "High", "Low", "unknown"}) assert.Equal(t, highest, "Critical") - assert.Equal(t, counts, "Critical=1,High=2,Medium=0,Low=1,Info=0") + assert.Equal(t, counts, "Critical=1, High=2, Medium=0, Low=1, Info=0") highest, counts = ScanSeveritySummary(nil) assert.Equal(t, highest, "") - assert.Equal(t, counts, "Critical=0,High=0,Medium=0,Low=0,Info=0") + assert.Equal(t, counts, "Critical=0, High=0, Medium=0, Low=0, Info=0") +} + +func TestFailureResult(t *testing.T) { + assert.Equal(t, FailureResult("Scan", "scanner_error", "Unavailable"), "Scan failed. Reason: scanner_error, Error Code: Unavailable") +} + +func TestErrorCode(t *testing.T) { + assert.Equal(t, ErrorCode(nil), ErrorCodeNone) + assert.Equal(t, ErrorCode(context.DeadlineExceeded), "DeadlineExceeded") + assert.Equal(t, ErrorCode(errors.New("boom")), "Unknown") +} + +func TestLogScan(t *testing.T) { + t.Setenv("CX_COPILOT_HOST", "") + var events []*wrappers.DataForAITelemetry + tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + events = append(events, data) + return nil + }} + LogScan(nil, "Claude", "Asca", "sess-1", "", []string{"High"}) // must not panic + LogScan(tel, "Claude", "Asca", "sess-1", "", []string{"HIGH", "Low"}) + LogScan(tel, "Cursor", "IaC", "", "", nil) + assert.Equal(t, len(events), 2) + + withFindings := events[0] + assert.Equal(t, withFindings.Type, "hooks-detect") + assert.Equal(t, withFindings.SubType, "scan") + assert.Equal(t, withFindings.APIVersion, APIVersionV2) + assert.Equal(t, withFindings.Engine, "Asca") + assert.Equal(t, withFindings.ScanType, "asca") + assert.Equal(t, withFindings.Agent, "Claude-CLI") + assert.Equal(t, withFindings.AIProvider, "Claude") + assert.Equal(t, withFindings.TotalCount, 2) + assert.Equal(t, withFindings.ProblemSeverity, "High") + assert.Equal(t, withFindings.StatusResult, "Critical=0, High=1, Medium=0, Low=1, Info=0") + assert.Equal(t, withFindings.Status, StatusSuccess) + assert.Equal(t, withFindings.AiAgentSessionId, "sess-1") + assert.Equal(t, (*withFindings.EventAttributes)["aiAgentSessionId"], "sess-1") + + clean := events[1] + assert.Equal(t, clean.TotalCount, 0) + assert.Equal(t, clean.ProblemSeverity, "") + assert.Equal(t, clean.StatusResult, "Critical=0, High=0, Medium=0, Low=0, Info=0") + _, hasSession := (*clean.EventAttributes)["aiAgentSessionId"] + assert.Assert(t, !hasSession) +} + +func TestPluginContext(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + dir := filepath.Join(home, ".checkmarx", "agent-logs", "cursor") + assert.NilError(t, os.MkdirAll(dir, 0o755)) + content := "CX_AGENT_VERSION=2026.11.3\nCX_PLUGIN_VERSION=1.0.4\nCX_PLUGIN_TYPE=CLI\nCX_OTHER=x\nCX_PLUGIN_TYPE_BAD=a b\n" + assert.NilError(t, os.WriteFile(filepath.Join(dir, pluginContextFile), []byte(content), 0o600)) + + got := PluginContext("Cursor-CLI") + assert.DeepEqual(t, got, map[string]string{"agentVersion": "2026.11.3", "cxPluginVersion": "1.0.4", "pluginType": "CLI"}) + assert.Equal(t, len(PluginContext("Claude-CLI")), 0, "no context file for this agent") + assert.Equal(t, len(PluginContext("Unknown")), 0) + + assert.NilError(t, os.WriteFile(filepath.Join(dir, pluginContextFile), []byte("CX_AGENT_VERSION=1;rm\n"), 0o600)) + assert.Equal(t, len(PluginContext("Cursor-CLI")), 0, "values outside the allowed character set are dropped") } func TestEnrich(t *testing.T) { @@ -123,11 +187,12 @@ func TestIgnoreFlags(t *testing.T) { t.Setenv(params.AgentVersionEnv, "1;pluginType=unexpected") t.Setenv(params.CxPluginVersionEnv, "") - assert.Equal(t, IgnoreFlags("Cursor", "invalid session"), " --optional-flags \"aiProvider=Cursor;agent=Cursor-cli;pluginType=CLI\"") + assert.Equal(t, IgnoreFlags("Cursor", "invalid session"), " --optional-flags \"aiProvider=Cursor;agent=Cursor-CLI;pluginType=CLI\"") assert.Equal(t, IgnoreFlags("", ""), "") } func TestLogScanFailure(t *testing.T) { + t.Setenv("CX_COPILOT_HOST", "") var events []*wrappers.DataForAITelemetry tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { events = append(events, data) @@ -142,6 +207,7 @@ func TestLogScanFailure(t *testing.T) { assert.Equal(t, event.APIVersion, "v2") assert.Equal(t, event.TotalCount, 0) assert.Equal(t, event.ProblemSeverity, "") - assert.Equal(t, event.Agent, "Copilot-cli") + assert.Equal(t, event.Agent, "Copilot-CLI") + assert.Equal(t, event.StatusResult, "Scan failed. Reason: scanner_timeout, Error Code: DeadlineExceeded") assert.Equal(t, (*event.EventAttributes)["reasonCode"], "scanner_timeout") } diff --git a/internal/commands/agenthooks/hostenv/hostenv.go b/internal/commands/agenthooks/hostenv/hostenv.go index c00641bca..c6e8e7ed7 100644 --- a/internal/commands/agenthooks/hostenv/hostenv.go +++ b/internal/commands/agenthooks/hostenv/hostenv.go @@ -28,9 +28,12 @@ const VSCodeIntegrationID = "vscode-chat" // plugin from ~/.copilot/installed-plugins/, the terminal's folder, so PLUGIN_ROOT alone cannot tell. const pluginHostEnv = "CX_COPILOT_HOST" -// agentVSCode is the telemetry agent label for GitHub Copilot inside VS Code. The terminal keeps "-cli". +// agentVSCode is the telemetry agent label for GitHub Copilot inside VS Code. The terminal keeps "-CLI". const agentVSCode = "Copilot-VSCode" +// cliAgentSuffix follows the analytics design's agent names (Claude-CLI, Copilot-CLI, Gemini-CLI, ...). +const cliAgentSuffix = "-CLI" + // PluginHost reports where this hook runs, from the PLUGIN_ROOT the host injected into the hook's // environment (cx inherits it from the plugin's hook script). VS Code always runs its own copy of the // plugin under /agentPlugins/ (Windows %APPDATA%\Code\agentPlugins, macOS @@ -73,10 +76,10 @@ func InVSCode() bool { } // TelemetryAgent is the telemetry `agent` value for an event from the given agent name: GitHub Copilot -// inside VS Code is "Copilot-VSCode"; everything else keeps "-cli". +// inside VS Code is "Copilot-VSCode"; everything else is "-CLI". func TelemetryAgent(agent string) string { if agent != copilotAgent || !InVSCode() { - return agent + "-cli" + return agent + cliAgentSuffix } return agentVSCode } diff --git a/internal/commands/agenthooks/hostenv/hostenv_test.go b/internal/commands/agenthooks/hostenv/hostenv_test.go index df4fa597e..7e53713cb 100644 --- a/internal/commands/agenthooks/hostenv/hostenv_test.go +++ b/internal/commands/agenthooks/hostenv/hostenv_test.go @@ -79,13 +79,13 @@ func TestTelemetryAgent(t *testing.T) { cases := []struct { name, agent, root, want string }{ - {"terminal Copilot", "Copilot", rootCLI, "Copilot-cli"}, + {"terminal Copilot", "Copilot", rootCLI, "Copilot-CLI"}, {"VS Code copy of a Copilot CLI install", "Copilot", rootVSCodeFromCLIInstall, "Copilot-VSCode"}, {"VS Code marketplace install", "Copilot", rootVSCodeFromMarketplace, "Copilot-VSCode"}, - {"VS Code fork stays -cli", "Copilot", `C:\Users\u\AppData\Roaming\Windsurf\agentPlugins\x\1a`, "Copilot-cli"}, - {"no host signal stays -cli", "Copilot", "", "Copilot-cli"}, - {"other agents unchanged in VS Code", "Claude", rootVSCodeFromCLIInstall, "Claude-cli"}, - {"other agents unchanged", "Cursor", "", "Cursor-cli"}, + {"VS Code fork stays -CLI", "Copilot", `C:\Users\u\AppData\Roaming\Windsurf\agentPlugins\x\1a`, "Copilot-CLI"}, + {"no host signal stays -CLI", "Copilot", "", "Copilot-CLI"}, + {"other agents unchanged in VS Code", "Claude", rootVSCodeFromCLIInstall, "Claude-CLI"}, + {"other agents unchanged", "Cursor", "", "Cursor-CLI"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/commands/agenthooks/sca/sca.go b/internal/commands/agenthooks/sca/sca.go index d05206de8..6cb218b80 100644 --- a/internal/commands/agenthooks/sca/sca.go +++ b/internal/commands/agenthooks/sca/sca.go @@ -4,9 +4,7 @@ import ( "os" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime" - "github.com/checkmarx/ast-cli/internal/wrappers" ) // BelowThreshold is set by the hook dispatcher and reports whether a finding's severity is under the @@ -23,12 +21,14 @@ var BelowThreshold func(severity string) bool func (s *Scanner) CheckBashInstall(command, workDir, agent, sessionID string) (finding, remediation, severity string) { s.workDir = workDir for _, req := range ParseInstall(command) { - mal, vuln, err := s.scanRequest(req, workDir) + mal, vuln, scanned, err := s.scanRequest(req, workDir) if err != nil { hooktelemetry.LogScanFailure(s.Telemetry, agent, hooktelemetry.EngineOSS, sessionID, workDir, err) continue } - s.logScan(agent, sessionID, workDir, mal, vuln) + if scanned { + s.logScan(agent, sessionID, workDir, mal, vuln) + } if f, r, sev := denyFrom(mal, vuln, workDir, agent, sessionID); f != "" { return f, r, sev } @@ -36,18 +36,21 @@ func (s *Scanner) CheckBashInstall(command, workDir, agent, sessionID string) (f return "", "", "" } -func (s *Scanner) scanRequest(req InstallRequest, workDir string) (malicious, vulnerable []ossrealtime.OssPackage, err error) { +// scanRequest scans one install request. scanned is false when there was nothing to scan. +func (s *Scanner) scanRequest(req InstallRequest, workDir string) (malicious, vulnerable []ossrealtime.OssPackage, scanned bool, err error) { if req.ManifestRef != "" { path := resolveRef(req.ManifestRef, workDir) if _, statErr := os.Stat(path); statErr != nil { - return nil, nil, nil + return nil, nil, false, nil } - return s.ScanFile(path) + malicious, vulnerable, err = s.ScanFile(path) + return malicious, vulnerable, true, err } if len(req.Packages) == 0 { - return nil, nil, nil + return nil, nil, false, nil } - return s.ScanPackages(req.Manager.Format(), req.Packages) + malicious, vulnerable, err = s.ScanPackages(req.Manager.Format(), req.Packages) + return malicious, vulnerable, true, err } // CheckManifestEdit is the entry point for the pre-file-edit guardrail. It @@ -96,13 +99,10 @@ func denyFrom(malicious, vulnerable []ossrealtime.OssPackage, workDir, agent, se return "", "", "" } -// logScan sends the SCA scan (hooks-detect) event: every detected CVE counted by severity, plus one -// Critical per malicious package. Like the other engines it reports what was DETECTED (the severity -// threshold only decides the deny) and sends nothing for a clean scan. Fail-open. +// logScan sends the SCA scan (hooks-detect) event for a completed scan: every detected CVE counted by +// severity, plus one Critical per malicious package. Like the other engines it reports what was +// DETECTED (the severity threshold only decides the deny), a clean scan included. Fail-open. func (s *Scanner) logScan(agent, sessionID, workDir string, malicious, vulnerable []ossrealtime.OssPackage) { - if s.Telemetry == nil { - return - } severities := make([]string, 0, len(malicious)) for range malicious { severities = append(severities, "Critical") @@ -112,25 +112,7 @@ func (s *Scanner) logScan(agent, sessionID, workDir string, malicious, vulnerabl severities = append(severities, v.Severity) } } - if len(severities) == 0 { - return - } - severity, statusResult := hooktelemetry.ScanSeveritySummary(severities) - data := &wrappers.DataForAITelemetry{ - Agent: hostenv.TelemetryAgent(agent), - AIProvider: agent, - Engine: hooktelemetry.EngineOSS, - TotalCount: len(severities), - UniqueID: wrappers.GetUniqueID(), - Type: "hooks-detect", - SubType: "scan", - ScanType: hooktelemetry.EngineOSS, - ProblemSeverity: severity, - StatusResult: statusResult, - AiAgentSessionId: sessionID, - } - hooktelemetry.Enrich(data, workDir) - _ = s.Telemetry.SendAIDataToLog(data) + hooktelemetry.LogScan(s.Telemetry, agent, hooktelemetry.EngineOSS, sessionID, workDir, severities) } // maliciousPackageIDs identifies denied malicious packages as name@version (they have no CVE), diff --git a/internal/commands/agenthooks/sca/sca_test.go b/internal/commands/agenthooks/sca/sca_test.go index 1a3af2220..d95017e61 100644 --- a/internal/commands/agenthooks/sca/sca_test.go +++ b/internal/commands/agenthooks/sca/sca_test.go @@ -256,7 +256,7 @@ func TestDenyVulnerable_EmitsProvenanceOptionalFlags(t *testing.T) { {PackageManager: "npm", PackageName: "axios", PackageVersion: "0.21.0"}, } _, remediation := DenyVulnerable(pkgs, "", "Cursor", "sess-9") - want := ` --optional-flags "aiProvider=Cursor;agent=Cursor-cli;aiAgentSessionId=sess-9"` + want := ` --optional-flags "aiProvider=Cursor;agent=Cursor-CLI;aiAgentSessionId=sess-9"` if !strings.Contains(remediation, want) { t.Errorf("expected provenance flags %q in ignore command, got %q", want, remediation) } diff --git a/internal/commands/agenthooks/sca/telemetry_ids_test.go b/internal/commands/agenthooks/sca/telemetry_ids_test.go index 7e99736b7..13d389f4a 100644 --- a/internal/commands/agenthooks/sca/telemetry_ids_test.go +++ b/internal/commands/agenthooks/sca/telemetry_ids_test.go @@ -46,25 +46,28 @@ func TestLogScan_SendsDetectedCounts(t *testing.T) { }}} s.logScan("Claude", "sess", t.TempDir(), nil, nil) - if len(sent) != 0 { - t.Fatal("a clean scan sends nothing") + if len(sent) != 1 { + t.Fatalf("a clean scan must send one event, got %d", len(sent)) + } + if clean := sent[0]; clean.TotalCount != 0 || clean.ProblemSeverity != "" || clean.APIVersion != hooktelemetry.APIVersionV2 { + t.Fatalf("unexpected clean scan event: %+v", clean) } mal := []ossrealtime.OssPackage{{PackageName: "evil", Status: statusMalicious}} vuln := []ossrealtime.OssPackage{{PackageName: "lodash", Vulnerabilities: []ossrealtime.Vulnerability{ {CVE: "CVE-1", Severity: "High"}, {CVE: "CVE-2", Severity: "Low"}}}} s.logScan("Claude", "sess", t.TempDir(), mal, vuln) - if len(sent) != 1 { - t.Fatalf("expected one scan event, got %d", len(sent)) + if len(sent) != 2 { + t.Fatalf("expected two scan events, got %d", len(sent)) } - d := sent[0] - if d.Type != "hooks-detect" || d.Engine != "oss" || d.ScanType != "oss" || d.Agent != "Claude-cli" || d.TotalCount != 3 { + d := sent[1] + if d.Type != "hooks-detect" || d.Engine != "oss" || d.ScanType != "oss" || d.Agent != "Claude-CLI" || d.TotalCount != 3 { t.Fatalf("unexpected event: %+v", d) } if d.ProblemSeverity != "Critical" { t.Fatalf("unexpected problemSeverity %q", d.ProblemSeverity) } - if d.StatusResult != "Critical=1,High=1,Medium=0,Low=1,Info=0" { + if d.StatusResult != "Critical=1, High=1, Medium=0, Low=1, Info=0" { t.Fatalf("unexpected statusResult %q", d.StatusResult) } diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index 613a03793..6f8e65200 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -73,10 +73,17 @@ func newAuthLoginCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Comm func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper) (resultErr error) { method, failureReason := "OAuth", "browser_authentication_failed" defer func() { - if resultErr != nil { - if agent := loginTelemetryAgent(cmd); agent != "" { - logger.PrintfIfVerbose("Login failure: agent=%s authMethod=%s reasonCode=%s", agent, method, failureReason) - } + if resultErr == nil { + return + } + agent := loginTelemetryAgent(cmd) + if agent == "" { + return + } + logger.PrintfIfVerbose("Login failure: agent=%s authMethod=%s reasonCode=%s", agent, method, failureReason) + // completeAuthLogin already reported the credential-save failure. + if failureReason != loginCredentialSaveFailed { + sendLoginFailureTelemetry(cmd, telemetryWrapper, agent, method, failureReason, resultErr) } }() if cmd.Flags().Changed(params.AstAPIKeyFlag) { @@ -133,15 +140,15 @@ func loginTelemetryAgent(cmd *cobra.Command) string { agent, _ := cmd.Flags().GetString(params.AgentFlag) switch strings.ToLower(strings.TrimSpace(agent)) { case "copilot-cli": - return "Copilot-cli" + return "Copilot-CLI" case "claude-cli": - return "Claude-cli" + return "Claude-CLI" case "cursor-cli": - return "Cursor-cli" + return "Cursor-CLI" case "gemini-cli": - return "Gemini-cli" + return "Gemini-CLI" case "codex-cli": - return "Codex-cli" + return "Codex-CLI" default: return "" } @@ -151,16 +158,47 @@ const loginCredentialSaveFailed = "credential_save_failed" func completeAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, credential, accessToken, authMethod string) error { err := persistLogin(cmd, credential) - sendLoginTelemetry(cmd, telemetryWrapper, accessToken, authMethod, err != nil) + sendLoginTelemetry(cmd, telemetryWrapper, accessToken, authMethod, err) return err } -func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, accessToken, authMethod string, saveFailed bool) { +func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, accessToken, authMethod string, saveErr error) { agent := loginTelemetryAgent(cmd) if telemetryWrapper == nil || agent == "" || accessToken == "" { return } wrappers.CacheAuthenticatedAccessToken(accessToken) + data, attrs := loginTelemetryData(cmd, agent, authMethod) + if saveErr != nil { + data.Status = hooktelemetry.StatusFailure + data.StatusResult = hooktelemetry.FailureResult("Authentication", loginCredentialSaveFailed, hooktelemetry.ErrorCode(saveErr)) + attrs["reasonCode"] = loginCredentialSaveFailed + } else { + data.SessionID = wrappers.GetSessionID() + } + if err := telemetryWrapper.SendAIDataToLog(data); err != nil { + logger.PrintIfVerbose("Failed to send authentication telemetry: " + err.Error()) + } +} + +// sendLoginFailureTelemetry reports a sign-in that never produced a token. It is best effort: the hook +// telemetry transport only has a token cached from an earlier login, and without one the send fails +// without a network call. +func sendLoginFailureTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, agent, authMethod, reason string, loginErr error) { + if telemetryWrapper == nil { + return + } + data, attrs := loginTelemetryData(cmd, agent, authMethod) + data.Status = hooktelemetry.StatusFailure + data.StatusResult = hooktelemetry.FailureResult("Authentication", reason, hooktelemetry.ErrorCode(loginErr)) + attrs["reasonCode"] = reason + if err := telemetryWrapper.SendAIDataToLog(data); err != nil { + logger.PrintIfVerbose("Failed to send authentication failure telemetry: " + err.Error()) + } +} + +// loginTelemetryData builds the successful authentication event; callers adjust it for failures. +func loginTelemetryData(cmd *cobra.Command, agent, authMethod string) (*wrappers.DataForAITelemetry, wrappers.EventAttributes) { attrs := wrappers.EventAttributes{"authMethod": authMethod} agentSessionID, _ := cmd.Flags().GetString(params.AIAgentSessionIDFlag) agentSessionID = strings.TrimSpace(agentSessionID) @@ -177,30 +215,32 @@ func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryW if pluginVersion == "" { pluginVersion = strings.TrimSpace(os.Getenv(params.CxPluginVersionEnv)) } + // The developer runs the API-key login in their own terminal, where neither flags nor the + // plugin's environment carry the versions; the plugin records them in its context file. + if agentVersion == "" || pluginVersion == "" { + pluginContext := hooktelemetry.PluginContext(agent) + if agentVersion == "" { + agentVersion = pluginContext["agentVersion"] + } + if pluginVersion == "" { + pluginVersion = pluginContext["cxPluginVersion"] + } + } data := &wrappers.DataForAITelemetry{ Type: authenticationEventType, SubType: authenticationEventType, - Status: telemetrySuccessStatus, + Status: hooktelemetry.StatusSuccess, StatusResult: "Authentication successful.", Agent: agent, AgentVersion: agentVersion, CxPluginVersion: pluginVersion, - AIProvider: strings.TrimSuffix(agent, "-cli"), + AIProvider: strings.TrimSuffix(agent, "-CLI"), AiAgentSessionId: agentSessionID, PluginType: "CLI", UniqueID: wrappers.GetUniqueID(), EventAttributes: &attrs, } - if saveFailed { - data.Status = hooktelemetry.StatusFailure - data.StatusResult = "Authenticated but could not save the credential." - attrs["reasonCode"] = loginCredentialSaveFailed - } else { - data.SessionID = wrappers.GetSessionID() - } - if err := telemetryWrapper.SendAIDataToLog(data); err != nil { - logger.PrintIfVerbose("Failed to send authentication telemetry: " + err.Error()) - } + return data, attrs } // connectionFlagsProvided reports whether any connection detail was passed as a flag. diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index c5e8a7363..4071f641c 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -5,10 +5,12 @@ package commands import ( "bytes" "errors" + "os" "path/filepath" "strings" "testing" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/credentialstore" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/wrappers" @@ -255,11 +257,11 @@ func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { {name: "blank", agent: testLoginAgent(" ")}, {name: "default", agent: testLoginAgent("ASTCLI")}, {name: "other", agent: testLoginAgent("Copilot-VSCode")}, - {name: "copilot", agent: testLoginAgent(" Copilot-CLI "), want: "Copilot-cli"}, - {name: "claude", agent: testLoginAgent("claude-cli"), want: "Claude-cli"}, - {name: "cursor", agent: testLoginAgent("cursor-cli"), want: "Cursor-cli"}, - {name: "gemini", agent: testLoginAgent("gemini-cli"), want: "Gemini-cli"}, - {name: "codex", agent: testLoginAgent("codex-cli"), want: "Codex-cli"}, + {name: "copilot", agent: testLoginAgent(" Copilot-CLI "), want: "Copilot-CLI"}, + {name: "claude", agent: testLoginAgent("claude-cli"), want: "Claude-CLI"}, + {name: "cursor", agent: testLoginAgent("cursor-cli"), want: "Cursor-CLI"}, + {name: "gemini", agent: testLoginAgent("gemini-cli"), want: "Gemini-CLI"}, + {name: "codex", agent: testLoginAgent("codex-cli"), want: "Codex-CLI"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -294,7 +296,8 @@ func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { t.Fatal("telemetry sent before credential was saved") } if data.Agent != tc.want || data.Type != authenticationEventType || - data.SubType != authenticationEventType || data.Status != telemetrySuccessStatus || + data.SubType != authenticationEventType || data.Status != hooktelemetry.StatusSuccess || + data.StatusResult != "Authentication successful." || data.AIProvider+"-CLI" != tc.want || data.SessionID == "" || (*data.EventAttributes)["authMethod"] != "OAuth" { t.Fatalf("unexpected authentication telemetry: %+v", data) } @@ -326,6 +329,42 @@ func testLoginAgent(agent string) *string { return &agent } +func TestLoginTelemetryData_PluginContextFallback(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv(params.AgentVersionEnv, "") + t.Setenv(params.CxPluginVersionEnv, "") + dir := filepath.Join(home, ".checkmarx", "agent-logs", "claude") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + content := "CX_AGENT_VERSION=2.1.4\nCX_PLUGIN_VERSION=1.0.5\nCX_PLUGIN_TYPE=CLI\n" + if err := os.WriteFile(filepath.Join(dir, "cx_telemetry_context"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + + cmd := newAuthLoginCommand(nil) + data, _ := loginTelemetryData(cmd, "Claude-CLI", "APIKey") + if data.AgentVersion != "2.1.4" || data.CxPluginVersion != "1.0.5" { + t.Fatalf("context file should fill missing versions: %+v", data) + } + + if err := cmd.Flags().Set(params.AgentVersionFlag, "9.9.9"); err != nil { + t.Fatal(err) + } + t.Setenv(params.CxPluginVersionEnv, "8.8.8") + data, _ = loginTelemetryData(cmd, "Claude-CLI", "APIKey") + if data.AgentVersion != "9.9.9" || data.CxPluginVersion != "8.8.8" { + t.Fatalf("flags and environment must win over the context file: %+v", data) + } + + data, _ = loginTelemetryData(newAuthLoginCommand(nil), "Codex-CLI", "APIKey") + if data.AgentVersion != "" { + t.Fatalf("another agent's context file must not be used: %+v", data) + } +} + func TestRunAuthLogin_InvalidAPIKeyKeepsCredential(t *testing.T) { withTempConfigDir(t) store := swapCredentialResolver(t) @@ -371,7 +410,8 @@ func TestCompleteAuthLogin_CredentialSaveFailure(t *testing.T) { if err := completeAuthLogin(cmd, telemetry, "test-credential", "test-access-token", "APIKey"); err == nil { t.Fatal("expected credential save to fail") } - if event == nil || event.Status != "failure" || event.SessionID != "" || + if event == nil || event.Status != hooktelemetry.StatusFailure || event.SessionID != "" || + !strings.HasPrefix(event.StatusResult, "Authentication failed. Reason: credential_save_failed, Error Code: ") || (*event.EventAttributes)["reasonCode"] != loginCredentialSaveFailed { t.Fatalf("unexpected login failure: %+v", event) } @@ -379,3 +419,49 @@ func TestCompleteAuthLogin_CredentialSaveFailure(t *testing.T) { t.Fatalf("existing session changed: %q", got) } } + +func TestRunAuthLogin_FailureSendsTelemetry(t *testing.T) { + withTempConfigDir(t) + swapCredentialResolver(t) + cases := []struct{ name, agent string }{{"eligible agent", "claude-cli"}, {"no agent", ""}} + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cmd, _, _ := newBufferedCmd() + cmd.Flags().String(params.AstAPIKeyFlag, "", "") + cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") + if err := cmd.Flags().Set(params.AstAPIKeyFlag, "not-a-token"); err != nil { + t.Fatal(err) + } + if tc.agent != "" { + if err := cmd.Flags().Set(params.AgentFlag, tc.agent); err != nil { + t.Fatal(err) + } + } + var events []*wrappers.DataForAITelemetry + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + events = append(events, data) + return nil + }} + if err := runAuthLogin(cmd, telemetry); err == nil { + t.Fatal("expected API-key verification to fail") + } + if tc.agent == "" { + if len(events) != 0 { + t.Fatalf("login without an agent sent telemetry: %+v", events) + } + return + } + if len(events) != 1 { + t.Fatalf("got %d events, want 1", len(events)) + } + event := events[0] + if event.Type != authenticationEventType || event.Agent != "Claude-CLI" || event.AIProvider != "Claude" || + event.Status != hooktelemetry.StatusFailure || event.SessionID != "" || + !strings.HasPrefix(event.StatusResult, "Authentication failed. Reason: api_key_authentication_failed, Error Code: ") || + (*event.EventAttributes)["reasonCode"] != "api_key_authentication_failed" || + (*event.EventAttributes)["authMethod"] != "APIKey" { + t.Fatalf("unexpected login failure telemetry: %+v", event) + } + }) + } +} diff --git a/internal/commands/ignore_vulnerability.go b/internal/commands/ignore_vulnerability.go index 31d8617a6..153d77269 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -173,6 +173,10 @@ func sendIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType st aiProvider := utils.GetOptionalParam("aiProvider") sessionID := utils.GetOptionalParam("aiAgentSessionId") agent := utils.GetOptionalParam("agent") + // Plugins released before the "-CLI" labels still pass "-cli". + if base, found := strings.CutSuffix(agent, "-cli"); found { + agent = base + "-CLI" + } engine := engineName(scanType) attrs := wrappers.EventAttributes{} @@ -193,14 +197,14 @@ func sendIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType st ScanType: strings.ToLower(engine), UniqueID: wrappers.GetUniqueID(), Type: "hooks-ignore", - SubType: "ignorePackage", + SubType: ignoreSubType(engine), TotalCount: len(entries), AiAgentSessionId: sessionID, } if failureReason != "" { attrs["reasonCode"] = failureReason telemetryData.Status = hooktelemetry.StatusFailure - telemetryData.StatusResult = "Unable to save the requested ignore." + telemetryData.StatusResult = hooktelemetry.FailureResult("Ignore", failureReason, hooktelemetry.ErrorCodeNone) } if len(attrs) > 0 { telemetryData.EventAttributes = &attrs @@ -218,6 +222,17 @@ func sendIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType st if v := utils.GetOptionalParam("pluginType"); v != "" { telemetryData.PluginType = v } + // Last resort: the context file the plugin's hooks keep for this agent. + pluginCtx := hooktelemetry.PluginContext(agent) + if telemetryData.AgentVersion == "" { + telemetryData.AgentVersion = pluginCtx["agentVersion"] + } + if telemetryData.CxPluginVersion == "" { + telemetryData.CxPluginVersion = pluginCtx["cxPluginVersion"] + } + if telemetryData.PluginType == "" { + telemetryData.PluginType = pluginCtx["pluginType"] + } if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { // fail-open @@ -247,6 +262,19 @@ func ignoreEntryID(entry any) string { } } +// ignoreSubType is the hooks-ignore subType for an engine label: packages and images are ignored by +// coordinates, every other engine by finding. +func ignoreSubType(engine string) string { + switch engine { + case hooktelemetry.EngineOSS: + return "ignorePackage" + case "Containers": + return "ignoreImage" + default: + return "ignoreFinding" + } +} + // engineName maps a --scan-type value to its telemetry engine label. func engineName(scanType string) string { switch strings.ToLower(strings.TrimSpace(scanType)) { diff --git a/internal/commands/ignore_vulnerability_telemetry_test.go b/internal/commands/ignore_vulnerability_telemetry_test.go index d6efef3ed..0f1111846 100644 --- a/internal/commands/ignore_vulnerability_telemetry_test.go +++ b/internal/commands/ignore_vulnerability_telemetry_test.go @@ -4,6 +4,7 @@ package commands import ( "io" + "os" "path/filepath" "strings" "testing" @@ -55,8 +56,8 @@ func TestLogIgnoreTelemetry_CarriesIDsAndNeverTheSecret(t *testing.T) { if got := (*sent.EventAttributes)["vulnerabilityId"]; got != "github-pat" { t.Fatalf("vulnerabilityId = %q", got) } - if sent.Status != "success" { - t.Fatalf("status = %q, want success (common fields are filled)", sent.Status) + if sent.Status != "Success" || sent.SubType != "ignoreFinding" { + t.Fatalf("status/subType = %q/%q, want Success/ignoreFinding (common fields are filled)", sent.Status, sent.SubType) } for k, v := range *sent.EventAttributes { if strings.Contains(v, "must-not-leak") { @@ -117,7 +118,7 @@ func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { return nil }} logIgnoreTelemetry(tel, "asca", nil) - if sent == nil || sent.AIProvider != "Codex" || sent.Agent != "Codex-cli" || + if sent == nil || sent.AIProvider != "Codex" || sent.Agent != "Codex-CLI" || sent.SubType != "ignoreFinding" || sent.AiAgentSessionId != agentSessionID || sent.AgentVersion != "1.2.3" || sent.CxPluginVersion != "2.3.4" || sent.PluginType != "CLI" { t.Fatalf("unexpected ignore telemetry: %+v", sent) @@ -130,7 +131,7 @@ func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { func TestIgnoreTelemetry_AttributedInvalidFinding(t *testing.T) { previous := utils.GetOptionalParam("agent") t.Cleanup(func() { _ = utils.SetOptionalParam("agent", previous) }) - if err := utils.SetOptionalParam("agent", "Copilot-cli"); err != nil { + if err := utils.SetOptionalParam("agent", "Copilot-CLI"); err != nil { t.Fatal(err) } var event *wrappers.DataForAITelemetry @@ -145,9 +146,59 @@ func TestIgnoreTelemetry_AttributedInvalidFinding(t *testing.T) { if err := cmd.Execute(); err == nil { t.Fatal("invalid finding should fail the command") } - if event == nil || event.Type != "hooks-ignore" || event.Agent != "Copilot-cli" || - event.Engine != "oss" || event.Status != "failure" || event.TotalCount != 0 || + if event == nil || event.Type != "hooks-ignore" || event.SubType != "ignorePackage" || event.Agent != "Copilot-CLI" || + event.Engine != "oss" || event.Status != "Failure" || event.TotalCount != 0 || + event.StatusResult != "Ignore failed. Reason: invalid_ignore_input, Error Code: None" || (*event.EventAttributes)["reasonCode"] != "invalid_ignore_input" { t.Fatalf("unexpected ignore failure: %+v", event) } } + +func TestIgnoreSubType(t *testing.T) { + for scanType, want := range map[string]string{ + "oss": "ignorePackage", "sca": "ignorePackage", "containers": "ignoreImage", + "asca": "ignoreFinding", "iac": "ignoreFinding", "secrets": "ignoreFinding", + } { + if got := ignoreSubType(engineName(scanType)); got != want { + t.Errorf("ignoreSubType(%q) = %q, want %q", scanType, got, want) + } + } +} + +func TestIgnoreTelemetry_PluginContextFallback(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + t.Setenv("CX_AGENT_VERSION", "") + t.Setenv("CX_PLUGIN_VERSION", "") + t.Setenv("CX_PLUGIN_TYPE", "") + dir := filepath.Join(home, ".checkmarx", "agent-logs", "claude") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + content := "CX_AGENT_VERSION=2.1.4\nCX_PLUGIN_VERSION=1.0.5\nCX_PLUGIN_TYPE=CLI\n" + if err := os.WriteFile(filepath.Join(dir, "cx_telemetry_context"), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + for _, key := range []string{"aiProvider", "agent", "aiAgentSessionId", "agentVersion", "cxPluginVersion", "pluginType"} { + previous := utils.GetOptionalParam(key) + t.Cleanup(func() { _ = utils.SetOptionalParam(key, previous) }) + } + key := params.OptionalFlagsKey + previous := viper.Get(key) + t.Cleanup(func() { viper.Set(key, previous) }) + viper.Set(key, "aiProvider=Claude;agent=Claude-CLI;agentVersion=9.9.9") + if err := extractOptionalFlags(&cobra.Command{}); err != nil { + t.Fatal(err) + } + + var sent *wrappers.DataForAITelemetry + tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + sent = data + return nil + }} + logIgnoreTelemetry(tel, "secrets", nil) + if sent == nil || sent.AgentVersion != "9.9.9" || sent.CxPluginVersion != "1.0.5" || sent.PluginType != "CLI" { + t.Fatalf("flags must win and the context file fill the gaps: %+v", sent) + } +} From 8fc4fc74cbd9491507aa1560aa05de83203cca71 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:51:29 +0530 Subject: [PATCH 13/19] AST-195928 Authenticate telemetry for failed re-logins --- internal/commands/auth_login.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index 6f8e65200..f3dff875f 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -181,13 +181,16 @@ func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryW } } -// sendLoginFailureTelemetry reports a sign-in that never produced a token. It is best effort: the hook -// telemetry transport only has a token cached from an earlier login, and without one the send fails -// without a network call. +// sendLoginFailureTelemetry reports a sign-in that never produced a token. It is best effort: auth login +// runs in a fresh process, while hook telemetry posts through a short-lived in-memory token cache. +// Seed that cache from any stored credential so a failed re-login can still report the failure. func sendLoginFailureTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, agent, authMethod, reason string, loginErr error) { if telemetryWrapper == nil { return } + if token, err := wrappers.GetAccessToken(); err == nil && strings.TrimSpace(token) != "" { + wrappers.CacheAuthenticatedAccessToken(token) + } data, attrs := loginTelemetryData(cmd, agent, authMethod) data.Status = hooktelemetry.StatusFailure data.StatusResult = hooktelemetry.FailureResult("Authentication", reason, hooktelemetry.ErrorCode(loginErr)) From 1bfe563f3cdfc3dfad17db78b699a993002b967f Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Tue, 1 Dec 2026 14:02:21 +0530 Subject: [PATCH 14/19] AST-195928 Keep failed logins cx cannot send for the Dev Assist plugin A signed-out cx has no token, so a failed cx auth login --agent ... could not report itself. The failure is now written to the plugin's state directory (cx_failed_logins.json), and the plugin sends it after the next successful sign-in. Co-authored-by: Cursor --- .../agenthooks/hooktelemetry/hooktelemetry.go | 64 +++++++++++++++++++ .../hooktelemetry/hooktelemetry_test.go | 36 +++++++++++ internal/commands/auth_login.go | 18 +++++- internal/commands/auth_login_test.go | 51 +++++++++++++++ 4 files changed, 167 insertions(+), 2 deletions(-) diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go index 2c9b7fe39..b617aa1c3 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -6,6 +6,7 @@ package hooktelemetry import ( "context" + "encoding/json" "errors" "fmt" "io" @@ -52,6 +53,9 @@ const ( pluginContextFile = "cx_telemetry_context" pluginContextMaxBytes = 4096 + + failedLoginsFile = "cx_failed_logins.json" + maxQueuedFailedLogins = 3 ) // severityOrder is the order severities appear in a scan event's statusResult. @@ -300,6 +304,66 @@ func PluginContext(agent string) map[string]string { return values } +// FailedLogin is a sign-in failure cx could not send, kept for the agent's Dev Assist plugin. +type FailedLogin struct { + Method string `json:"method"` + Reason string `json:"reason"` + ErrorCode string `json:"errorCode"` + At float64 `json:"at"` +} + +// QueueFailedLogin keeps a sign-in failure that cx could not send, usually because a signed-out cx has +// no token to post with. The Dev Assist plugin for agent (a telemetry agent label such as Claude-CLI) +// sends it after the next successful sign-in. Only the most recent failures are kept, and nothing is +// written for an unknown agent or when the plugin's state directory does not exist. +func QueueFailedLogin(agent string, failure FailedLogin) error { + leaf, ok := pluginStateDirs[strings.ToLower(strings.TrimSpace(agent))] + if !ok { + return nil + } + home, err := os.UserHomeDir() + if err != nil { + return err + } + dir := filepath.Join(home, ".checkmarx", "agent-logs", leaf) + if info, statErr := os.Stat(dir); statErr != nil || !info.IsDir() { + return nil + } + path := filepath.Join(dir, failedLoginsFile) + var failures []FailedLogin + if f, openErr := os.Open(path); openErr == nil { + raw, readErr := io.ReadAll(io.LimitReader(f, pluginContextMaxBytes+1)) + _ = f.Close() + if readErr == nil && len(raw) <= pluginContextMaxBytes && json.Unmarshal(raw, &failures) != nil { + failures = nil + } + } + failures = append(failures, failure) + if len(failures) > maxQueuedFailedLogins { + failures = failures[len(failures)-maxQueuedFailedLogins:] + } + raw, err := json.Marshal(failures) + if err != nil { + return err + } + tmp, err := os.CreateTemp(dir, failedLoginsFile+".*.tmp") + if err != nil { + return err + } + _, writeErr := tmp.Write(raw) + closeErr := tmp.Close() + if writeErr == nil { + writeErr = closeErr + } + if writeErr == nil { + writeErr = os.Rename(tmp.Name(), path) + } + if writeErr != nil { + _ = os.Remove(tmp.Name()) + } + return writeErr +} + // RepoURL returns the credential-free "origin" URL of the git repository containing workDir, or "" when // there is none. The result is cached per workDir for the life of the process. func RepoURL(workDir string) string { diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go index 130bbd518..8a3f89f2c 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -122,6 +122,42 @@ func TestPluginContext(t *testing.T) { assert.Equal(t, len(PluginContext("Cursor-CLI")), 0, "values outside the allowed character set are dropped") } +func TestQueueFailedLogin(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + dir := filepath.Join(home, ".checkmarx", "agent-logs", "claude") + path := filepath.Join(dir, failedLoginsFile) + + assert.NilError(t, QueueFailedLogin("Claude-CLI", FailedLogin{Method: "APIKey", At: 1})) + _, err := os.Stat(path) + assert.Assert(t, os.IsNotExist(err), "nothing is kept when the plugin has no state directory") + + assert.NilError(t, os.MkdirAll(dir, 0o755)) + assert.NilError(t, QueueFailedLogin("Unknown", FailedLogin{Method: "APIKey", At: 1})) + _, err = os.Stat(path) + assert.Assert(t, os.IsNotExist(err), "nothing is kept for an unknown agent") + + for at := 1; at <= 4; at++ { + failure := FailedLogin{Method: "APIKey", Reason: "api_key_authentication_failed", ErrorCode: "Unknown", At: float64(at)} + assert.NilError(t, QueueFailedLogin("Claude-CLI", failure)) + } + raw, err := os.ReadFile(path) + assert.NilError(t, err) + assert.Equal(t, string(raw), `[`+ + `{"method":"APIKey","reason":"api_key_authentication_failed","errorCode":"Unknown","at":2},`+ + `{"method":"APIKey","reason":"api_key_authentication_failed","errorCode":"Unknown","at":3},`+ + `{"method":"APIKey","reason":"api_key_authentication_failed","errorCode":"Unknown","at":4}]`, + "only the most recent failures are kept") + + assert.NilError(t, os.WriteFile(path, []byte("not json"), 0o600)) + assert.NilError(t, QueueFailedLogin("Claude-CLI", FailedLogin{Method: "OAuth", Reason: "browser_authentication_failed", ErrorCode: "Unknown", At: 5})) + raw, err = os.ReadFile(path) + assert.NilError(t, err) + assert.Equal(t, string(raw), `[{"method":"OAuth","reason":"browser_authentication_failed","errorCode":"Unknown","at":5}]`, + "an unreadable file is replaced") +} + func TestEnrich(t *testing.T) { dir := t.TempDir() repo, err := gogit.PlainInit(dir, false) diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index f3dff875f..84db18cec 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -5,6 +5,7 @@ import ( "fmt" "os" "strings" + "time" "github.com/MakeNowJust/heredoc" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" @@ -183,20 +184,33 @@ func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryW // sendLoginFailureTelemetry reports a sign-in that never produced a token. It is best effort: auth login // runs in a fresh process, while hook telemetry posts through a short-lived in-memory token cache. -// Seed that cache from any stored credential so a failed re-login can still report the failure. +// Seed that cache from any stored credential so a failed re-login can still report the failure. A +// signed-out cx has no token to post with, so a failure it cannot send is left for the agent's Dev +// Assist plugin to send after the next successful sign-in. func sendLoginFailureTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, agent, authMethod, reason string, loginErr error) { if telemetryWrapper == nil { return } + failedAt := time.Now() if token, err := wrappers.GetAccessToken(); err == nil && strings.TrimSpace(token) != "" { wrappers.CacheAuthenticatedAccessToken(token) } + errorCode := hooktelemetry.ErrorCode(loginErr) data, attrs := loginTelemetryData(cmd, agent, authMethod) data.Status = hooktelemetry.StatusFailure - data.StatusResult = hooktelemetry.FailureResult("Authentication", reason, hooktelemetry.ErrorCode(loginErr)) + data.StatusResult = hooktelemetry.FailureResult("Authentication", reason, errorCode) attrs["reasonCode"] = reason if err := telemetryWrapper.SendAIDataToLog(data); err != nil { logger.PrintIfVerbose("Failed to send authentication failure telemetry: " + err.Error()) + failure := hooktelemetry.FailedLogin{ + Method: authMethod, + Reason: reason, + ErrorCode: errorCode, + At: float64(failedAt.UnixNano()) / float64(time.Second), + } + if queueErr := hooktelemetry.QueueFailedLogin(agent, failure); queueErr != nil { + logger.PrintIfVerbose("Failed to keep the authentication failure for the plugin: " + queueErr.Error()) + } } } diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index 4071f641c..2dbbab06b 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -4,11 +4,13 @@ package commands import ( "bytes" + "encoding/json" "errors" "os" "path/filepath" "strings" "testing" + "time" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/credentialstore" @@ -420,6 +422,55 @@ func TestCompleteAuthLogin_CredentialSaveFailure(t *testing.T) { } } +func TestRunAuthLogin_UnsentFailureIsKeptForThePlugin(t *testing.T) { + withTempConfigDir(t) + swapCredentialResolver(t) + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + dir := filepath.Join(home, ".checkmarx", "agent-logs", "claude") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + queued := filepath.Join(dir, "cx_failed_logins.json") + login := func(sendErr error) { + cmd, _, _ := newBufferedCmd() + cmd.Flags().String(params.AstAPIKeyFlag, "", "") + cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") + for flag, value := range map[string]string{params.AstAPIKeyFlag: "not-a-token", params.AgentFlag: "claude-cli"} { + if err := cmd.Flags().Set(flag, value); err != nil { + t.Fatal(err) + } + } + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(*wrappers.DataForAITelemetry) error { + return sendErr + }} + if err := runAuthLogin(cmd, telemetry); err == nil { + t.Fatal("expected API-key verification to fail") + } + } + + login(nil) + if _, err := os.Stat(queued); !os.IsNotExist(err) { + t.Fatalf("a failure cx sent must not be kept for the plugin: %v", err) + } + + before := time.Now() + login(errors.New("no token")) + raw, err := os.ReadFile(queued) + if err != nil { + t.Fatal(err) + } + var failures []hooktelemetry.FailedLogin + if err := json.Unmarshal(raw, &failures); err != nil { + t.Fatal(err) + } + if len(failures) != 1 || failures[0].Method != "APIKey" || failures[0].Reason != "api_key_authentication_failed" || + failures[0].ErrorCode != "Unknown" || failures[0].At < float64(before.Unix()) { + t.Fatalf("unexpected kept failure: %s", raw) + } +} + func TestRunAuthLogin_FailureSendsTelemetry(t *testing.T) { withTempConfigDir(t) swapCredentialResolver(t) From 325a07eea85b2062c701ab02d78fa4b7d06eb94b Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:43:57 +0530 Subject: [PATCH 15/19] AST-195928 Address review findings on the agent telemetry changes Restore the auth validate authentication event for the default agent, keep @ in repo URL paths and IPv6 hosts when sanitizing, count only the reported severities in totalCount, require https for the API-key realm (loopback excepted), cap the stored-token lookup on failed logins at 1s, and end kics_test.go with a newline. Co-Authored-By: Claude Sonnet 5.5 --- .../agenthooks/guardrails/kics/kics_test.go | 2 +- .../agenthooks/hooktelemetry/hooktelemetry.go | 49 +++++++++++++++---- .../hooktelemetry/hooktelemetry_test.go | 18 +++++++ internal/commands/auth.go | 17 ++++--- internal/commands/auth_login.go | 25 +++++++++- internal/wrappers/api_key_realm_test.go | 42 ++++++++++++++++ internal/wrappers/client.go | 19 ++++++- 7 files changed, 152 insertions(+), 20 deletions(-) create mode 100644 internal/wrappers/api_key_realm_test.go diff --git a/internal/commands/agenthooks/guardrails/kics/kics_test.go b/internal/commands/agenthooks/guardrails/kics/kics_test.go index f4c767d4b..3c30dba2f 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics_test.go +++ b/internal/commands/agenthooks/guardrails/kics/kics_test.go @@ -231,4 +231,4 @@ func TestScanFileEdit_EngineDownProducesNote(t *testing.T) { assert.False(t, res.blocked, "must fail open, not block the edit") assert.Contains(t, res.note, "main.tf") assert.Contains(t, res.note, "not running") -} \ No newline at end of file +} diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go index b617aa1c3..000252459 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -192,7 +192,7 @@ func LogScan(telemetry wrappers.TelemetryWrapper, agent, engine, sessionID, work Type: scanEventType, SubType: scanEventSubType, APIVersion: APIVersionV2, AIProvider: agent, Agent: hostenv.TelemetryAgent(agent), Engine: engine, ScanType: strings.ToLower(engine), - TotalCount: len(severities), ProblemSeverity: severity, StatusResult: statusResult, + TotalCount: countKnownSeverities(severities), ProblemSeverity: severity, StatusResult: statusResult, UniqueID: wrappers.GetUniqueID(), AiAgentSessionId: sessionID, EventAttributes: &attrs, } @@ -231,6 +231,20 @@ func LogScanFailure(telemetry wrappers.TelemetryWrapper, agent, engine, sessionI _ = telemetry.SendAIDataToLog(data) } +// countKnownSeverities counts the severities ScanSeveritySummary reports, so totalCount matches statusResult. +func countKnownSeverities(severities []string) int { + total := 0 + for _, s := range severities { + for _, known := range severityOrder { + if strings.EqualFold(s, known) { + total++ + break + } + } + } + return total +} + // ScanSeveritySummary returns the highest detected severity and the counts for statusResult. // Severities outside the known five are not counted. func ScanSeveritySummary(severities []string) (highest, statusResult string) { @@ -396,6 +410,21 @@ func originURL(workDir string) string { return urls[0] } +// hostWithoutPort drops a port so ssh and https remotes of the same repository match. A bracketed IPv6 +// host keeps its brackets; an unbracketed one has no port to drop. +func hostWithoutPort(host string) string { + if strings.HasPrefix(host, "[") { + if end := strings.IndexByte(host, ']'); end >= 0 { + return host[:end+1] + } + return host + } + if strings.Count(host, ":") == 1 { + host, _, _ = strings.Cut(host, ":") + } + return host +} + // SanitizeRepoURL removes every credential from a git remote URL so it is safe to send: the userinfo of // any scheme (tokens, passwords and usernames), the query and the fragment. An SCP-style remote // (git@host:org/repo) becomes https://host/org/repo. A local path, or anything unrecognised, returns "". @@ -407,11 +436,16 @@ func SanitizeRepoURL(raw string) string { var host, path string if i := strings.Index(raw, schemeSeparator); i >= 0 { rest := raw[i+len(schemeSeparator):] - if at := strings.LastIndexByte(rest, '@'); at >= 0 { - rest = rest[at+1:] + // Userinfo can only sit in the authority, so look for '@' before the first '/', '?' or '#'. An '@' + // later on belongs to the path (https://host/org/repo@v1). + authority, tail := rest, "" + if end := strings.IndexAny(rest, "/?#"); end >= 0 { + authority, tail = rest[:end], rest[end:] } - host, path, _ = strings.Cut(rest, "/") - path = "/" + path + if at := strings.LastIndexByte(authority, '@'); at >= 0 { + authority = authority[at+1:] + } + host, path = authority, tail } else { // SCP-style: [user@]host:path. A Windows drive (C:\...) or a bare path has no host part. colon := strings.IndexByte(raw, ':') @@ -427,10 +461,7 @@ func SanitizeRepoURL(raw string) string { if j := strings.IndexAny(path, "?#"); j >= 0 { path = path[:j] } - // Drop a port so ssh and https remotes of the same repository match. - if k := strings.LastIndexByte(host, ':'); k >= 0 { - host = host[:k] - } + host = hostWithoutPort(host) if host == "" { return "" } diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go index 8a3f89f2c..9ebfa9499 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -40,6 +40,12 @@ func TestSanitizeRepoURL(t *testing.T) { {"ssh://git@github.com:22/acme/repo.git", "https://github.com/acme/repo"}, {"git@github.com:acme/repo.git", "https://github.com/acme/repo"}, {"https://dev.azure.com:443/org/proj/_git/repo/", "https://dev.azure.com/org/proj/_git/repo"}, + {"https://github.com/acme/repo@v1", "https://github.com/acme/repo@v1"}, + {"https://token@github.com/acme/repo@v1", "https://github.com/acme/repo@v1"}, + {"https://github.com?token=abc", "https://github.com"}, + {"https://[::1]/acme/repo", "https://[::1]/acme/repo"}, + {"https://[::1]:8443/acme/repo.git", "https://[::1]/acme/repo"}, + {"ssh://git@[2001:db8::1]:22/acme/repo", "https://[2001:db8::1]/acme/repo"}, {`C:\work\repo`, ""}, {"/home/me/repo", ""}, {"", ""}, @@ -104,6 +110,18 @@ func TestLogScan(t *testing.T) { assert.Assert(t, !hasSession) } +func TestLogScanTotalCountMatchesTheSeveritiesReported(t *testing.T) { + t.Setenv("CX_COPILOT_HOST", "") + var event *wrappers.DataForAITelemetry + tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + event = data + return nil + }} + LogScan(tel, "Claude", "Asca", "", "", []string{"High", "Unrecognised", ""}) + assert.Equal(t, event.TotalCount, 1) + assert.Equal(t, event.StatusResult, "Critical=0, High=1, Medium=0, Low=0, Info=0") +} + func TestPluginContext(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) diff --git a/internal/commands/auth.go b/internal/commands/auth.go index 4502c265e..d3a953f31 100644 --- a/internal/commands/auth.go +++ b/internal/commands/auth.go @@ -136,18 +136,19 @@ func validLogin(telemetryWrapper wrappers.TelemetryWrapper) func(cmd *cobra.Comm authWrapper.SetPath(viper.GetString(params.ScansPathKey)) err := authWrapper.ValidateLogin() + // Send telemetry only for CLI agents 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()) - // } + telemetryErr := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{ + UniqueID: uniqueID, + Type: "authentication", + SubType: "authentication", + }) + if telemetryErr != nil { + logger.PrintIfVerbose("Failed to send telemetry data: " + telemetryErr.Error()) + } } } diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index 84db18cec..4688afb42 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -182,6 +182,29 @@ func sendLoginTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryW } } +// loginFailureTokenTimeout bounds how long reporting a failed sign-in may wait on IAM for a stored token, +// the same cap a hook telemetry POST has. +const loginFailureTokenTimeout = time.Second + +// storedAccessTokenWithin returns a token for the stored credential, or "" when there is none or IAM does +// not answer within the timeout. +func storedAccessTokenWithin(timeout time.Duration) string { + result := make(chan string, 1) + go func() { + token, err := wrappers.GetAccessToken() + if err != nil { + token = "" + } + result <- strings.TrimSpace(token) + }() + select { + case token := <-result: + return token + case <-time.After(timeout): + return "" + } +} + // sendLoginFailureTelemetry reports a sign-in that never produced a token. It is best effort: auth login // runs in a fresh process, while hook telemetry posts through a short-lived in-memory token cache. // Seed that cache from any stored credential so a failed re-login can still report the failure. A @@ -192,7 +215,7 @@ func sendLoginFailureTelemetry(cmd *cobra.Command, telemetryWrapper wrappers.Tel return } failedAt := time.Now() - if token, err := wrappers.GetAccessToken(); err == nil && strings.TrimSpace(token) != "" { + if token := storedAccessTokenWithin(loginFailureTokenTimeout); token != "" { wrappers.CacheAuthenticatedAccessToken(token) } errorCode := hooktelemetry.ErrorCode(loginErr) diff --git a/internal/wrappers/api_key_realm_test.go b/internal/wrappers/api_key_realm_test.go new file mode 100644 index 000000000..d62663dcf --- /dev/null +++ b/internal/wrappers/api_key_realm_test.go @@ -0,0 +1,42 @@ +package wrappers + +import ( + "net/url" + "testing" +) + +func TestIsSecureRealmScheme(t *testing.T) { + tests := []struct { + realm string + want bool + }{ + {"https://iam.example.com/auth/realms/org", true}, + {"https://127.0.0.1:8443/auth/realms/org", true}, + {"http://127.0.0.1:8080/auth/realms/org", true}, + {"http://localhost:8080/auth/realms/org", true}, + {"http://[::1]:8080/auth/realms/org", true}, + {"http://iam.example.com/auth/realms/org", false}, + {"http://10.0.0.5/auth/realms/org", false}, + {"ftp://iam.example.com/auth/realms/org", false}, + } + for _, tt := range tests { + parsed, err := url.Parse(tt.realm) + if err != nil { + t.Fatalf("parse %q: %v", tt.realm, err) + } + if got := isSecureRealmScheme(parsed); got != tt.want { + t.Errorf("isSecureRealmScheme(%q) = %v, want %v", tt.realm, got, tt.want) + } + } +} + +func TestExchangeLoginAPIKey_RejectsPlainHTTPRealm(t *testing.T) { + apiKey := unsignedJWT(map[string]interface{}{"aud": "http://iam.example.com/auth/realms/organization"}) + token, err := ExchangeLoginAPIKey(apiKey) + if err == nil || token != "" { + t.Fatal("a non-loopback http realm must be rejected before any request is made") + } + if err.Error() != "API key has an invalid IAM realm URL" { + t.Fatalf("unexpected error: %v", err) + } +} diff --git a/internal/wrappers/client.go b/internal/wrappers/client.go index 0c44c8aa6..a51aa7725 100644 --- a/internal/wrappers/client.go +++ b/internal/wrappers/client.go @@ -705,6 +705,23 @@ func InvalidateAccessTokenCache() { cachedAccessTime = time.Time{} } +// isSecureRealmScheme accepts https, and plain http only for a loopback host, so the key is never +// exchanged in clear text with a realm named by the key itself. +func isSecureRealmScheme(realm *url.URL) bool { + if realm.Scheme == "https" { + return true + } + if realm.Scheme != "http" { + return false + } + host := realm.Hostname() + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + // ExchangeLoginAPIKey verifies the supplied key with IAM without using the access-token cache. func ExchangeLoginAPIKey(apiKey string) (string, error) { logger.RegisterSensitiveValue(apiKey) @@ -714,7 +731,7 @@ func ExchangeLoginAPIKey(apiKey string) (string, error) { } parsedRealm, err := url.Parse(realmURL) if err != nil || parsedRealm.Hostname() == "" || parsedRealm.User != nil || - (parsedRealm.Scheme != "https" && parsedRealm.Scheme != "http") || parsedRealm.RawQuery != "" || parsedRealm.Fragment != "" { + !isSecureRealmScheme(parsedRealm) || parsedRealm.RawQuery != "" || parsedRealm.Fragment != "" { return "", errors.New("API key has an invalid IAM realm URL") } accessToken, err := getNewToken(getAPIKeyPayload(apiKey), strings.TrimRight(realmURL, "/")+"/"+BaseAuthURLSuffix) From 9c6aa69ebf7fbb502a864b8a6d22697c78ae4a6e Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:27:22 +0530 Subject: [PATCH 16/19] AST-195928 Fix golangci-lint findings in the agent telemetry changes Reuse authenticationEventType in the auth validate event, name the repeated plugin-context keys and agent state dirs, check the plugin context file close, and add a containers engine constant. Split the two login telemetry tests into helpers to bring them under the cyclomatic limit, reuse existing constants in the hostenv and hooktelemetry tests, and mark the table-driven test fixtures that repeat values on purpose with nolint:goconst, as predicates_test.go already does. Co-Authored-By: Claude Sonnet 5.5 --- internal/commands/agenthooks/cx/hooks_test.go | 2 + .../agenthooks/hooktelemetry/hooktelemetry.go | 30 +- .../hooktelemetry/hooktelemetry_test.go | 10 +- .../agenthooks/hostenv/hostenv_test.go | 11 +- .../agenthooks/sca/telemetry_ids_test.go | 2 + .../commands/agenthooks/sca/threshold_test.go | 1 + internal/commands/auth.go | 4 +- internal/commands/auth_login_test.go | 238 ++++---- internal/commands/config.yaml | 0 internal/commands/ignore_vulnerability.go | 7 +- .../ignore_vulnerability_telemetry_test.go | 7 + internal/commands/telemetry_test.go | 245 ++++---- internal/wrappers/api_key_realm_test.go | 2 +- internal/wrappers/jwt-helper_test.go | 567 +++++++++--------- 14 files changed, 597 insertions(+), 529 deletions(-) create mode 100644 internal/commands/config.yaml diff --git a/internal/commands/agenthooks/cx/hooks_test.go b/internal/commands/agenthooks/cx/hooks_test.go index 95f5a2b7a..a1f4b7439 100644 --- a/internal/commands/agenthooks/cx/hooks_test.go +++ b/internal/commands/agenthooks/cx/hooks_test.go @@ -195,6 +195,7 @@ func TestCxBeforeToolCall_ToolRule_AsksUser(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestCxBeforeToolCall_SCAFinding_DeniesWithContext(t *testing.T) { resetHookGlobals(t) tel := &recordingTelemetry{} @@ -624,6 +625,7 @@ func TestRegisterGuardrails_AndPassThrough(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestLogRemediationTelemetry(t *testing.T) { resetHookGlobals(t) diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go index 000252459..9afa647ea 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -121,9 +121,9 @@ func IgnoreFlags(agent, sessionID string) string { pairs := []string{"aiProvider=" + agent, "agent=" + hostenv.TelemetryAgent(agent)} for _, field := range []struct{ key, value string }{ {"aiAgentSessionId", sessionID}, - {"agentVersion", os.Getenv(params.AgentVersionEnv)}, - {"cxPluginVersion", os.Getenv(params.CxPluginVersionEnv)}, - {"pluginType", os.Getenv(params.PluginTypeEnv)}, + {contextKeyAgentVersion, os.Getenv(params.AgentVersionEnv)}, + {contextKeyCxPluginVersion, os.Getenv(params.CxPluginVersionEnv)}, + {contextKeyPluginType, os.Getenv(params.PluginTypeEnv)}, } { value := strings.TrimSpace(field.value) if ignoreFlagValue.MatchString(value) { @@ -272,17 +272,27 @@ func ScanSeveritySummary(severities []string) (highest, statusResult string) { // ~/.checkmarx/agent-logs, where the plugin keeps its cx_telemetry_context file. var pluginStateDirs = map[string]string{ "claude-cli": "claude", - "copilot-cli": "copilot-cli", - "copilot-vscode": "copilot-cli", + copilotCLIAgent: copilotCLIAgent, + "copilot-vscode": copilotCLIAgent, "cursor-cli": "cursor", "codex-cli": "codex", - "gemini-cli": "gemini-cli", + geminiCLIAgent: geminiCLIAgent, } +// The keys PluginContext returns and IgnoreFlags passes on to the ignore command. +const ( + contextKeyAgentVersion = "agentVersion" + contextKeyCxPluginVersion = "cxPluginVersion" + contextKeyPluginType = "pluginType" + + copilotCLIAgent = "copilot-cli" + geminiCLIAgent = "gemini-cli" +) + var pluginContextKeys = map[string]string{ - "CX_AGENT_VERSION": "agentVersion", - "CX_PLUGIN_VERSION": "cxPluginVersion", - "CX_PLUGIN_TYPE": "pluginType", + "CX_AGENT_VERSION": contextKeyAgentVersion, + "CX_PLUGIN_VERSION": contextKeyCxPluginVersion, + "CX_PLUGIN_TYPE": contextKeyPluginType, } // PluginContext reads the agent version, plugin version and plugin type that the Dev Assist plugin @@ -303,7 +313,7 @@ func PluginContext(agent string) map[string]string { if err != nil { return values } - defer f.Close() + defer func() { _ = f.Close() }() raw, err := io.ReadAll(io.LimitReader(f, pluginContextMaxBytes+1)) if err != nil || len(raw) > pluginContextMaxBytes { return values diff --git a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go index 9ebfa9499..881eaab3e 100644 --- a/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -30,6 +30,7 @@ func testRemotePassword() string { return "unused" } +//nolint:goconst // test fixtures repeat values on purpose func TestSanitizeRepoURL(t *testing.T) { credentialedURL := "https://user:" + testRemotePassword() + "@github.com/acme/repo" tests := []struct{ in, want string }{ @@ -55,6 +56,7 @@ func TestSanitizeRepoURL(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestScanSeveritySummary(t *testing.T) { highest, counts := ScanSeveritySummary([]string{"High", "critical", "High", "Low", "unknown"}) assert.Equal(t, highest, "Critical") @@ -72,7 +74,7 @@ func TestFailureResult(t *testing.T) { func TestErrorCode(t *testing.T) { assert.Equal(t, ErrorCode(nil), ErrorCodeNone) assert.Equal(t, ErrorCode(context.DeadlineExceeded), "DeadlineExceeded") - assert.Equal(t, ErrorCode(errors.New("boom")), "Unknown") + assert.Equal(t, ErrorCode(errors.New("boom")), errorCodeUnknown) } func TestLogScan(t *testing.T) { @@ -140,6 +142,7 @@ func TestPluginContext(t *testing.T) { assert.Equal(t, len(PluginContext("Cursor-CLI")), 0, "values outside the allowed character set are dropped") } +//nolint:goconst // test fixtures repeat values on purpose func TestQueueFailedLogin(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) @@ -157,7 +160,7 @@ func TestQueueFailedLogin(t *testing.T) { assert.Assert(t, os.IsNotExist(err), "nothing is kept for an unknown agent") for at := 1; at <= 4; at++ { - failure := FailedLogin{Method: "APIKey", Reason: "api_key_authentication_failed", ErrorCode: "Unknown", At: float64(at)} + failure := FailedLogin{Method: "APIKey", Reason: "api_key_authentication_failed", ErrorCode: errorCodeUnknown, At: float64(at)} assert.NilError(t, QueueFailedLogin("Claude-CLI", failure)) } raw, err := os.ReadFile(path) @@ -169,7 +172,7 @@ func TestQueueFailedLogin(t *testing.T) { "only the most recent failures are kept") assert.NilError(t, os.WriteFile(path, []byte("not json"), 0o600)) - assert.NilError(t, QueueFailedLogin("Claude-CLI", FailedLogin{Method: "OAuth", Reason: "browser_authentication_failed", ErrorCode: "Unknown", At: 5})) + assert.NilError(t, QueueFailedLogin("Claude-CLI", FailedLogin{Method: "OAuth", Reason: "browser_authentication_failed", ErrorCode: errorCodeUnknown, At: 5})) raw, err = os.ReadFile(path) assert.NilError(t, err) assert.Equal(t, string(raw), `[{"method":"OAuth","reason":"browser_authentication_failed","errorCode":"Unknown","at":5}]`, @@ -201,6 +204,7 @@ func TestEnrich(t *testing.T) { assert.Equal(t, data.Status, StatusSuccess) } +//nolint:goconst // test fixtures repeat values on purpose func TestRemediationFindings(t *testing.T) { SetRemediationFindings([]string{"CVE-1", " ", "CVE-2", "CVE-1"}, 4) ids, count := TakeRemediationFindings() diff --git a/internal/commands/agenthooks/hostenv/hostenv_test.go b/internal/commands/agenthooks/hostenv/hostenv_test.go index 7e53713cb..f065d4927 100644 --- a/internal/commands/agenthooks/hostenv/hostenv_test.go +++ b/internal/commands/agenthooks/hostenv/hostenv_test.go @@ -75,15 +75,16 @@ func TestPluginHostFromPlugin(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestTelemetryAgent(t *testing.T) { cases := []struct { name, agent, root, want string }{ - {"terminal Copilot", "Copilot", rootCLI, "Copilot-CLI"}, - {"VS Code copy of a Copilot CLI install", "Copilot", rootVSCodeFromCLIInstall, "Copilot-VSCode"}, - {"VS Code marketplace install", "Copilot", rootVSCodeFromMarketplace, "Copilot-VSCode"}, - {"VS Code fork stays -CLI", "Copilot", `C:\Users\u\AppData\Roaming\Windsurf\agentPlugins\x\1a`, "Copilot-CLI"}, - {"no host signal stays -CLI", "Copilot", "", "Copilot-CLI"}, + {"terminal Copilot", copilotAgent, rootCLI, "Copilot-CLI"}, + {"VS Code copy of a Copilot CLI install", copilotAgent, rootVSCodeFromCLIInstall, agentVSCode}, + {"VS Code marketplace install", copilotAgent, rootVSCodeFromMarketplace, agentVSCode}, + {"VS Code fork stays -CLI", copilotAgent, `C:\Users\u\AppData\Roaming\Windsurf\agentPlugins\x\1a`, "Copilot-CLI"}, + {"no host signal stays -CLI", copilotAgent, "", "Copilot-CLI"}, {"other agents unchanged in VS Code", "Claude", rootVSCodeFromCLIInstall, "Claude-CLI"}, {"other agents unchanged", "Cursor", "", "Cursor-CLI"}, } diff --git a/internal/commands/agenthooks/sca/telemetry_ids_test.go b/internal/commands/agenthooks/sca/telemetry_ids_test.go index 13d389f4a..a95786d68 100644 --- a/internal/commands/agenthooks/sca/telemetry_ids_test.go +++ b/internal/commands/agenthooks/sca/telemetry_ids_test.go @@ -11,6 +11,7 @@ import ( "github.com/checkmarx/ast-cli/internal/wrappers/mock" ) +//nolint:goconst // test fixtures repeat values on purpose func TestDenyFrom_RecordsRemediationFindings(t *testing.T) { old := BelowThreshold t.Cleanup(func() { BelowThreshold = old }) @@ -38,6 +39,7 @@ func TestDenyFrom_RecordsRemediationFindings(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestLogScan_SendsDetectedCounts(t *testing.T) { var sent []*wrappers.DataForAITelemetry s := &Scanner{Telemetry: mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(d *wrappers.DataForAITelemetry) error { diff --git a/internal/commands/agenthooks/sca/threshold_test.go b/internal/commands/agenthooks/sca/threshold_test.go index 79a694635..a6a1bf538 100644 --- a/internal/commands/agenthooks/sca/threshold_test.go +++ b/internal/commands/agenthooks/sca/threshold_test.go @@ -30,6 +30,7 @@ func TestAboveThreshold_DropsLowCVEsAndEmptyPackages(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestHighestVulnSeverityUsesScanSeverityRules(t *testing.T) { for _, tc := range []struct { name string diff --git a/internal/commands/auth.go b/internal/commands/auth.go index d3a953f31..7107e5111 100644 --- a/internal/commands/auth.go +++ b/internal/commands/auth.go @@ -143,8 +143,8 @@ func validLogin(telemetryWrapper wrappers.TelemetryWrapper) func(cmd *cobra.Comm if uniqueID != "" { telemetryErr := telemetryWrapper.SendAIDataToLog(&wrappers.DataForAITelemetry{ UniqueID: uniqueID, - Type: "authentication", - SubType: "authentication", + Type: authenticationEventType, + SubType: authenticationEventType, }) if telemetryErr != nil { logger.PrintIfVerbose("Failed to send telemetry data: " + telemetryErr.Error()) diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index 2dbbab06b..330474f75 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -246,15 +246,17 @@ func TestPersistLogin_PrintsSuccessMessage(t *testing.T) { } } +type telemetryAgentCase struct { + name string + agent *string + want string +} + +//nolint:goconst // test fixtures repeat values on purpose func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { - const credential = "test-login-credential" t.Setenv(params.AgentVersionEnv, "fallback-agent") t.Setenv(params.CxPluginVersionEnv, "fallback-plugin") - cases := []struct { - name string - agent *string - want string - }{ + cases := []telemetryAgentCase{ {name: "omitted"}, {name: "blank", agent: testLoginAgent(" ")}, {name: "default", agent: testLoginAgent("ASTCLI")}, @@ -266,64 +268,88 @@ func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { {name: "codex", agent: testLoginAgent("codex-cli"), want: "Codex-CLI"}, } for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - withTempConfigDir(t) - store := swapCredentialResolver(t) - oldExpiry, oldSession := viper.Get(params.TokenExpirySecondsKey), viper.Get(params.SessionIDConfigKey) - t.Cleanup(func() { - viper.Set(params.TokenExpirySecondsKey, oldExpiry) - viper.Set(params.SessionIDConfigKey, oldSession) - wrappers.InvalidateAccessTokenCache() - }) - viper.Set(params.TokenExpirySecondsKey, 120) - viper.Set(params.SessionIDConfigKey, "") - cmd := newAuthLoginCommand(nil) - for flag, value := range map[string]string{ - params.AgentVersionFlag: "1.2.3", params.CxPluginVersionFlag: "4.5.6", params.AIAgentSessionIDFlag: "current-session", - } { - if err := cmd.Flags().Set(flag, value); err != nil { - t.Fatal(err) - } - } - cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") - if tc.agent != nil { - if err := cmd.Flags().Set(params.AgentFlag, *tc.agent); err != nil { - t.Fatal(err) - } - } - calls := 0 - telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - calls++ - if store.Store[credentialstore.CredentialAPIKey] != credential { - t.Fatal("telemetry sent before credential was saved") - } - if data.Agent != tc.want || data.Type != authenticationEventType || - data.SubType != authenticationEventType || data.Status != hooktelemetry.StatusSuccess || - data.StatusResult != "Authentication successful." || data.AIProvider+"-CLI" != tc.want || - data.SessionID == "" || (*data.EventAttributes)["authMethod"] != "OAuth" { - t.Fatalf("unexpected authentication telemetry: %+v", data) - } - if data.AgentVersion != "1.2.3" || data.CxPluginVersion != "4.5.6" || - data.AIProvider == "" || data.AiAgentSessionId != "current-session" || - (*data.EventAttributes)["aiAgentSessionId"] != "current-session" { - t.Fatalf("missing login metadata: %+v", data) - } - return errors.New("telemetry unavailable") - }} - if err := completeAuthLogin(cmd, telemetry, credential, "test-access-token", "OAuth"); err != nil { - t.Fatal(err) - } - if tc.want == "" { - if calls != 0 || viper.GetString(params.SessionIDConfigKey) != "" { - t.Fatal("non-eligible login sent telemetry or generated a session ID") - } - } else if calls != 1 || readYamlKey(t, params.SessionIDConfigKey) == "" { - t.Fatal("eligible login should send one event and persist a session ID") - } - if store.Store[credentialstore.CredentialAPIKey] != credential { - t.Fatal("login credential was not saved") - } - }) + t.Run(tc.name, func(t *testing.T) { runTelemetryAgentAllowlistCase(t, tc) }) + } +} + +func runTelemetryAgentAllowlistCase(t *testing.T, tc telemetryAgentCase) { + const credential = "test-login-credential" + withTempConfigDir(t) + store := swapCredentialResolver(t) + oldExpiry, oldSession := viper.Get(params.TokenExpirySecondsKey), viper.Get(params.SessionIDConfigKey) + t.Cleanup(func() { + viper.Set(params.TokenExpirySecondsKey, oldExpiry) + viper.Set(params.SessionIDConfigKey, oldSession) + wrappers.InvalidateAccessTokenCache() + }) + viper.Set(params.TokenExpirySecondsKey, 120) + viper.Set(params.SessionIDConfigKey, "") + cmd := newAuthLoginCommand(nil) + setTelemetryLoginFlags(t, cmd, tc.agent) + calls := 0 + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + calls++ + if store.Store[credentialstore.CredentialAPIKey] != credential { + t.Fatal("telemetry sent before credential was saved") + } + assertAuthenticationSuccessEvent(t, data, tc.want) + assertLoginMetadata(t, data) + return errors.New("telemetry unavailable") + }} + if err := completeAuthLogin(cmd, telemetry, credential, "test-access-token", "OAuth"); err != nil { + t.Fatal(err) + } + assertAllowlistOutcome(t, tc.want, calls) + if store.Store[credentialstore.CredentialAPIKey] != credential { + t.Fatal("login credential was not saved") + } +} + +//nolint:goconst // test fixtures repeat values on purpose +func setTelemetryLoginFlags(t *testing.T, cmd *cobra.Command, agent *string) { + t.Helper() + for flag, value := range map[string]string{ + params.AgentVersionFlag: "1.2.3", params.CxPluginVersionFlag: "4.5.6", params.AIAgentSessionIDFlag: "current-session", + } { + if err := cmd.Flags().Set(flag, value); err != nil { + t.Fatal(err) + } + } + cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") + if agent != nil { + if err := cmd.Flags().Set(params.AgentFlag, *agent); err != nil { + t.Fatal(err) + } + } +} + +func assertAuthenticationSuccessEvent(t *testing.T, data *wrappers.DataForAITelemetry, want string) { + t.Helper() + if data.Agent != want || data.Type != authenticationEventType || + data.SubType != authenticationEventType || data.Status != hooktelemetry.StatusSuccess || + data.StatusResult != "Authentication successful." || data.AIProvider+"-CLI" != want || + data.SessionID == "" || (*data.EventAttributes)["authMethod"] != "OAuth" { + t.Fatalf("unexpected authentication telemetry: %+v", data) + } +} + +func assertLoginMetadata(t *testing.T, data *wrappers.DataForAITelemetry) { + t.Helper() + if data.AgentVersion != "1.2.3" || data.CxPluginVersion != "4.5.6" || + data.AIProvider == "" || data.AiAgentSessionId != "current-session" || + (*data.EventAttributes)["aiAgentSessionId"] != "current-session" { + t.Fatalf("missing login metadata: %+v", data) + } +} + +func assertAllowlistOutcome(t *testing.T, want string, calls int) { + t.Helper() + if want == "" { + if calls != 0 || viper.GetString(params.SessionIDConfigKey) != "" { + t.Fatal("non-eligible login sent telemetry or generated a session ID") + } + } else if calls != 1 || readYamlKey(t, params.SessionIDConfigKey) == "" { + t.Fatal("eligible login should send one event and persist a session ID") } } @@ -331,6 +357,7 @@ func testLoginAgent(agent string) *string { return &agent } +//nolint:goconst // test fixtures repeat values on purpose func TestLoginTelemetryData_PluginContextFallback(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) @@ -422,6 +449,7 @@ func TestCompleteAuthLogin_CredentialSaveFailure(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestRunAuthLogin_UnsentFailureIsKeptForThePlugin(t *testing.T) { withTempConfigDir(t) swapCredentialResolver(t) @@ -476,43 +504,49 @@ func TestRunAuthLogin_FailureSendsTelemetry(t *testing.T) { swapCredentialResolver(t) cases := []struct{ name, agent string }{{"eligible agent", "claude-cli"}, {"no agent", ""}} for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - cmd, _, _ := newBufferedCmd() - cmd.Flags().String(params.AstAPIKeyFlag, "", "") - cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") - if err := cmd.Flags().Set(params.AstAPIKeyFlag, "not-a-token"); err != nil { - t.Fatal(err) - } - if tc.agent != "" { - if err := cmd.Flags().Set(params.AgentFlag, tc.agent); err != nil { - t.Fatal(err) - } - } - var events []*wrappers.DataForAITelemetry - telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { - events = append(events, data) - return nil - }} - if err := runAuthLogin(cmd, telemetry); err == nil { - t.Fatal("expected API-key verification to fail") - } - if tc.agent == "" { - if len(events) != 0 { - t.Fatalf("login without an agent sent telemetry: %+v", events) - } - return - } - if len(events) != 1 { - t.Fatalf("got %d events, want 1", len(events)) - } - event := events[0] - if event.Type != authenticationEventType || event.Agent != "Claude-CLI" || event.AIProvider != "Claude" || - event.Status != hooktelemetry.StatusFailure || event.SessionID != "" || - !strings.HasPrefix(event.StatusResult, "Authentication failed. Reason: api_key_authentication_failed, Error Code: ") || - (*event.EventAttributes)["reasonCode"] != "api_key_authentication_failed" || - (*event.EventAttributes)["authMethod"] != "APIKey" { - t.Fatalf("unexpected login failure telemetry: %+v", event) - } - }) + t.Run(tc.name, func(t *testing.T) { runLoginFailureTelemetryCase(t, tc.agent) }) + } +} + +func runLoginFailureTelemetryCase(t *testing.T, agent string) { + cmd, _, _ := newBufferedCmd() + cmd.Flags().String(params.AstAPIKeyFlag, "", "") + cmd.Flags().String(params.AgentFlag, params.DefaultAgent, "") + if err := cmd.Flags().Set(params.AstAPIKeyFlag, "not-a-token"); err != nil { + t.Fatal(err) + } + if agent != "" { + if err := cmd.Flags().Set(params.AgentFlag, agent); err != nil { + t.Fatal(err) + } + } + var events []*wrappers.DataForAITelemetry + telemetry := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(data *wrappers.DataForAITelemetry) error { + events = append(events, data) + return nil + }} + if err := runAuthLogin(cmd, telemetry); err == nil { + t.Fatal("expected API-key verification to fail") + } + if agent == "" { + if len(events) != 0 { + t.Fatalf("login without an agent sent telemetry: %+v", events) + } + return + } + if len(events) != 1 { + t.Fatalf("got %d events, want 1", len(events)) + } + assertAPIKeyFailureEvent(t, events[0]) +} + +func assertAPIKeyFailureEvent(t *testing.T, event *wrappers.DataForAITelemetry) { + t.Helper() + if event.Type != authenticationEventType || event.Agent != "Claude-CLI" || event.AIProvider != "Claude" || + event.Status != hooktelemetry.StatusFailure || event.SessionID != "" || + !strings.HasPrefix(event.StatusResult, "Authentication failed. Reason: api_key_authentication_failed, Error Code: ") || + (*event.EventAttributes)["reasonCode"] != "api_key_authentication_failed" || + (*event.EventAttributes)["authMethod"] != "APIKey" { + t.Fatalf("unexpected login failure telemetry: %+v", event) } } diff --git a/internal/commands/config.yaml b/internal/commands/config.yaml new file mode 100644 index 000000000..e69de29bb diff --git a/internal/commands/ignore_vulnerability.go b/internal/commands/ignore_vulnerability.go index 153d77269..bdca54c3d 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -262,13 +262,16 @@ func ignoreEntryID(entry any) string { } } +// containersEngine is the telemetry engine label for container images. +const containersEngine = "Containers" + // ignoreSubType is the hooks-ignore subType for an engine label: packages and images are ignored by // coordinates, every other engine by finding. func ignoreSubType(engine string) string { switch engine { case hooktelemetry.EngineOSS: return "ignorePackage" - case "Containers": + case containersEngine: return "ignoreImage" default: return "ignoreFinding" @@ -283,7 +286,7 @@ func engineName(scanType string) string { case ignore.ScanTypeSecrets: return "Secrets" case ignore.ScanTypeContainers: - return "Containers" + return containersEngine case ignore.ScanTypeIaC: return "Iac" case ignore.ScanTypeASCA: diff --git a/internal/commands/ignore_vulnerability_telemetry_test.go b/internal/commands/ignore_vulnerability_telemetry_test.go index 0f1111846..a00d9387b 100644 --- a/internal/commands/ignore_vulnerability_telemetry_test.go +++ b/internal/commands/ignore_vulnerability_telemetry_test.go @@ -22,6 +22,7 @@ import ( "github.com/spf13/viper" ) +//nolint:goconst // test fixtures repeat values on purpose func TestIgnoreEntryID(t *testing.T) { cases := []struct { entry any @@ -42,6 +43,7 @@ func TestIgnoreEntryID(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestLogIgnoreTelemetry_CarriesIDsAndNeverTheSecret(t *testing.T) { var sent *wrappers.DataForAITelemetry tel := mock.TelemetryMockWrapper{CustomSendAIDataToLog: func(d *wrappers.DataForAITelemetry) error { @@ -66,6 +68,7 @@ func TestLogIgnoreTelemetry_CarriesIDsAndNeverTheSecret(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestIgnoreTelemetryOnlyReportsNewBatchEntries(t *testing.T) { const existing = `{"PackageManager":"npm","PackageName":"existing","PackageVersion":"1.0.0"}` const added = `{"PackageManager":"npm","PackageName":"added","PackageVersion":"2.0.0"}` @@ -97,6 +100,7 @@ func TestIgnoreTelemetryOnlyReportsNewBatchEntries(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { const agentSessionID = "agent-session" t.Setenv("CX_AGENT_VERSION", "env-version") @@ -128,6 +132,7 @@ func TestIgnoreTelemetryWithOptionalFlags(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestIgnoreTelemetry_AttributedInvalidFinding(t *testing.T) { previous := utils.GetOptionalParam("agent") t.Cleanup(func() { _ = utils.SetOptionalParam("agent", previous) }) @@ -154,6 +159,7 @@ func TestIgnoreTelemetry_AttributedInvalidFinding(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestIgnoreSubType(t *testing.T) { for scanType, want := range map[string]string{ "oss": "ignorePackage", "sca": "ignorePackage", "containers": "ignoreImage", @@ -165,6 +171,7 @@ func TestIgnoreSubType(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestIgnoreTelemetry_PluginContextFallback(t *testing.T) { home := t.TempDir() t.Setenv("HOME", home) diff --git a/internal/commands/telemetry_test.go b/internal/commands/telemetry_test.go index e0848d46a..53840fdc9 100644 --- a/internal/commands/telemetry_test.go +++ b/internal/commands/telemetry_test.go @@ -1,121 +1,124 @@ -//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_AuthenticationWithoutAgentSkipsSend(t *testing.T) { - originalSessionID := viper.GetString(params.SessionIDConfigKey) - t.Cleanup(func() { viper.Set(params.SessionIDConfigKey, originalSessionID) }) - viper.Set(params.SessionIDConfigKey, "existing-session") - - for _, tc := range []struct { - name string - args []string - }{ - {name: "omitted"}, - {name: "blank", args: []string{"--agent", " "}}, - } { - t.Run(tc.name, func(t *testing.T) { - called := false - cmd := NewTelemetryCommand(mock.TelemetryMockWrapper{ - CustomSendAIDataToLog: func(_ *wrappers.DataForAITelemetry) error { - called = true - return nil - }, - }) - cmd.SetOut(io.Discard) - cmd.SetArgs(append([]string{"ai", "--type", "authentication", "--status", "success"}, tc.args...)) - - assert.NilError(t, cmd.Execute()) - assert.Assert(t, !called, "authentication telemetry should be skipped") - assert.Equal(t, viper.GetString(params.SessionIDConfigKey), "existing-session") - }) - } -} - -func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} - execCmdNilAssertion( - t, - "telemetry", "ai", "--ai-provider", "Cursor", "--problem-severity", "Critical", "--type", "click", "--sub-type", "ast-results.viewPackageDetails", "--agent", "Cursor", "--engine", "secrets") -} - -func TestTelemetryHelp(t *testing.T) { - execCmdNilAssertion(t, "help", "telemetry", "ai") -} +//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" +) + +//nolint:goconst // test fixtures repeat values on purpose +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) + }) + } +} + +//nolint:goconst // test fixtures repeat values on purpose +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", + }) +} + +//nolint:goconst // test fixtures repeat values on purpose +func TestRunTelemetryAI_AuthenticationWithoutAgentSkipsSend(t *testing.T) { + originalSessionID := viper.GetString(params.SessionIDConfigKey) + t.Cleanup(func() { viper.Set(params.SessionIDConfigKey, originalSessionID) }) + viper.Set(params.SessionIDConfigKey, "existing-session") + + for _, tc := range []struct { + name string + args []string + }{ + {name: "omitted"}, + {name: "blank", args: []string{"--agent", " "}}, + } { + t.Run(tc.name, func(t *testing.T) { + called := false + cmd := NewTelemetryCommand(mock.TelemetryMockWrapper{ + CustomSendAIDataToLog: func(_ *wrappers.DataForAITelemetry) error { + called = true + return nil + }, + }) + cmd.SetOut(io.Discard) + cmd.SetArgs(append([]string{"ai", "--type", "authentication", "--status", "success"}, tc.args...)) + + assert.NilError(t, cmd.Execute()) + assert.Assert(t, !called, "authentication telemetry should be skipped") + assert.Equal(t, viper.GetString(params.SessionIDConfigKey), "existing-session") + }) + } +} + +func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { + mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} + execCmdNilAssertion( + t, + "telemetry", "ai", "--ai-provider", "Cursor", "--problem-severity", "Critical", "--type", "click", "--sub-type", "ast-results.viewPackageDetails", "--agent", "Cursor", "--engine", "secrets") +} + +func TestTelemetryHelp(t *testing.T) { + execCmdNilAssertion(t, "help", "telemetry", "ai") +} diff --git a/internal/wrappers/api_key_realm_test.go b/internal/wrappers/api_key_realm_test.go index d62663dcf..ec85e3c41 100644 --- a/internal/wrappers/api_key_realm_test.go +++ b/internal/wrappers/api_key_realm_test.go @@ -31,7 +31,7 @@ func TestIsSecureRealmScheme(t *testing.T) { } func TestExchangeLoginAPIKey_RejectsPlainHTTPRealm(t *testing.T) { - apiKey := unsignedJWT(map[string]interface{}{"aud": "http://iam.example.com/auth/realms/organization"}) + apiKey := unsignedJWT(map[string]interface{}{audienceClaimKey: "http://iam.example.com/auth/realms/organization"}) token, err := ExchangeLoginAPIKey(apiKey) if err == nil || token != "" { t.Fatal("a non-loopback http realm must be rejected before any request is made") diff --git a/internal/wrappers/jwt-helper_test.go b/internal/wrappers/jwt-helper_test.go index 1cc4d1417..48664eb37 100644 --- a/internal/wrappers/jwt-helper_test.go +++ b/internal/wrappers/jwt-helper_test.go @@ -1,283 +1,284 @@ -package wrappers - -import ( - "strings" - "testing" - - commonParams "github.com/checkmarx/ast-cli/internal/params" - "github.com/spf13/viper" - "gotest.tools/assert" -) - -func TestGetDefaultEngines(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - expectedEngines map[string]bool - }{ - { - name: "using new sscs licensing", - scsLicensingV2: true, - expectedEngines: map[string]bool{ - "sast": true, - "sca": true, - "api-security": true, - "iac-security": true, - "containers": true, - "repository-health": true, - "secret-detection": true, - }, - }, - { - name: "using old sscs licensing", - scsLicensingV2: false, - expectedEngines: map[string]bool{ - "sast": true, - "sca": true, - "api-security": true, - "iac-security": true, - "containers": true, - "scs": true, - "enterprise-secrets": true, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualEngines := getDefaultEngines(tt.scsLicensingV2) - assert.Equal(t, tt.expectedEngines, actualEngines) - }) - } -} - -func TestGetEnabledEngines(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - expectedEngines []string - }{ - { - name: "using new sscs licensing", - scsLicensingV2: true, - expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "repository-health", "secret-detection"}, - }, - { - name: "using old sscs licensing", - scsLicensingV2: false, - expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "scs", "enterprise-secrets"}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualEngines := getDefaultEngines(tt.scsLicensingV2) - assert.Equal(t, tt.expectedEngines, actualEngines) - }) - } -} - -func TestGetUniqueID(t *testing.T) { - // Save original value and restore after test - originalID := viper.GetString(commonParams.UniqueIDConfigKey) - defer viper.Set(commonParams.UniqueIDConfigKey, originalID) - - t.Run("returns existing unique ID from config", func(t *testing.T) { - // Setup: set existing ID - existingID := "550e8400-e29b-41d4-a716-446655440000_testuser" - viper.Set(commonParams.UniqueIDConfigKey, existingID) - - result := GetUniqueID() - - if result != "" { - assert.Equal(t, existingID, result) - } else { - t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") - } - }) - - t.Run("generates new unique ID when none exists", func(t *testing.T) { - // Setup: clear existing ID - viper.Set(commonParams.UniqueIDConfigKey, "") - - result := GetUniqueID() - - if result == "" { - t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") - return - } - - // Verify format: UUID_username - assert.Assert(t, strings.Contains(result, "_"), "Should have UUID_username format") - assert.Assert(t, len(result) > 36, "Should contain UUID and username") - - // Verify no backslash (Windows domain stripped) - parts := strings.Split(result, "_") - assert.Assert(t, len(parts) >= 2, "Should have at least 2 parts") - assert.Assert(t, !strings.Contains(parts[1], "\\"), "Username should not contain backslash") - }) -} - -func TestIsValidUniqueIDFormat(t *testing.T) { - tests := []struct { - name string - uniqueID string - valid bool - }{ - { - name: "valid format with UUID and username", - uniqueID: "550e8400-e29b-41d4-a716-446655440000_testuser", - valid: true, - }, - { - name: "invalid - no underscore", - uniqueID: "550e8400-e29b-41d4-a716-446655440000testuser", - valid: false, - }, - { - name: "invalid - empty username", - uniqueID: "550e8400-e29b-41d4-a716-446655440000_", - valid: false, - }, - { - name: "invalid - malformed UUID", - uniqueID: "550e8400-e29b-41d4-invalid-446655440000_testuser", - valid: false, - }, - { - name: "valid - username containing underscore", - uniqueID: "550e8400-e29b-41d4-a716-446655440000_test_user", - valid: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := isValidUniqueIDFormat(tt.uniqueID) - assert.Equal(t, tt.valid, result, "validation result should match expected") - }) - } -} - -func TestGetSessionIDAlwaysGeneratesNewID(t *testing.T) { - // Save original value and restore after test - originalID := viper.GetString(commonParams.SessionIDConfigKey) - defer viper.Set(commonParams.SessionIDConfigKey, originalID) - - t.Run("generates new session ID when none exists", func(t *testing.T) { - viper.Set(commonParams.SessionIDConfigKey, "") - - result := GetSessionID() - - assert.Assert(t, result != "", "Should generate new session ID") - assert.Assert(t, len(result) == 36, "Should be valid UUID format (36 chars)") - assert.Assert(t, strings.Count(result, "-") == 4, "Should have 4 dashes in UUID") - }) - - t.Run("replaces existing valid session ID", func(t *testing.T) { - existingID := "550e8400-e29b-41d4-a716-446655440000" - viper.Set(commonParams.SessionIDConfigKey, existingID) - - result := GetSessionID() - - assert.Assert(t, result != existingID, "Should generate a new ID even when a valid one exists") - assert.Assert(t, len(result) == 36, "Should generate valid UUID format") - assert.Equal(t, result, viper.GetString(commonParams.SessionIDConfigKey), "Should store the new ID in config") - }) - - t.Run("replaces invalid session ID", func(t *testing.T) { - invalidID := "550e8400-e29b-41d4-invalid-446655440000" - viper.Set(commonParams.SessionIDConfigKey, invalidID) - - result := GetSessionID() - - assert.Assert(t, result != invalidID, "Should regenerate when ID is invalid") - assert.Assert(t, len(result) == 36, "Should generate valid UUID format") - }) -} - -func TestBuildLicenseDetailsFromJWT(t *testing.T) { - tests := []struct { - name string - allowedEngines []string - dastEnabled bool - expectedCxOneAssist string - expectedCxDevAssist string - expectedDast string - }{ - { - name: "all features enabled", - allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.CheckmarxDevAssistType}, - dastEnabled: true, - expectedCxOneAssist: "true", - expectedCxDevAssist: "true", - expectedDast: "true", - }, - { - name: "all features enabled - AIProtection", - allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.AIProtectionType}, - dastEnabled: true, - expectedCxOneAssist: "true", - expectedCxDevAssist: "false", - expectedDast: "true", - }, - { - name: "only dev assist enabled", - allowedEngines: []string{"sast", commonParams.CheckmarxDevAssistType}, - dastEnabled: false, - expectedCxOneAssist: "false", - expectedCxDevAssist: "true", - expectedDast: "false", - }, - { - name: "no assist features enabled", - allowedEngines: []string{"sast", "sca", "iac-security"}, - dastEnabled: false, - expectedCxOneAssist: "false", - expectedCxDevAssist: "false", - expectedDast: "false", - }, - { - name: "only dast enabled", - allowedEngines: []string{"sast"}, - dastEnabled: true, - expectedCxOneAssist: "false", - expectedCxDevAssist: "false", - expectedDast: "true", - }, - { - name: "case insensitive matching", - allowedEngines: []string{"checkmarx one assist", "checkmarx developer assist"}, - dastEnabled: false, - expectedCxOneAssist: "true", - expectedCxDevAssist: "true", - expectedDast: "false", - }, - { - name: "empty allowed engines", - allowedEngines: []string{}, - dastEnabled: false, - expectedCxOneAssist: "false", - expectedCxDevAssist: "false", - expectedDast: "false", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Create a JWT struct with test data - jwtStruct := &JWTStruct{} - jwtStruct.AstLicense.LicenseData.AllowedEngines = tt.allowedEngines - jwtStruct.AstLicense.LicenseData.DastEnabled = tt.dastEnabled - - // Call the function under test - licenseDetails := buildLicenseDetailsFromJWT(jwtStruct) - - // Assert the results - assert.Equal(t, tt.expectedCxOneAssist, licenseDetails[commonParams.CxOneAssistEnabledKey], - "CxOneAssist should be %s", tt.expectedCxOneAssist) - assert.Equal(t, tt.expectedCxDevAssist, licenseDetails[commonParams.CxDevAssistEnabledKey], - "CxDevAssist should be %s", tt.expectedCxDevAssist) - assert.Equal(t, tt.expectedDast, licenseDetails[commonParams.DastEnabledKey], - "Dast should be %s", tt.expectedDast) - }) - } -} +package wrappers + +import ( + "strings" + "testing" + + commonParams "github.com/checkmarx/ast-cli/internal/params" + "github.com/spf13/viper" + "gotest.tools/assert" +) + +func TestGetDefaultEngines(t *testing.T) { + tests := []struct { + name string + scsLicensingV2 bool + expectedEngines map[string]bool + }{ + { + name: "using new sscs licensing", + scsLicensingV2: true, + expectedEngines: map[string]bool{ + "sast": true, + "sca": true, + "api-security": true, + "iac-security": true, + "containers": true, + "repository-health": true, + "secret-detection": true, + }, + }, + { + name: "using old sscs licensing", + scsLicensingV2: false, + expectedEngines: map[string]bool{ + "sast": true, + "sca": true, + "api-security": true, + "iac-security": true, + "containers": true, + "scs": true, + "enterprise-secrets": true, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actualEngines := getDefaultEngines(tt.scsLicensingV2) + assert.Equal(t, tt.expectedEngines, actualEngines) + }) + } +} + +func TestGetEnabledEngines(t *testing.T) { + tests := []struct { + name string + scsLicensingV2 bool + expectedEngines []string + }{ + { + name: "using new sscs licensing", + scsLicensingV2: true, + expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "repository-health", "secret-detection"}, + }, + { + name: "using old sscs licensing", + scsLicensingV2: false, + expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "scs", "enterprise-secrets"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actualEngines := getDefaultEngines(tt.scsLicensingV2) + assert.Equal(t, tt.expectedEngines, actualEngines) + }) + } +} + +//nolint:goconst // test fixtures repeat values on purpose +func TestGetUniqueID(t *testing.T) { + // Save original value and restore after test + originalID := viper.GetString(commonParams.UniqueIDConfigKey) + defer viper.Set(commonParams.UniqueIDConfigKey, originalID) + + t.Run("returns existing unique ID from config", func(t *testing.T) { + // Setup: set existing ID + existingID := "550e8400-e29b-41d4-a716-446655440000_testuser" + viper.Set(commonParams.UniqueIDConfigKey, existingID) + + result := GetUniqueID() + + if result != "" { + assert.Equal(t, existingID, result) + } else { + t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") + } + }) + + t.Run("generates new unique ID when none exists", func(t *testing.T) { + // Setup: clear existing ID + viper.Set(commonParams.UniqueIDConfigKey, "") + + result := GetUniqueID() + + if result == "" { + t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") + return + } + + // Verify format: UUID_username + assert.Assert(t, strings.Contains(result, "_"), "Should have UUID_username format") + assert.Assert(t, len(result) > 36, "Should contain UUID and username") + + // Verify no backslash (Windows domain stripped) + parts := strings.Split(result, "_") + assert.Assert(t, len(parts) >= 2, "Should have at least 2 parts") + assert.Assert(t, !strings.Contains(parts[1], "\\"), "Username should not contain backslash") + }) +} + +func TestIsValidUniqueIDFormat(t *testing.T) { + tests := []struct { + name string + uniqueID string + valid bool + }{ + { + name: "valid format with UUID and username", + uniqueID: "550e8400-e29b-41d4-a716-446655440000_testuser", + valid: true, + }, + { + name: "invalid - no underscore", + uniqueID: "550e8400-e29b-41d4-a716-446655440000testuser", + valid: false, + }, + { + name: "invalid - empty username", + uniqueID: "550e8400-e29b-41d4-a716-446655440000_", + valid: false, + }, + { + name: "invalid - malformed UUID", + uniqueID: "550e8400-e29b-41d4-invalid-446655440000_testuser", + valid: false, + }, + { + name: "valid - username containing underscore", + uniqueID: "550e8400-e29b-41d4-a716-446655440000_test_user", + valid: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := isValidUniqueIDFormat(tt.uniqueID) + assert.Equal(t, tt.valid, result, "validation result should match expected") + }) + } +} + +func TestGetSessionIDAlwaysGeneratesNewID(t *testing.T) { + // Save original value and restore after test + originalID := viper.GetString(commonParams.SessionIDConfigKey) + defer viper.Set(commonParams.SessionIDConfigKey, originalID) + + t.Run("generates new session ID when none exists", func(t *testing.T) { + viper.Set(commonParams.SessionIDConfigKey, "") + + result := GetSessionID() + + assert.Assert(t, result != "", "Should generate new session ID") + assert.Assert(t, len(result) == 36, "Should be valid UUID format (36 chars)") + assert.Assert(t, strings.Count(result, "-") == 4, "Should have 4 dashes in UUID") + }) + + t.Run("replaces existing valid session ID", func(t *testing.T) { + existingID := "550e8400-e29b-41d4-a716-446655440000" + viper.Set(commonParams.SessionIDConfigKey, existingID) + + result := GetSessionID() + + assert.Assert(t, result != existingID, "Should generate a new ID even when a valid one exists") + assert.Assert(t, len(result) == 36, "Should generate valid UUID format") + assert.Equal(t, result, viper.GetString(commonParams.SessionIDConfigKey), "Should store the new ID in config") + }) + + t.Run("replaces invalid session ID", func(t *testing.T) { + invalidID := "550e8400-e29b-41d4-invalid-446655440000" + viper.Set(commonParams.SessionIDConfigKey, invalidID) + + result := GetSessionID() + + assert.Assert(t, result != invalidID, "Should regenerate when ID is invalid") + assert.Assert(t, len(result) == 36, "Should generate valid UUID format") + }) +} + +func TestBuildLicenseDetailsFromJWT(t *testing.T) { + tests := []struct { + name string + allowedEngines []string + dastEnabled bool + expectedCxOneAssist string + expectedCxDevAssist string + expectedDast string + }{ + { + name: "all features enabled", + allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.CheckmarxDevAssistType}, + dastEnabled: true, + expectedCxOneAssist: "true", + expectedCxDevAssist: "true", + expectedDast: "true", + }, + { + name: "all features enabled - AIProtection", + allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.AIProtectionType}, + dastEnabled: true, + expectedCxOneAssist: "true", + expectedCxDevAssist: "false", + expectedDast: "true", + }, + { + name: "only dev assist enabled", + allowedEngines: []string{"sast", commonParams.CheckmarxDevAssistType}, + dastEnabled: false, + expectedCxOneAssist: "false", + expectedCxDevAssist: "true", + expectedDast: "false", + }, + { + name: "no assist features enabled", + allowedEngines: []string{"sast", "sca", "iac-security"}, + dastEnabled: false, + expectedCxOneAssist: "false", + expectedCxDevAssist: "false", + expectedDast: "false", + }, + { + name: "only dast enabled", + allowedEngines: []string{"sast"}, + dastEnabled: true, + expectedCxOneAssist: "false", + expectedCxDevAssist: "false", + expectedDast: "true", + }, + { + name: "case insensitive matching", + allowedEngines: []string{"checkmarx one assist", "checkmarx developer assist"}, + dastEnabled: false, + expectedCxOneAssist: "true", + expectedCxDevAssist: "true", + expectedDast: "false", + }, + { + name: "empty allowed engines", + allowedEngines: []string{}, + dastEnabled: false, + expectedCxOneAssist: "false", + expectedCxDevAssist: "false", + expectedDast: "false", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Create a JWT struct with test data + jwtStruct := &JWTStruct{} + jwtStruct.AstLicense.LicenseData.AllowedEngines = tt.allowedEngines + jwtStruct.AstLicense.LicenseData.DastEnabled = tt.dastEnabled + + // Call the function under test + licenseDetails := buildLicenseDetailsFromJWT(jwtStruct) + + // Assert the results + assert.Equal(t, tt.expectedCxOneAssist, licenseDetails[commonParams.CxOneAssistEnabledKey], + "CxOneAssist should be %s", tt.expectedCxOneAssist) + assert.Equal(t, tt.expectedCxDevAssist, licenseDetails[commonParams.CxDevAssistEnabledKey], + "CxDevAssist should be %s", tt.expectedCxDevAssist) + assert.Equal(t, tt.expectedDast, licenseDetails[commonParams.DastEnabledKey], + "Dast should be %s", tt.expectedDast) + }) + } +} From 730111f0b3a043c7d0a59fc1eafd0419e9e66b70 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:27:48 +0530 Subject: [PATCH 17/19] AST-195928 Remove the empty config.yaml a test run left behind Co-Authored-By: Claude Sonnet 5.5 --- internal/commands/config.yaml | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 internal/commands/config.yaml diff --git a/internal/commands/config.yaml b/internal/commands/config.yaml deleted file mode 100644 index e69de29bb..000000000 From 84dcfcfc8e7eabbdcc69f9ca3394866c60f58931 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Wed, 2 Dec 2026 13:55:19 +0530 Subject: [PATCH 18/19] AST-195928 Fix the remaining lint findings and restore LF line endings Name the auth methods, agent labels, ignore subTypes and the two failure reasons that goconst flagged in production code, and mark the new login metadata test helper like the other fixture helpers. The previous lint commit also turned telemetry_test.go and jwt-helper_test.go into CRLF files; put them back to LF so they diff against staging by their real changes only. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> --- internal/commands/agenthooks/cx/hooks.go | 7 +- internal/commands/auth_login.go | 26 +- internal/commands/auth_login_test.go | 1 + internal/commands/ignore_vulnerability.go | 16 +- internal/commands/telemetry_test.go | 248 +++++----- internal/wrappers/jwt-helper_test.go | 568 +++++++++++----------- 6 files changed, 445 insertions(+), 421 deletions(-) diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index 9e44267a1..672b82af7 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -33,6 +33,9 @@ const ( engineSecrets = "Secrets" ) +// remediationInstructionsMissing is the reason a remediation event reports when the hook had no guidance to give. +const remediationInstructionsMissing = "remediation_instructions_missing" + // scaScanner is the package-level SCA scanner used by the guardrail handlers. // It is set by RegisterGuardrails so the handlers (free functions registered // with the agenthooks library) can reach it without an injection mechanism. @@ -347,9 +350,9 @@ func logRemediationTelemetry(agent, engine, severity, sessionID, workDir, guidan } if strings.TrimSpace(guidance) == "" { telemetryData.Status = hooktelemetry.StatusFailure - telemetryData.StatusResult = hooktelemetry.FailureResult("Remediation", "remediation_instructions_missing", hooktelemetry.ErrorCodeNone) + telemetryData.StatusResult = hooktelemetry.FailureResult("Remediation", remediationInstructionsMissing, hooktelemetry.ErrorCodeNone) telemetryData.TotalCount = 0 - attrs["reasonCode"] = "remediation_instructions_missing" + attrs["reasonCode"] = remediationInstructionsMissing } hooktelemetry.Enrich(telemetryData, workDir) diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index 4688afb42..32e75ea94 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -72,7 +72,7 @@ func newAuthLoginCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Comm } func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper) (resultErr error) { - method, failureReason := "OAuth", "browser_authentication_failed" + method, failureReason := authMethodOAuth, "browser_authentication_failed" defer func() { if resultErr == nil { return @@ -88,7 +88,7 @@ func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper } }() if cmd.Flags().Changed(params.AstAPIKeyFlag) { - method, failureReason = "APIKey", "api_key_authentication_failed" + method, failureReason = authMethodAPIKey, "api_key_authentication_failed" apiKey, err := cmd.Flags().GetString(params.AstAPIKeyFlag) if err != nil || strings.TrimSpace(apiKey) == "" { return errors.New("--apikey requires a nonempty API key") @@ -141,20 +141,32 @@ func loginTelemetryAgent(cmd *cobra.Command) string { agent, _ := cmd.Flags().GetString(params.AgentFlag) switch strings.ToLower(strings.TrimSpace(agent)) { case "copilot-cli": - return "Copilot-CLI" + return agentCopilotCLI case "claude-cli": - return "Claude-CLI" + return agentClaudeCLI case "cursor-cli": - return "Cursor-CLI" + return agentCursorCLI case "gemini-cli": - return "Gemini-CLI" + return agentGeminiCLI case "codex-cli": - return "Codex-CLI" + return agentCodexCLI default: return "" } } +// The authMethod values and the telemetry agent labels a CLI login reports. +const ( + authMethodOAuth = "OAuth" + authMethodAPIKey = "APIKey" + + agentCopilotCLI = "Copilot-CLI" + agentClaudeCLI = "Claude-CLI" + agentCursorCLI = "Cursor-CLI" + agentGeminiCLI = "Gemini-CLI" + agentCodexCLI = "Codex-CLI" +) + const loginCredentialSaveFailed = "credential_save_failed" func completeAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper, credential, accessToken, authMethod string) error { diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index 330474f75..dad55ada4 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -333,6 +333,7 @@ func assertAuthenticationSuccessEvent(t *testing.T, data *wrappers.DataForAITele } } +//nolint:goconst // test fixtures repeat values on purpose func assertLoginMetadata(t *testing.T, data *wrappers.DataForAITelemetry) { t.Helper() if data.AgentVersion != "1.2.3" || data.CxPluginVersion != "4.5.6" || diff --git a/internal/commands/ignore_vulnerability.go b/internal/commands/ignore_vulnerability.go index bdca54c3d..7d74a4e5a 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -67,7 +67,7 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd return errors.Errorf("invalid --scan-type %q; expected one of: oss, sca, secrets, containers, iac, asca", scanType) } - failureReason := "invalid_ignore_input" + failureReason := invalidIgnoreInputReason defer func() { if resultErr != nil && !remove && utils.GetOptionalParam("agent") != "" { sendIgnoreTelemetry(telemetryWrapper, scanType, nil, failureReason) @@ -265,16 +265,24 @@ func ignoreEntryID(entry any) string { // containersEngine is the telemetry engine label for container images. const containersEngine = "Containers" +// The hooks-ignore subTypes, and the reason an ignore with unusable input is reported with. +const ( + ignorePackageSubType = "ignorePackage" + ignoreImageSubType = "ignoreImage" + ignoreFindingSubType = "ignoreFinding" + invalidIgnoreInputReason = "invalid_ignore_input" +) + // ignoreSubType is the hooks-ignore subType for an engine label: packages and images are ignored by // coordinates, every other engine by finding. func ignoreSubType(engine string) string { switch engine { case hooktelemetry.EngineOSS: - return "ignorePackage" + return ignorePackageSubType case containersEngine: - return "ignoreImage" + return ignoreImageSubType default: - return "ignoreFinding" + return ignoreFindingSubType } } diff --git a/internal/commands/telemetry_test.go b/internal/commands/telemetry_test.go index 53840fdc9..e370d35b6 100644 --- a/internal/commands/telemetry_test.go +++ b/internal/commands/telemetry_test.go @@ -1,124 +1,124 @@ -//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" -) - -//nolint:goconst // test fixtures repeat values on purpose -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) - }) - } -} - -//nolint:goconst // test fixtures repeat values on purpose -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", - }) -} - -//nolint:goconst // test fixtures repeat values on purpose -func TestRunTelemetryAI_AuthenticationWithoutAgentSkipsSend(t *testing.T) { - originalSessionID := viper.GetString(params.SessionIDConfigKey) - t.Cleanup(func() { viper.Set(params.SessionIDConfigKey, originalSessionID) }) - viper.Set(params.SessionIDConfigKey, "existing-session") - - for _, tc := range []struct { - name string - args []string - }{ - {name: "omitted"}, - {name: "blank", args: []string{"--agent", " "}}, - } { - t.Run(tc.name, func(t *testing.T) { - called := false - cmd := NewTelemetryCommand(mock.TelemetryMockWrapper{ - CustomSendAIDataToLog: func(_ *wrappers.DataForAITelemetry) error { - called = true - return nil - }, - }) - cmd.SetOut(io.Discard) - cmd.SetArgs(append([]string{"ai", "--type", "authentication", "--status", "success"}, tc.args...)) - - assert.NilError(t, cmd.Execute()) - assert.Assert(t, !called, "authentication telemetry should be skipped") - assert.Equal(t, viper.GetString(params.SessionIDConfigKey), "existing-session") - }) - } -} - -func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} - execCmdNilAssertion( - t, - "telemetry", "ai", "--ai-provider", "Cursor", "--problem-severity", "Critical", "--type", "click", "--sub-type", "ast-results.viewPackageDetails", "--agent", "Cursor", "--engine", "secrets") -} - -func TestTelemetryHelp(t *testing.T) { - execCmdNilAssertion(t, "help", "telemetry", "ai") -} +//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" +) + +//nolint:goconst // test fixtures repeat values on purpose +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) + }) + } +} + +//nolint:goconst // test fixtures repeat values on purpose +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", + }) +} + +//nolint:goconst // test fixtures repeat values on purpose +func TestRunTelemetryAI_AuthenticationWithoutAgentSkipsSend(t *testing.T) { + originalSessionID := viper.GetString(params.SessionIDConfigKey) + t.Cleanup(func() { viper.Set(params.SessionIDConfigKey, originalSessionID) }) + viper.Set(params.SessionIDConfigKey, "existing-session") + + for _, tc := range []struct { + name string + args []string + }{ + {name: "omitted"}, + {name: "blank", args: []string{"--agent", " "}}, + } { + t.Run(tc.name, func(t *testing.T) { + called := false + cmd := NewTelemetryCommand(mock.TelemetryMockWrapper{ + CustomSendAIDataToLog: func(_ *wrappers.DataForAITelemetry) error { + called = true + return nil + }, + }) + cmd.SetOut(io.Discard) + cmd.SetArgs(append([]string{"ai", "--type", "authentication", "--status", "success"}, tc.args...)) + + assert.NilError(t, cmd.Execute()) + assert.Assert(t, !called, "authentication telemetry should be skipped") + assert.Equal(t, viper.GetString(params.SessionIDConfigKey), "existing-session") + }) + } +} + +func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { + mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} + execCmdNilAssertion( + t, + "telemetry", "ai", "--ai-provider", "Cursor", "--problem-severity", "Critical", "--type", "click", "--sub-type", "ast-results.viewPackageDetails", "--agent", "Cursor", "--engine", "secrets") +} + +func TestTelemetryHelp(t *testing.T) { + execCmdNilAssertion(t, "help", "telemetry", "ai") +} diff --git a/internal/wrappers/jwt-helper_test.go b/internal/wrappers/jwt-helper_test.go index 48664eb37..310d2795c 100644 --- a/internal/wrappers/jwt-helper_test.go +++ b/internal/wrappers/jwt-helper_test.go @@ -1,284 +1,284 @@ -package wrappers - -import ( - "strings" - "testing" - - commonParams "github.com/checkmarx/ast-cli/internal/params" - "github.com/spf13/viper" - "gotest.tools/assert" -) - -func TestGetDefaultEngines(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - expectedEngines map[string]bool - }{ - { - name: "using new sscs licensing", - scsLicensingV2: true, - expectedEngines: map[string]bool{ - "sast": true, - "sca": true, - "api-security": true, - "iac-security": true, - "containers": true, - "repository-health": true, - "secret-detection": true, - }, - }, - { - name: "using old sscs licensing", - scsLicensingV2: false, - expectedEngines: map[string]bool{ - "sast": true, - "sca": true, - "api-security": true, - "iac-security": true, - "containers": true, - "scs": true, - "enterprise-secrets": true, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualEngines := getDefaultEngines(tt.scsLicensingV2) - assert.Equal(t, tt.expectedEngines, actualEngines) - }) - } -} - -func TestGetEnabledEngines(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - expectedEngines []string - }{ - { - name: "using new sscs licensing", - scsLicensingV2: true, - expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "repository-health", "secret-detection"}, - }, - { - name: "using old sscs licensing", - scsLicensingV2: false, - expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "scs", "enterprise-secrets"}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualEngines := getDefaultEngines(tt.scsLicensingV2) - assert.Equal(t, tt.expectedEngines, actualEngines) - }) - } -} - -//nolint:goconst // test fixtures repeat values on purpose -func TestGetUniqueID(t *testing.T) { - // Save original value and restore after test - originalID := viper.GetString(commonParams.UniqueIDConfigKey) - defer viper.Set(commonParams.UniqueIDConfigKey, originalID) - - t.Run("returns existing unique ID from config", func(t *testing.T) { - // Setup: set existing ID - existingID := "550e8400-e29b-41d4-a716-446655440000_testuser" - viper.Set(commonParams.UniqueIDConfigKey, existingID) - - result := GetUniqueID() - - if result != "" { - assert.Equal(t, existingID, result) - } else { - t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") - } - }) - - t.Run("generates new unique ID when none exists", func(t *testing.T) { - // Setup: clear existing ID - viper.Set(commonParams.UniqueIDConfigKey, "") - - result := GetUniqueID() - - if result == "" { - t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") - return - } - - // Verify format: UUID_username - assert.Assert(t, strings.Contains(result, "_"), "Should have UUID_username format") - assert.Assert(t, len(result) > 36, "Should contain UUID and username") - - // Verify no backslash (Windows domain stripped) - parts := strings.Split(result, "_") - assert.Assert(t, len(parts) >= 2, "Should have at least 2 parts") - assert.Assert(t, !strings.Contains(parts[1], "\\"), "Username should not contain backslash") - }) -} - -func TestIsValidUniqueIDFormat(t *testing.T) { - tests := []struct { - name string - uniqueID string - valid bool - }{ - { - name: "valid format with UUID and username", - uniqueID: "550e8400-e29b-41d4-a716-446655440000_testuser", - valid: true, - }, - { - name: "invalid - no underscore", - uniqueID: "550e8400-e29b-41d4-a716-446655440000testuser", - valid: false, - }, - { - name: "invalid - empty username", - uniqueID: "550e8400-e29b-41d4-a716-446655440000_", - valid: false, - }, - { - name: "invalid - malformed UUID", - uniqueID: "550e8400-e29b-41d4-invalid-446655440000_testuser", - valid: false, - }, - { - name: "valid - username containing underscore", - uniqueID: "550e8400-e29b-41d4-a716-446655440000_test_user", - valid: true, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := isValidUniqueIDFormat(tt.uniqueID) - assert.Equal(t, tt.valid, result, "validation result should match expected") - }) - } -} - -func TestGetSessionIDAlwaysGeneratesNewID(t *testing.T) { - // Save original value and restore after test - originalID := viper.GetString(commonParams.SessionIDConfigKey) - defer viper.Set(commonParams.SessionIDConfigKey, originalID) - - t.Run("generates new session ID when none exists", func(t *testing.T) { - viper.Set(commonParams.SessionIDConfigKey, "") - - result := GetSessionID() - - assert.Assert(t, result != "", "Should generate new session ID") - assert.Assert(t, len(result) == 36, "Should be valid UUID format (36 chars)") - assert.Assert(t, strings.Count(result, "-") == 4, "Should have 4 dashes in UUID") - }) - - t.Run("replaces existing valid session ID", func(t *testing.T) { - existingID := "550e8400-e29b-41d4-a716-446655440000" - viper.Set(commonParams.SessionIDConfigKey, existingID) - - result := GetSessionID() - - assert.Assert(t, result != existingID, "Should generate a new ID even when a valid one exists") - assert.Assert(t, len(result) == 36, "Should generate valid UUID format") - assert.Equal(t, result, viper.GetString(commonParams.SessionIDConfigKey), "Should store the new ID in config") - }) - - t.Run("replaces invalid session ID", func(t *testing.T) { - invalidID := "550e8400-e29b-41d4-invalid-446655440000" - viper.Set(commonParams.SessionIDConfigKey, invalidID) - - result := GetSessionID() - - assert.Assert(t, result != invalidID, "Should regenerate when ID is invalid") - assert.Assert(t, len(result) == 36, "Should generate valid UUID format") - }) -} - -func TestBuildLicenseDetailsFromJWT(t *testing.T) { - tests := []struct { - name string - allowedEngines []string - dastEnabled bool - expectedCxOneAssist string - expectedCxDevAssist string - expectedDast string - }{ - { - name: "all features enabled", - allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.CheckmarxDevAssistType}, - dastEnabled: true, - expectedCxOneAssist: "true", - expectedCxDevAssist: "true", - expectedDast: "true", - }, - { - name: "all features enabled - AIProtection", - allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.AIProtectionType}, - dastEnabled: true, - expectedCxOneAssist: "true", - expectedCxDevAssist: "false", - expectedDast: "true", - }, - { - name: "only dev assist enabled", - allowedEngines: []string{"sast", commonParams.CheckmarxDevAssistType}, - dastEnabled: false, - expectedCxOneAssist: "false", - expectedCxDevAssist: "true", - expectedDast: "false", - }, - { - name: "no assist features enabled", - allowedEngines: []string{"sast", "sca", "iac-security"}, - dastEnabled: false, - expectedCxOneAssist: "false", - expectedCxDevAssist: "false", - expectedDast: "false", - }, - { - name: "only dast enabled", - allowedEngines: []string{"sast"}, - dastEnabled: true, - expectedCxOneAssist: "false", - expectedCxDevAssist: "false", - expectedDast: "true", - }, - { - name: "case insensitive matching", - allowedEngines: []string{"checkmarx one assist", "checkmarx developer assist"}, - dastEnabled: false, - expectedCxOneAssist: "true", - expectedCxDevAssist: "true", - expectedDast: "false", - }, - { - name: "empty allowed engines", - allowedEngines: []string{}, - dastEnabled: false, - expectedCxOneAssist: "false", - expectedCxDevAssist: "false", - expectedDast: "false", - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - // Create a JWT struct with test data - jwtStruct := &JWTStruct{} - jwtStruct.AstLicense.LicenseData.AllowedEngines = tt.allowedEngines - jwtStruct.AstLicense.LicenseData.DastEnabled = tt.dastEnabled - - // Call the function under test - licenseDetails := buildLicenseDetailsFromJWT(jwtStruct) - - // Assert the results - assert.Equal(t, tt.expectedCxOneAssist, licenseDetails[commonParams.CxOneAssistEnabledKey], - "CxOneAssist should be %s", tt.expectedCxOneAssist) - assert.Equal(t, tt.expectedCxDevAssist, licenseDetails[commonParams.CxDevAssistEnabledKey], - "CxDevAssist should be %s", tt.expectedCxDevAssist) - assert.Equal(t, tt.expectedDast, licenseDetails[commonParams.DastEnabledKey], - "Dast should be %s", tt.expectedDast) - }) - } -} +package wrappers + +import ( + "strings" + "testing" + + commonParams "github.com/checkmarx/ast-cli/internal/params" + "github.com/spf13/viper" + "gotest.tools/assert" +) + +func TestGetDefaultEngines(t *testing.T) { + tests := []struct { + name string + scsLicensingV2 bool + expectedEngines map[string]bool + }{ + { + name: "using new sscs licensing", + scsLicensingV2: true, + expectedEngines: map[string]bool{ + "sast": true, + "sca": true, + "api-security": true, + "iac-security": true, + "containers": true, + "repository-health": true, + "secret-detection": true, + }, + }, + { + name: "using old sscs licensing", + scsLicensingV2: false, + expectedEngines: map[string]bool{ + "sast": true, + "sca": true, + "api-security": true, + "iac-security": true, + "containers": true, + "scs": true, + "enterprise-secrets": true, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actualEngines := getDefaultEngines(tt.scsLicensingV2) + assert.Equal(t, tt.expectedEngines, actualEngines) + }) + } +} + +func TestGetEnabledEngines(t *testing.T) { + tests := []struct { + name string + scsLicensingV2 bool + expectedEngines []string + }{ + { + name: "using new sscs licensing", + scsLicensingV2: true, + expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "repository-health", "secret-detection"}, + }, + { + name: "using old sscs licensing", + scsLicensingV2: false, + expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "scs", "enterprise-secrets"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + actualEngines := getDefaultEngines(tt.scsLicensingV2) + assert.Equal(t, tt.expectedEngines, actualEngines) + }) + } +} + +//nolint:goconst // test fixtures repeat values on purpose +func TestGetUniqueID(t *testing.T) { + // Save original value and restore after test + originalID := viper.GetString(commonParams.UniqueIDConfigKey) + defer viper.Set(commonParams.UniqueIDConfigKey, originalID) + + t.Run("returns existing unique ID from config", func(t *testing.T) { + // Setup: set existing ID + existingID := "550e8400-e29b-41d4-a716-446655440000_testuser" + viper.Set(commonParams.UniqueIDConfigKey, existingID) + + result := GetUniqueID() + + if result != "" { + assert.Equal(t, existingID, result) + } else { + t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") + } + }) + + t.Run("generates new unique ID when none exists", func(t *testing.T) { + // Setup: clear existing ID + viper.Set(commonParams.UniqueIDConfigKey, "") + + result := GetUniqueID() + + if result == "" { + t.Skip("Requires valid auth and 'Checkmarx Developer Assist' or 'Checkmarx OneAssist' license") + return + } + + // Verify format: UUID_username + assert.Assert(t, strings.Contains(result, "_"), "Should have UUID_username format") + assert.Assert(t, len(result) > 36, "Should contain UUID and username") + + // Verify no backslash (Windows domain stripped) + parts := strings.Split(result, "_") + assert.Assert(t, len(parts) >= 2, "Should have at least 2 parts") + assert.Assert(t, !strings.Contains(parts[1], "\\"), "Username should not contain backslash") + }) +} + +func TestIsValidUniqueIDFormat(t *testing.T) { + tests := []struct { + name string + uniqueID string + valid bool + }{ + { + name: "valid format with UUID and username", + uniqueID: "550e8400-e29b-41d4-a716-446655440000_testuser", + valid: true, + }, + { + name: "invalid - no underscore", + uniqueID: "550e8400-e29b-41d4-a716-446655440000testuser", + valid: false, + }, + { + name: "invalid - empty username", + uniqueID: "550e8400-e29b-41d4-a716-446655440000_", + valid: false, + }, + { + name: "invalid - malformed UUID", + uniqueID: "550e8400-e29b-41d4-invalid-446655440000_testuser", + valid: false, + }, + { + name: "valid - username containing underscore", + uniqueID: "550e8400-e29b-41d4-a716-446655440000_test_user", + valid: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + result := isValidUniqueIDFormat(tt.uniqueID) + assert.Equal(t, tt.valid, result, "validation result should match expected") + }) + } +} + +func TestGetSessionIDAlwaysGeneratesNewID(t *testing.T) { + // Save original value and restore after test + originalID := viper.GetString(commonParams.SessionIDConfigKey) + defer viper.Set(commonParams.SessionIDConfigKey, originalID) + + t.Run("generates new session ID when none exists", func(t *testing.T) { + viper.Set(commonParams.SessionIDConfigKey, "") + + result := GetSessionID() + + assert.Assert(t, result != "", "Should generate new session ID") + assert.Assert(t, len(result) == 36, "Should be valid UUID format (36 chars)") + assert.Assert(t, strings.Count(result, "-") == 4, "Should have 4 dashes in UUID") + }) + + t.Run("replaces existing valid session ID", func(t *testing.T) { + existingID := "550e8400-e29b-41d4-a716-446655440000" + viper.Set(commonParams.SessionIDConfigKey, existingID) + + result := GetSessionID() + + assert.Assert(t, result != existingID, "Should generate a new ID even when a valid one exists") + assert.Assert(t, len(result) == 36, "Should generate valid UUID format") + assert.Equal(t, result, viper.GetString(commonParams.SessionIDConfigKey), "Should store the new ID in config") + }) + + t.Run("replaces invalid session ID", func(t *testing.T) { + invalidID := "550e8400-e29b-41d4-invalid-446655440000" + viper.Set(commonParams.SessionIDConfigKey, invalidID) + + result := GetSessionID() + + assert.Assert(t, result != invalidID, "Should regenerate when ID is invalid") + assert.Assert(t, len(result) == 36, "Should generate valid UUID format") + }) +} + +func TestBuildLicenseDetailsFromJWT(t *testing.T) { + tests := []struct { + name string + allowedEngines []string + dastEnabled bool + expectedCxOneAssist string + expectedCxDevAssist string + expectedDast string + }{ + { + name: "all features enabled", + allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.CheckmarxDevAssistType}, + dastEnabled: true, + expectedCxOneAssist: "true", + expectedCxDevAssist: "true", + expectedDast: "true", + }, + { + name: "all features enabled - AIProtection", + allowedEngines: []string{"sast", "sca", commonParams.CheckmarxOneAssistType, commonParams.AIProtectionType}, + dastEnabled: true, + expectedCxOneAssist: "true", + expectedCxDevAssist: "false", + expectedDast: "true", + }, + { + name: "only dev assist enabled", + allowedEngines: []string{"sast", commonParams.CheckmarxDevAssistType}, + dastEnabled: false, + expectedCxOneAssist: "false", + expectedCxDevAssist: "true", + expectedDast: "false", + }, + { + name: "no assist features enabled", + allowedEngines: []string{"sast", "sca", "iac-security"}, + dastEnabled: false, + expectedCxOneAssist: "false", + expectedCxDevAssist: "false", + expectedDast: "false", + }, + { + name: "only dast enabled", + allowedEngines: []string{"sast"}, + dastEnabled: true, + expectedCxOneAssist: "false", + expectedCxDevAssist: "false", + expectedDast: "true", + }, + { + name: "case insensitive matching", + allowedEngines: []string{"checkmarx one assist", "checkmarx developer assist"}, + dastEnabled: false, + expectedCxOneAssist: "true", + expectedCxDevAssist: "true", + expectedDast: "false", + }, + { + name: "empty allowed engines", + allowedEngines: []string{}, + dastEnabled: false, + expectedCxOneAssist: "false", + expectedCxDevAssist: "false", + expectedDast: "false", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Create a JWT struct with test data + jwtStruct := &JWTStruct{} + jwtStruct.AstLicense.LicenseData.AllowedEngines = tt.allowedEngines + jwtStruct.AstLicense.LicenseData.DastEnabled = tt.dastEnabled + + // Call the function under test + licenseDetails := buildLicenseDetailsFromJWT(jwtStruct) + + // Assert the results + assert.Equal(t, tt.expectedCxOneAssist, licenseDetails[commonParams.CxOneAssistEnabledKey], + "CxOneAssist should be %s", tt.expectedCxOneAssist) + assert.Equal(t, tt.expectedCxDevAssist, licenseDetails[commonParams.CxDevAssistEnabledKey], + "CxDevAssist should be %s", tt.expectedCxDevAssist) + assert.Equal(t, tt.expectedDast, licenseDetails[commonParams.DastEnabledKey], + "Dast should be %s", tt.expectedDast) + }) + } +} From 20c23d561a43764cd773b158be20193d31e72815 Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Wed, 2 Dec 2026 14:20:13 +0530 Subject: [PATCH 19/19] AST-195928 Name the authentication failure reasons goconst flagged api_key_authentication_failed once the auth method became a constant. Name it and browser_authentication_failed, and use the constant in the two test assertions that repeated it. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> --- internal/commands/auth_login.go | 7 +++++-- internal/commands/auth_login_test.go | 4 ++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/internal/commands/auth_login.go b/internal/commands/auth_login.go index 32e75ea94..19352c9b3 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -72,7 +72,7 @@ func newAuthLoginCommand(telemetryWrapper wrappers.TelemetryWrapper) *cobra.Comm } func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper) (resultErr error) { - method, failureReason := authMethodOAuth, "browser_authentication_failed" + method, failureReason := authMethodOAuth, browserAuthenticationFailed defer func() { if resultErr == nil { return @@ -88,7 +88,7 @@ func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper } }() if cmd.Flags().Changed(params.AstAPIKeyFlag) { - method, failureReason = authMethodAPIKey, "api_key_authentication_failed" + method, failureReason = authMethodAPIKey, apiKeyAuthenticationFailed apiKey, err := cmd.Flags().GetString(params.AstAPIKeyFlag) if err != nil || strings.TrimSpace(apiKey) == "" { return errors.New("--apikey requires a nonempty API key") @@ -160,6 +160,9 @@ const ( authMethodOAuth = "OAuth" authMethodAPIKey = "APIKey" + browserAuthenticationFailed = "browser_authentication_failed" + apiKeyAuthenticationFailed = "api_key_authentication_failed" + agentCopilotCLI = "Copilot-CLI" agentClaudeCLI = "Claude-CLI" agentCursorCLI = "Cursor-CLI" diff --git a/internal/commands/auth_login_test.go b/internal/commands/auth_login_test.go index dad55ada4..3c6e429a5 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -494,7 +494,7 @@ func TestRunAuthLogin_UnsentFailureIsKeptForThePlugin(t *testing.T) { if err := json.Unmarshal(raw, &failures); err != nil { t.Fatal(err) } - if len(failures) != 1 || failures[0].Method != "APIKey" || failures[0].Reason != "api_key_authentication_failed" || + if len(failures) != 1 || failures[0].Method != "APIKey" || failures[0].Reason != apiKeyAuthenticationFailed || failures[0].ErrorCode != "Unknown" || failures[0].At < float64(before.Unix()) { t.Fatalf("unexpected kept failure: %s", raw) } @@ -546,7 +546,7 @@ func assertAPIKeyFailureEvent(t *testing.T, event *wrappers.DataForAITelemetry) if event.Type != authenticationEventType || event.Agent != "Claude-CLI" || event.AIProvider != "Claude" || event.Status != hooktelemetry.StatusFailure || event.SessionID != "" || !strings.HasPrefix(event.StatusResult, "Authentication failed. Reason: api_key_authentication_failed, Error Code: ") || - (*event.EventAttributes)["reasonCode"] != "api_key_authentication_failed" || + (*event.EventAttributes)["reasonCode"] != apiKeyAuthenticationFailed || (*event.EventAttributes)["authMethod"] != "APIKey" { t.Fatalf("unexpected login failure telemetry: %+v", event) }