diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index dbe0b0d65..672b82af7 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -7,11 +7,16 @@ 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" "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" @@ -20,8 +25,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" @@ -29,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. @@ -70,6 +77,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 +115,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, "SCA", severity, sid) + logRemediationTelemetry(agent, hooktelemetry.EngineOSS, severity, telemetrySID, ev.WorkDir, remediation) return agenthooks.DenyWithContext(finding, remediation) } } @@ -145,7 +174,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, context) return agenthooks.RejectEditWithContext(reason, context) } } @@ -154,7 +183,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, context) return agenthooks.RejectEditWithContext(reason, context) } kicsNote = note @@ -163,7 +192,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, hooktelemetry.EngineOSS, severity, ev.SessionID, ev.WorkDir, remediation) return agenthooks.RejectEditWithContext(finding, remediation) } } @@ -171,7 +200,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, context) return agenthooks.RejectEditWithContext(reason, context) } } @@ -265,7 +294,11 @@ 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) secretsScanner = secrets.NewScanner(jwt, ff) telemetryWrapper = tel @@ -288,11 +321,19 @@ 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, guidance string) { + ids, count := hooktelemetry.TakeRemediationFindings() if telemetryWrapper == nil { return } + attrs := wrappers.EventAttributes{"remediationMode": hooktelemetry.RemediationModeSelfHealing} + if ids != "" { + attrs["vulnerabilityId"] = ids + } + if sessionID != "" { + attrs["aiAgentSessionId"] = sessionID + } telemetryData := &wrappers.DataForAITelemetry{ AIProvider: agent, Agent: hostenv.TelemetryAgent(agent), @@ -301,9 +342,19 @@ func logRemediationTelemetry(agent, engine, severity, sessionID string) { UniqueID: wrappers.GetUniqueID(), Type: "hooks-remediate", SubType: "fixWithAIAssist", + StatusResult: hooktelemetry.RemediationSucceeded, + TotalCount: count, ProblemSeverity: severity, AiAgentSessionId: sessionID, + EventAttributes: &attrs, } + if strings.TrimSpace(guidance) == "" { + telemetryData.Status = hooktelemetry.StatusFailure + telemetryData.StatusResult = hooktelemetry.FailureResult("Remediation", remediationInstructionsMissing, hooktelemetry.ErrorCodeNone) + telemetryData.TotalCount = 0 + attrs["reasonCode"] = remediationInstructionsMissing + } + hooktelemetry.Enrich(telemetryData, workDir) if err := telemetryWrapper.SendAIDataToLog(telemetryData); err != nil { // fail-open @@ -319,8 +370,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 a70eeb8c1..a1f4b7439 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" @@ -194,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{} @@ -222,8 +224,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 +416,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) } } @@ -623,23 +625,26 @@ func TestRegisterGuardrails_AndPassThrough(t *testing.T) { } } +//nolint:goconst // test fixtures repeat values on purpose func TestLogRemediationTelemetry(t *testing.T) { resetHookGlobals(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) { tel := &recordingTelemetry{} telemetryWrapper = tel - logRemediationTelemetry("Cursor", "Asca", "Critical", "sess-9") + const ruleID = "1027" + hooktelemetry.SetRemediationFindings([]string{ruleID, ruleID}, 2) + logRemediationTelemetry("Cursor", "Asca", "Critical", "sess-9", "", "guidance") if len(tel.calls) != 1 { 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" { @@ -648,6 +653,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 completed successfully." { + t.Errorf("StatusResult = %q", got.StatusResult) + } if got.ProblemSeverity != "Critical" || got.AiAgentSessionId != "sess-9" { t.Errorf("severity/session = %q/%q", got.ProblemSeverity, got.AiAgentSessionId) } @@ -656,7 +666,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)) } @@ -858,7 +868,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") }) } @@ -868,7 +878,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") }) } @@ -964,3 +974,20 @@ 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.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 2427913e0..505535106 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca.go +++ b/internal/commands/agenthooks/guardrails/asca/asca.go @@ -1,12 +1,14 @@ package asca import ( + "errors" "os" "path/filepath" + "strconv" "strings" agenthooks "github.com/Checkmarx/ast-cx-hooks" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/services" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" @@ -41,7 +43,8 @@ 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() { if r := recover(); r != nil { @@ -49,7 +52,9 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, telemetryWrapper wrappers.Teleme reason = "" context = "" } - logASCATelemetry(telemetryWrapper, agent, ev.SessionID, findingCount) + if scanned { + hooktelemetry.LogScan(telemetryWrapper, agent, "Asca", ev.SessionID, ev.WorkDir, severities) + } }() if !isSupportedByASCA(ev.FilePath) { @@ -79,19 +84,22 @@ 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 { + scanned = true return false, "", "", "" } @@ -101,17 +109,27 @@ 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. + detected := newFindings + scanned = true + 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)) + } r, c := formatFindings(ev.FilePath, newFindings, ev.WorkDir, agent, ev.SessionID) - findingCount = len(newFindings) + hooktelemetry.SetRemediationFindings(ids, len(newFindings)) return true, r, c, highestSeverity(newFindings) } @@ -184,27 +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 string, totalCount int) { - if telemetryWrapper == nil || totalCount == 0 { - return - } - - telemetryData := &wrappers.DataForAITelemetry{ - Agent: hostenv.TelemetryAgent(agent), - AIProvider: agent, - Engine: "Asca", - TotalCount: totalCount, - UniqueID: wrappers.GetUniqueID(), - Type: "hooks-detect", - SubType: "scan", - ScanType: "asca", - AiAgentSessionId: sessionID, - } - - 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..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,41 +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) - }) -} - -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) - 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) - assert.NotNil(t, captured) - assert.Equal(t, "Asca", captured.Engine) - assert.Equal(t, 2, captured.TotalCount) - assert.Equal(t, "Claude", captured.AIProvider) -} - // ── findingsSummary / formatFindings ───────────────────────────────────────── func TestFindingsSummary_IncludesRemediation(t *testing.T) { 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/kics/kics.go b/internal/commands/agenthooks/guardrails/kics/kics.go index 684f4ee01..6ecd8f3af 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics.go +++ b/internal/commands/agenthooks/guardrails/kics/kics.go @@ -7,7 +7,7 @@ import ( "strings" agenthooks "github.com/Checkmarx/ast-cx-hooks" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" @@ -54,7 +54,8 @@ 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() { if r := recover(); r != nil { @@ -65,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, findingCount) + if scanned { + hooktelemetry.LogScan(telemetryWrapper, agent, "IaC", ev.SessionID, ev.WorkDir, severities) + } }() if !isSupportedByKICS(ev.FilePath) { @@ -83,6 +86,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() @@ -92,26 +96,32 @@ 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 { + scanned = true return false, "", "", "", "" } // For new files (no original content), every finding is new if originalContent == "" { + detected := newResults + scanned = true + severities = resultSeverities(detected) newResults = aboveThreshold(newResults) if len(newResults) == 0 { return false, "", "", "", "" } r, c := formatFindings(ev.FilePath, newResults, ev.Agent, ev.WorkDir, ev.SessionID) - findingCount = len(newResults) + hooktelemetry.SetRemediationFindings(resultIDs(newResults), len(newResults)) return true, r, c, "", highestSeverity(newResults) } // 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() @@ -120,19 +130,42 @@ 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), "" } - newFindings := aboveThreshold(NewFindings(origResults, newResults)) + // Telemetry reports what was DETECTED; the threshold only decides what is denied. + detected := NewFindings(origResults, newResults) + scanned = true + severities = resultSeverities(detected) + newFindings := aboveThreshold(detected) if len(newFindings) == 0 { return false, "", "", "", "" } r, c := formatFindings(ev.FilePath, newFindings, ev.Agent, ev.WorkDir, ev.SessionID) - findingCount = len(newFindings) + hooktelemetry.SetRemediationFindings(resultIDs(newFindings), 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 { @@ -163,31 +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 string, totalCount int) { - if telemetryWrapper == nil || totalCount == 0 { - return - } - - telemetryData := &wrappers.DataForAITelemetry{ - Agent: hostenv.TelemetryAgent(agent), - AIProvider: agent, - Engine: "IaC", - TotalCount: totalCount, - UniqueID: wrappers.GetUniqueID(), - Type: "hooks-detect", - SubType: "scan", - ScanType: "iac", - AiAgentSessionId: sessionID, - } - - 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 058f6f1b1..3c30dba2f 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" ) @@ -234,42 +232,3 @@ func TestScanFileEdit_EngineDownProducesNote(t *testing.T) { 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) - }) -} - -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) - 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) - 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) -} 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/guardrails/secrets/secrets.go b/internal/commands/agenthooks/guardrails/secrets/secrets.go index b4c3bbd8e..75e64c4b1 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets.go @@ -4,7 +4,7 @@ import ( "os" agenthooks "github.com/Checkmarx/ast-cx-hooks" - "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hooktelemetry" "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" @@ -35,7 +35,8 @@ 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 { logger.PrintfIfVerbose("secrets guardrail: recovered from panic, failing open: %v", r) @@ -44,12 +45,13 @@ func ScanFileEdit(ev *agenthooks.FileEditEvent, svc *Scanner, telemetryWrapper w context = "" severity = "" } - logSecretsTelemetry(telemetryWrapper, agent, ev.SessionID, findingCount) + if scanned { + hooktelemetry.LogScan(telemetryWrapper, agent, "Secrets", ev.SessionID, ev.WorkDir, severities) + } }() newContent, originalContent, ok := proposedContent(ev.FilePath, ev.Changes) if !ok { - findingCount = 1 return true, provenanceTag() + " " + unresolvedEditReason, provenanceTag() + " " + unresolvedEditContext, "" } if newContent == "" { @@ -59,10 +61,12 @@ 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, "", "", "" } if len(newResults) == 0 { + scanned = true return false, "", "", "" } @@ -70,22 +74,34 @@ 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, "", "", "" } 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 + scanned = true + 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) + } r, c := formatFindings(ev.FilePath, findings, ev.Agent, ev.WorkDir, ev.SessionID) - findingCount = len(findings) + hooktelemetry.SetRemediationFindings(ids, len(findings)) return true, r, c, highestSeverity(findings) } @@ -116,28 +132,6 @@ func highestSeverity(findings []secretsrealtime.SecretsRealtimeResult) string { return best } -func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sessionID string, totalCount int) { - if telemetryWrapper == nil || totalCount == 0 { - return - } - - telemetryData := &wrappers.DataForAITelemetry{ - Agent: hostenv.TelemetryAgent(agent), - AIProvider: agent, - Engine: "Secrets", - TotalCount: totalCount, - UniqueID: wrappers.GetUniqueID(), - Type: "hooks-detect", - SubType: "scan", - ScanType: "secrets", - AiAgentSessionId: sessionID, - } - - 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/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/agenthooks/hooktelemetry/hooktelemetry.go b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go new file mode 100644 index 000000000..9afa647ea --- /dev/null +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry.go @@ -0,0 +1,480 @@ +// 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 ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "regexp" + "strings" + "sync" + + 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" +) + +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). + 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 + + failedLoginsFile = "cx_failed_logins.json" + maxQueuedFailedLogins = 3 +) + +// 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{} + + remediationMu sync.Mutex + remediationIDs string + remediationCount int +) + +// 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 { + id = strings.TrimSpace(id) + if id == "" || seen[id] { + continue + } + seen[id] = true + kept = append(kept, id) + if len(kept) == maxFindingIDs { + break + } + } + return strings.Join(kept, ",") +} + +// 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. +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}, + {contextKeyAgentVersion, os.Getenv(params.AgentVersionEnv)}, + {contextKeyCxPluginVersion, os.Getenv(params.CxPluginVersionEnv)}, + {contextKeyPluginType, 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) { + 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 + } +} + +// 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: countKnownSeverities(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) { + 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 + } + code := ErrorCode(err) + reason := "scanner_error" + if code == codes.DeadlineExceeded.String() { + reason = "scanner_timeout" + } + attrs := scanAttributes(sessionID) + attrs["reasonCode"] = reason + data := &wrappers.DataForAITelemetry{ + Type: scanEventType, SubType: scanEventSubType, APIVersion: APIVersionV2, + AIProvider: agent, Agent: hostenv.TelemetryAgent(agent), + Engine: engine, ScanType: strings.ToLower(engine), + Status: StatusFailure, StatusResult: FailureResult("Scan", reason, code), + UniqueID: wrappers.GetUniqueID(), AiAgentSessionId: sessionID, + EventAttributes: &attrs, + } + Enrich(data, workDir) + _ = 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) { + 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 { + count := counts[s] + if highest == "" && count > 0 { + highest = s + } + parts = append(parts, fmt.Sprintf("%s=%d", s, count)) + } + 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", + copilotCLIAgent: copilotCLIAgent, + "copilot-vscode": copilotCLIAgent, + "cursor-cli": "cursor", + "codex-cli": "codex", + 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": contextKeyAgentVersion, + "CX_PLUGIN_VERSION": contextKeyCxPluginVersion, + "CX_PLUGIN_TYPE": contextKeyPluginType, +} + +// 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 func() { _ = 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 +} + +// 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 { + 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] +} + +// 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 "". +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):] + // 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:] + } + 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, ':') + 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] + } + host = hostWithoutPort(host) + 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..881eaab3e --- /dev/null +++ b/internal/commands/agenthooks/hooktelemetry/hooktelemetry_test.go @@ -0,0 +1,271 @@ +//go:build !integration + +package hooktelemetry + +import ( + "context" + "errors" + "os" + "path/filepath" + "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" + + 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 +// 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" +} + +//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 }{ + {"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"}, + {"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", ""}, + {"", ""}, + } + for _, tt := range tests { + assert.Equal(t, SanitizeRepoURL(tt.in), tt.want, "input %q", tt.in) + } +} + +//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") + 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 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")), errorCodeUnknown) +} + +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 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) + 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") +} + +//nolint:goconst // test fixtures repeat values on purpose +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: errorCodeUnknown, 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: 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}]`, + "an unreadable file is replaced") +} + +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) +} + +//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() + 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))) + } + 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) { + 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") +} + +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("", ""), "") +} + +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) + 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.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..f065d4927 100644 --- a/internal/commands/agenthooks/hostenv/hostenv_test.go +++ b/internal/commands/agenthooks/hostenv/hostenv_test.go @@ -75,17 +75,18 @@ 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"}, - {"other agents unchanged in VS Code", "Claude", rootVSCodeFromCLIInstall, "Claude-cli"}, - {"other agents unchanged", "Cursor", "", "Cursor-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"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { 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 641906fd4..6cb218b80 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" ) @@ -20,10 +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 } + if scanned { + s.logScan(agent, sessionID, workDir, mal, vuln) + } if f, r, sev := denyFrom(mal, vuln, workDir, agent, sessionID); f != "" { return f, r, sev } @@ -31,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 @@ -64,8 +72,10 @@ 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) return denyFrom(mal, vuln, workDir, agent, sessionID) } @@ -76,16 +86,60 @@ func denyFrom(malicious, vulnerable []ossrealtime.OssPackage, workDir, agent, se tag := provenanceTag(agent) if len(malicious) > 0 { f, r := DenyMalicious(malicious, agent) + hooktelemetry.SetRemediationFindings(maliciousPackageIDs(malicious), len(malicious)) return tag + " " + f, tag + " " + r, statusMalicious } vulnerable = aboveThreshold(vulnerable) if len(vulnerable) > 0 { f, r := DenyVulnerable(vulnerable, workDir, agent, sessionID) + ids := vulnerableCVEs(vulnerable) + hooktelemetry.SetRemediationFindings(ids, len(ids)) return tag + " " + f, tag + " " + r, highestVulnSeverity(vulnerable) } return "", "", "" } +// 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) { + 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) + } + } + hooktelemetry.LogScan(s.Telemetry, agent, hooktelemetry.EngineOSS, sessionID, workDir, severities) +} + +// 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 + 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 { @@ -111,16 +165,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/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/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..a95786d68 --- /dev/null +++ b/internal/commands/agenthooks/sca/telemetry_ids_test.go @@ -0,0 +1,77 @@ +//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" +) + +//nolint:goconst // test fixtures repeat values on purpose +func TestDenyFrom_RecordsRemediationFindings(t *testing.T) { + old := BelowThreshold + t.Cleanup(func() { BelowThreshold = old }) + 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 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{ + {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 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) + } +} + +//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 { + sent = append(sent, d) + return nil + }}} + + s.logScan("Claude", "sess", t.TempDir(), nil, nil) + 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) != 2 { + t.Fatalf("expected two scan events, got %d", len(sent)) + } + 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" { + t.Fatalf("unexpected statusResult %q", d.StatusResult) + } + + (&Scanner{}).logScan("Claude", "sess", "", mal, vuln) // no telemetry wrapper: must not panic +} diff --git a/internal/commands/agenthooks/sca/threshold_test.go b/internal/commands/agenthooks/sca/threshold_test.go index 320a45521..a6a1bf538 100644 --- a/internal/commands/agenthooks/sca/threshold_test.go +++ b/internal/commands/agenthooks/sca/threshold_test.go @@ -30,6 +30,25 @@ 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 + 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 }) diff --git a/internal/commands/auth.go b/internal/commands/auth.go index 613d3065f..7107e5111 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 } @@ -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.go b/internal/commands/auth_login.go index da85c0695..19352c9b3 100644 --- a/internal/commands/auth_login.go +++ b/internal/commands/auth_login.go @@ -4,8 +4,11 @@ import ( "context" "fmt" "os" + "strings" + "time" "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" @@ -23,20 +26,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 +58,49 @@ 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) + 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 } -func runAuthLogin(cmd *cobra.Command, _ []string) error { +func runAuthLogin(cmd *cobra.Command, telemetryWrapper wrappers.TelemetryWrapper) (resultErr error) { + method, failureReason := authMethodOAuth, browserAuthenticationFailed + defer func() { + 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) { + 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") + } + accessToken, err := wrappers.ExchangeLoginAPIKey(apiKey) + if err != nil { + return err + } + failureReason = loginCredentialSaveFailed + return completeAuthLogin(cmd, telemetryWrapper, apiKey, accessToken, method) + } + // 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 +109,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 +130,172 @@ func runAuthLogin(cmd *cobra.Command, _ []string) error { return err } - return persistLogin(cmd, tokens.RefreshToken) + failureReason = loginCredentialSaveFailed + return completeAuthLogin(cmd, telemetryWrapper, tokens.RefreshToken, tokens.AccessToken, method) +} + +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 agentCopilotCLI + case "claude-cli": + return agentClaudeCLI + case "cursor-cli": + return agentCursorCLI + case "gemini-cli": + return agentGeminiCLI + case "codex-cli": + return agentCodexCLI + default: + return "" + } +} + +// The authMethod values and the telemetry agent labels a CLI login reports. +const ( + authMethodOAuth = "OAuth" + authMethodAPIKey = "APIKey" + + browserAuthenticationFailed = "browser_authentication_failed" + apiKeyAuthenticationFailed = "api_key_authentication_failed" + + 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 { + err := persistLogin(cmd, credential) + sendLoginTelemetry(cmd, telemetryWrapper, accessToken, authMethod, err) + return err +} + +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()) + } +} + +// 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 +// 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 := storedAccessTokenWithin(loginFailureTokenTimeout); token != "" { + wrappers.CacheAuthenticatedAccessToken(token) + } + errorCode := hooktelemetry.ErrorCode(loginErr) + data, attrs := loginTelemetryData(cmd, agent, authMethod) + data.Status = hooktelemetry.StatusFailure + 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()) + } + } +} + +// 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) + 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)) + } + // 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: hooktelemetry.StatusSuccess, + StatusResult: "Authentication successful.", + Agent: agent, + AgentVersion: agentVersion, + CxPluginVersion: pluginVersion, + AIProvider: strings.TrimSuffix(agent, "-CLI"), + AiAgentSessionId: agentSessionID, + PluginType: "CLI", + UniqueID: wrappers.GetUniqueID(), + EventAttributes: &attrs, + } + return data, attrs } // connectionFlagsProvided reports whether any connection detail was passed as a flag. @@ -94,11 +305,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..3c6e429a5 100644 --- a/internal/commands/auth_login_test.go +++ b/internal/commands/auth_login_test.go @@ -4,12 +4,18 @@ 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" "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 +245,309 @@ func TestPersistLogin_PrintsSuccessMessage(t *testing.T) { t.Errorf("expected success message in output, got: %q", output) } } + +type telemetryAgentCase struct { + name string + agent *string + want string +} + +//nolint:goconst // test fixtures repeat values on purpose +func TestCompleteAuthLogin_TelemetryAgentAllowlist(t *testing.T) { + t.Setenv(params.AgentVersionEnv, "fallback-agent") + t.Setenv(params.CxPluginVersionEnv, "fallback-plugin") + cases := []telemetryAgentCase{ + {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) { 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) + } +} + +//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" || + 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") + } +} + +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) + 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) + 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") + } +} + +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 != 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) + } + if got := viper.GetString(params.SessionIDConfigKey); got != "previous-session" { + t.Fatalf("existing session changed: %q", got) + } +} + +//nolint:goconst // test fixtures repeat values on purpose +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 != apiKeyAuthenticationFailed || + 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) + cases := []struct{ name, agent string }{{"eligible agent", "claude-cli"}, {"no agent", ""}} + for _, tc := range cases { + 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"] != apiKeyAuthenticationFailed || + (*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 1f3f22d1c..7d74a4e5a 100644 --- a/internal/commands/ignore_vulnerability.go +++ b/internal/commands/ignore_vulnerability.go @@ -7,9 +7,15 @@ 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" + "github.com/checkmarx/ast-cli/internal/wrappers/grpcs" "github.com/checkmarx/ast-cli/internal/wrappers/utils" "github.com/pkg/errors" "github.com/spf13/cobra" @@ -51,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) @@ -61,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 := invalidIgnoreInputReason + defer func() { + if resultErr != nil && !remove && utils.GetOptionalParam("agent") != "" { + sendIgnoreTelemetry(telemetryWrapper, scanType, nil, failureReason) + } + }() + data, err := readIgnoreData(cmd, dataArg) if err != nil { return err @@ -71,18 +84,24 @@ 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 { 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 @@ -92,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) } @@ -100,8 +120,8 @@ func runIgnoreVulnerability(telemetryWrapper wrappers.TelemetryWrapper) func(cmd if remove { action = "revived" } - if !remove && changed > 0 { - logIgnoreTelemetry(telemetryWrapper, scanType) + if len(addedEntries) > 0 { + logIgnoreTelemetry(telemetryWrapper, scanType, addedEntries) } _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s %d vulnerability(ies); %d entr%s now in %s\n", @@ -141,7 +161,11 @@ 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) { + sendIgnoreTelemetry(telemetryWrapper, scanType, entries, "") +} + +func sendIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType string, entries []any, failureReason string) { if telemetryWrapper == nil { return } @@ -149,7 +173,23 @@ func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType str 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{} + ids := make([]string, 0, len(entries)) + for _, e := range entries { + ids = append(ids, ignoreEntryID(e)) + } + if v := hooktelemetry.FormatFindingIDs(ids); v != "" { + attrs["vulnerabilityId"] = v + } + if sessionID != "" { + attrs["aiAgentSessionId"] = sessionID + } telemetryData := &wrappers.DataForAITelemetry{ AIProvider: aiProvider, Agent: agent, @@ -157,27 +197,104 @@ func logIgnoreTelemetry(telemetryWrapper wrappers.TelemetryWrapper, scanType str 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 = hooktelemetry.FailureResult("Ignore", failureReason, hooktelemetry.ErrorCodeNone) + } + 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 + } + // 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 } } -// 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"). +// 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 "" + } +} + +// 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 ignorePackageSubType + case containersEngine: + return ignoreImageSubType + default: + return ignoreFindingSubType + } +} + +// 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: - 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 new file mode 100644 index 000000000..a00d9387b --- /dev/null +++ b/internal/commands/ignore_vulnerability_telemetry_test.go @@ -0,0 +1,211 @@ +//go:build !integration + +package commands + +import ( + "io" + "os" + "path/filepath" + "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" +) + +//nolint:goconst // test fixtures repeat values on purpose +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) + } + } +} + +//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 { + 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" || 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") { + t.Fatalf("secret value leaked in attribute %q", k) + } + } +} + +//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"}` + 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 + }} + scanTypes := []string{"oss", "sca"} + for i, payload := range []string{existing, "[" + existing + "," + added + "]"} { + cmd := NewIgnoreVulnerabilityCommand(telemetry) + cmd.SetOut(io.Discard) + cmd.SetArgs([]string{"--scan-type", scanTypes[i], "--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)) + } + 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) + } +} + +//nolint:goconst // test fixtures repeat values on purpose +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) + 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="+agentSessionID+";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.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) + } + if sent.EventAttributes == nil || (*sent.EventAttributes)["aiAgentSessionId"] != agentSessionID { + t.Fatalf("missing session attribute: %+v", sent.EventAttributes) + } +} + +//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) }) + 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.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) + } +} + +//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", + "asca": "ignoreFinding", "iac": "ignoreFinding", "secrets": "ignoreFinding", + } { + if got := ignoreSubType(engineName(scanType)); got != want { + t.Errorf("ignoreSubType(%q) = %q, want %q", scanType, got, want) + } + } +} + +//nolint:goconst // test fixtures repeat values on purpose +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) + } +} diff --git a/internal/commands/telemetry.go b/internal/commands/telemetry.go index 49ebfce78..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{ @@ -45,7 +49,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 +103,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 == authenticationEventType && strings.TrimSpace(agent) == "" { + return nil + } engine, _ := cmd.Flags().GetString("engine") scanType, _ := cmd.Flags().GetString("scan-type") status, _ := cmd.Flags().GetString("status") @@ -114,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/commands/telemetry_test.go b/internal/commands/telemetry_test.go index dcca56155..e370d35b6 100644 --- a/internal/commands/telemetry_test.go +++ b/internal/commands/telemetry_test.go @@ -13,6 +13,7 @@ import ( "gotest.tools/assert" ) +//nolint:goconst // test fixtures repeat values on purpose func TestParseEventAttributes(t *testing.T) { tests := []struct { name string @@ -47,6 +48,7 @@ func TestParseEventAttributes(t *testing.T) { } } +//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) @@ -79,6 +81,37 @@ func TestRunTelemetryAI_PassesEventAttributesAndSessionID(t *testing.T) { }) } +//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( 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" 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/api_key_realm_test.go b/internal/wrappers/api_key_realm_test.go new file mode 100644 index 000000000..ec85e3c41 --- /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{}{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") + } + 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 abfc0293b..a51aa7725 100644 --- a/internal/wrappers/client.go +++ b/internal/wrappers/client.go @@ -705,6 +705,47 @@ 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) + realmURL, err := ExtractFromTokenClaims(apiKey, audienceClaimKey) + if err != nil { + return "", err + } + parsedRealm, err := url.Parse(realmURL) + if err != nil || parsedRealm.Hostname() == "" || parsedRealm.User != nil || + !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) + 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 93610b717..0e58a1503 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) { @@ -570,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) + } +} diff --git a/internal/wrappers/jwt-helper_test.go b/internal/wrappers/jwt-helper_test.go index 1cc4d1417..310d2795c 100644 --- a/internal/wrappers/jwt-helper_test.go +++ b/internal/wrappers/jwt-helper_test.go @@ -75,6 +75,7 @@ func TestGetEnabledEngines(t *testing.T) { } } +//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) 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) +} 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, }