From cb301082416844ddfe2d98be1ef7444681e08410 Mon Sep 17 00:00:00 2001 From: atishj99 Date: Fri, 30 Oct 2026 22:22:56 +0530 Subject: [PATCH 1/4] Remove feature-flag gates from scan features Use current license names for SCS engines and remove feature-flag checks from realtime scans, risk-management results, AISC, and multipart uploads. --- internal/commands/agenthooks.go | 4 +- internal/commands/agenthooks/cx/hooks.go | 8 +- internal/commands/agenthooks/cx/hooks_test.go | 7 +- .../agenthooks/guardrails/kics/scanner.go | 7 +- .../guardrails/kics/scanner_test.go | 6 +- .../agenthooks/guardrails/secrets/scanner.go | 7 +- internal/commands/agenthooks/sca/scan.go | 7 +- .../commands/containers-realtime-engine.go | 3 +- .../containers-realtime-engine_test.go | 8 - internal/commands/hooks.go | 18 +- internal/commands/iac-realtime-engine.go | 3 +- internal/commands/iac-realtime-engine_test.go | 33 +- internal/commands/oss-realtime-engine.go | 3 +- internal/commands/oss-realtime-engine_test.go | 6 - internal/commands/pre-receive.go | 18 +- internal/commands/pre_commit.go | 26 +- internal/commands/pre_commit_test.go | 69 +- internal/commands/pre_receive_test.go | 3 +- internal/commands/result.go | 15 +- internal/commands/result_test.go | 9 - internal/commands/root.go | 2 +- internal/commands/scan.go | 109 +-- internal/commands/scan_test.go | 763 +++--------------- internal/commands/secrets-realtime.go | 3 +- internal/commands/secrets-realtime_test.go | 14 - internal/commands/telemetry_test.go | 4 - internal/constants/errors/errors.go | 1 - internal/constants/errors/errors_test.go | 1 - internal/params/flags.go | 2 - internal/services/realtimeengine/common.go | 9 - .../services/realtimeengine/common_test.go | 28 - .../containersrealtime/containers-realtime.go | 6 - .../containers-realtime_test.go | 29 - .../iacrealtime/iac-realtime.go | 16 +- .../iacrealtime/iac-realtime_test.go | 156 +--- .../ossrealtime/oss-realtime.go | 8 - .../ossrealtime/oss-realtime_test.go | 21 - .../secretsrealtime/secrets-realtime.go | 7 - .../secretsrealtime/secrets-realtime_test.go | 47 +- internal/wrappers/feature-flags.go | 17 - internal/wrappers/jwt-helper.go | 54 +- internal/wrappers/jwt-helper_test.go | 80 +- internal/wrappers/mock/jwt-helper-mock.go | 11 +- test/integration/scan_test.go | 10 +- 44 files changed, 290 insertions(+), 1368 deletions(-) diff --git a/internal/commands/agenthooks.go b/internal/commands/agenthooks.go index 82b95f5de..7c1a66dfc 100644 --- a/internal/commands/agenthooks.go +++ b/internal/commands/agenthooks.go @@ -160,7 +160,7 @@ func NewHookCheckAuthCommand(jwt wrappers.JWTWrapper) *cobra.Command { // Routes are declared per-agent in cxhooks.Agents (cx package). // ============================================================================= -func HookDispatchCommands(jwt wrappers.JWTWrapper, featureFlags wrappers.FeatureFlagsWrapper, realtimeScanner wrappers.RealtimeScannerWrapper, telemetryWrapper wrappers.TelemetryWrapper) []*cobra.Command { +func HookDispatchCommands(jwt wrappers.JWTWrapper, realtimeScanner wrappers.RealtimeScannerWrapper, telemetryWrapper wrappers.TelemetryWrapper) []*cobra.Command { var cmds []*cobra.Command for _, agent := range cxhooks.Agents { for _, r := range agent.Routes { @@ -175,7 +175,7 @@ func HookDispatchCommands(jwt wrappers.JWTWrapper, featureFlags wrappers.Feature Run: func(cmd *cobra.Command, _ []string) { if isLicensed(jwt) { logger.PrintIfVerbose(fmt.Sprintf("hooks: registering security guardrails for %s", cmd.Use)) - cxhooks.RegisterGuardrails(jwt, featureFlags, realtimeScanner, telemetryWrapper) + cxhooks.RegisterGuardrails(jwt, realtimeScanner, telemetryWrapper) } else { logger.PrintIfVerbose(fmt.Sprintf("hooks: registering pass-through for %s", cmd.Use)) cxhooks.RegisterPassThrough() diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index 9fb7e3317..58fce4c22 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -259,10 +259,10 @@ 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) { - scaScanner = sca.NewScanner(jwt, ff, rt) - kicsScanner = kics.NewScanner(jwt, ff) - secretsScanner = secrets.NewScanner(jwt, ff) +func RegisterGuardrails(jwt wrappers.JWTWrapper, rt wrappers.RealtimeScannerWrapper, tel wrappers.TelemetryWrapper) { + scaScanner = sca.NewScanner(jwt, rt) + kicsScanner = kics.NewScanner(jwt) + secretsScanner = secrets.NewScanner(jwt) telemetryWrapper = tel agenthooks.WhenAgentIdle(cxWhenAgentIdle) agenthooks.BeforeToolCall(cxBeforeToolCall) diff --git a/internal/commands/agenthooks/cx/hooks_test.go b/internal/commands/agenthooks/cx/hooks_test.go index a70eeb8c1..9823dd0ba 100644 --- a/internal/commands/agenthooks/cx/hooks_test.go +++ b/internal/commands/agenthooks/cx/hooks_test.go @@ -594,7 +594,6 @@ func TestRegisterGuardrails_AndPassThrough(t *testing.T) { RegisterGuardrails( &mock.JWTMockWrapper{}, - mock.FeatureFlagsMockWrapper{}, mock.NewRealtimeScannerMockWrapper(), mock.TelemetryMockWrapper{}, ) @@ -831,7 +830,7 @@ func TestRegisterGuardrails_SetsScanners(t *testing.T) { }() telemetry := mock.TelemetryMockWrapper{} - RegisterGuardrails(&mock.JWTMockWrapper{}, &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, telemetry) + RegisterGuardrails(&mock.JWTMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, telemetry) assert.NotNil(t, scaScanner) assert.NotNil(t, kicsScanner) @@ -843,7 +842,7 @@ func TestRegisterPassThrough_ClearsScanners(t *testing.T) { prevSca, prevKics, prevSecrets := scaScanner, kicsScanner, secretsScanner defer func() { scaScanner, kicsScanner, secretsScanner = prevSca, prevKics, prevSecrets }() - RegisterGuardrails(&mock.JWTMockWrapper{}, &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, mock.TelemetryMockWrapper{}) + RegisterGuardrails(&mock.JWTMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, mock.TelemetryMockWrapper{}) assert.NotNil(t, scaScanner) RegisterPassThrough() @@ -917,7 +916,7 @@ func TestCodexApplyPatch_KICSFinding_DeniesEndToEnd(t *testing.T) { resetHookGlobals(t) agenthooks.ClearRoutes() - RegisterGuardrails(&mock.JWTMockWrapper{}, &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, mock.TelemetryMockWrapper{}) + RegisterGuardrails(&mock.JWTMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, mock.TelemetryMockWrapper{}) t.Cleanup(agenthooks.ClearRoutes) // RegisterGuardrails wires up real SCA/KICS scanners; swap KICS's underlying diff --git a/internal/commands/agenthooks/guardrails/kics/scanner.go b/internal/commands/agenthooks/guardrails/kics/scanner.go index 70716e982..fdb142ecd 100644 --- a/internal/commands/agenthooks/guardrails/kics/scanner.go +++ b/internal/commands/agenthooks/guardrails/kics/scanner.go @@ -17,7 +17,6 @@ import ( // substitute scan via NewScannerWithFunc. type Scanner struct { jwt wrappers.JWTWrapper - ff wrappers.FeatureFlagsWrapper scan func(path, ignoreFilePath string) ([]iacrealtime.IacRealtimeResult, error) // engine that last completed a scan. A delta edit scans twice (proposed and @@ -30,8 +29,8 @@ type Scanner struct { } // NewScanner returns a Scanner backed by the given wrappers. -func NewScanner(jwt wrappers.JWTWrapper, ff wrappers.FeatureFlagsWrapper) *Scanner { - s := &Scanner{jwt: jwt, ff: ff} +func NewScanner(jwt wrappers.JWTWrapper) *Scanner { + s := &Scanner{jwt: jwt} s.scan = s.runRealScan return s } @@ -143,7 +142,7 @@ func scanErrorAfterNoFallback(err error) error { } func (s *Scanner) runRealScan(path, ignoreFilePath string) ([]iacrealtime.IacRealtimeResult, error) { - svc := iacrealtime.NewIacRealtimeService(s.jwt, s.ff, iacrealtime.NewContainerManager()) + svc := iacrealtime.NewIacRealtimeService(s.jwt, iacrealtime.NewContainerManager()) engine := s.engine if engine == "" { diff --git a/internal/commands/agenthooks/guardrails/kics/scanner_test.go b/internal/commands/agenthooks/guardrails/kics/scanner_test.go index 0168aadfa..cf74f43da 100644 --- a/internal/commands/agenthooks/guardrails/kics/scanner_test.go +++ b/internal/commands/agenthooks/guardrails/kics/scanner_test.go @@ -16,9 +16,8 @@ import ( func TestNewScanner_ReturnsValidScanner(t *testing.T) { jwt := &mock.JWTMockWrapper{} - ff := &mock.FeatureFlagsMockWrapper{} - s := NewScanner(jwt, ff) + s := NewScanner(jwt) if s == nil { t.Fatal("expected non-nil scanner") } @@ -29,9 +28,8 @@ func TestNewScanner_ReturnsValidScanner(t *testing.T) { func TestNewScanner_HoldsWrappers(t *testing.T) { jwt := &mock.JWTMockWrapper{} - ff := &mock.FeatureFlagsMockWrapper{} - s := NewScanner(jwt, ff) + s := NewScanner(jwt) assert.NotNil(t, s) // Verify wrappers are internally stored assert.NotNil(t, s.scan) diff --git a/internal/commands/agenthooks/guardrails/secrets/scanner.go b/internal/commands/agenthooks/guardrails/secrets/scanner.go index a2eb58a1e..a4cd3eac4 100644 --- a/internal/commands/agenthooks/guardrails/secrets/scanner.go +++ b/internal/commands/agenthooks/guardrails/secrets/scanner.go @@ -9,13 +9,12 @@ import ( // Tests substitute scan via NewScannerWithFunc. type Scanner struct { jwt wrappers.JWTWrapper - ff wrappers.FeatureFlagsWrapper scan func(sourcePath, content, ignoreFilePath string) ([]secretsrealtime.SecretsRealtimeResult, error) } // NewScanner returns a Scanner backed by the secrets realtime engine. -func NewScanner(jwt wrappers.JWTWrapper, ff wrappers.FeatureFlagsWrapper) *Scanner { - s := &Scanner{jwt: jwt, ff: ff} +func NewScanner(jwt wrappers.JWTWrapper) *Scanner { + s := &Scanner{jwt: jwt} s.scan = s.runRealScan return s } @@ -27,6 +26,6 @@ func NewScannerWithFunc(f func(sourcePath, content, ignoreFilePath string) ([]se } func (s *Scanner) runRealScan(sourcePath, content, ignoreFilePath string) ([]secretsrealtime.SecretsRealtimeResult, error) { - svc := secretsrealtime.NewSecretsRealtimeService(s.jwt, s.ff) + svc := secretsrealtime.NewSecretsRealtimeService(s.jwt) return svc.ScanContent(sourcePath, content, ignoreFilePath) } diff --git a/internal/commands/agenthooks/sca/scan.go b/internal/commands/agenthooks/sca/scan.go index e78ab6b54..f4ad3c8a6 100644 --- a/internal/commands/agenthooks/sca/scan.go +++ b/internal/commands/agenthooks/sca/scan.go @@ -23,7 +23,6 @@ const ( // substitute scan via NewScannerWithFunc. type Scanner struct { JWT wrappers.JWTWrapper - FF wrappers.FeatureFlagsWrapper RT wrappers.RealtimeScannerWrapper scan func(path string) (*ossrealtime.OssPackageResults, error) // workDir is the workspace root reported by the hook event (its "cwd"). The @@ -35,8 +34,8 @@ type Scanner struct { // NewScanner returns a Scanner backed by the given wrappers. The scan call // goes through ossrealtime.NewOssRealtimeService.RunOssRealtimeScan. -func NewScanner(jwt wrappers.JWTWrapper, ff wrappers.FeatureFlagsWrapper, rt wrappers.RealtimeScannerWrapper) *Scanner { - s := &Scanner{JWT: jwt, FF: ff, RT: rt} +func NewScanner(jwt wrappers.JWTWrapper, rt wrappers.RealtimeScannerWrapper) *Scanner { + s := &Scanner{JWT: jwt, RT: rt} s.scan = s.runRealScan return s } @@ -48,7 +47,7 @@ func NewScannerWithFunc(f func(path string) (*ossrealtime.OssPackageResults, err } func (s *Scanner) runRealScan(path string) (*ossrealtime.OssPackageResults, error) { - svc := ossrealtime.NewOssRealtimeService(s.JWT, s.FF, s.RT) + svc := ossrealtime.NewOssRealtimeService(s.JWT, s.RT) return svc.RunOssRealtimeScan(path, existingIgnoreFilePath(s.workDir)) } diff --git a/internal/commands/containers-realtime-engine.go b/internal/commands/containers-realtime-engine.go index dddce085b..eb6d15eee 100644 --- a/internal/commands/containers-realtime-engine.go +++ b/internal/commands/containers-realtime-engine.go @@ -12,7 +12,6 @@ import ( func RunScanContainersRealtimeCommand( realtimeScannerWrapper wrappers.RealtimeScannerWrapper, jwtWrapper wrappers.JWTWrapper, - featureFlagWrapper wrappers.FeatureFlagsWrapper, ) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, _ []string) error { fileSourceFlag, _ := cmd.Flags().GetString(commonParams.SourcesFlag) @@ -22,7 +21,7 @@ func RunScanContainersRealtimeCommand( ignoredFilePathFlag, _ := cmd.Flags().GetString(commonParams.IgnoredFilePathFlag) - containersRealtimeService := containersrealtime.NewContainersRealtimeService(jwtWrapper, featureFlagWrapper, realtimeScannerWrapper) + containersRealtimeService := containersrealtime.NewContainersRealtimeService(jwtWrapper, realtimeScannerWrapper) images, err := containersRealtimeService.RunContainersRealtimeScan(fileSourceFlag, ignoredFilePathFlag) if err != nil { diff --git a/internal/commands/containers-realtime-engine_test.go b/internal/commands/containers-realtime-engine_test.go index e0034b353..c325d5123 100644 --- a/internal/commands/containers-realtime-engine_test.go +++ b/internal/commands/containers-realtime-engine_test.go @@ -6,13 +6,10 @@ import ( "strings" "testing" - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/mock" "github.com/stretchr/testify/assert" ) func TestRunScanContainersRealtimeCommand_EmptyFilePath_Fails(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} err := execCmdNotNilAssertion(t, "scan", "containers-realtime", "-s", "") assert.NotNil(t, err) assert.True(t, strings.Contains(err.Error(), "file path is required") || @@ -21,29 +18,24 @@ func TestRunScanContainersRealtimeCommand_EmptyFilePath_Fails(t *testing.T) { } func TestRunScanContainersRealtimeCommand_MissingSourcesFlag_Fails(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} err := execCmdNotNilAssertion(t, "scan", "containers-realtime") assert.NotNil(t, err) } func TestRunScanContainersRealtimeCommand_Dockerfile_Success(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} execCmdNilAssertion(t, "scan", "containers-realtime", "-s", "data/Dockerfile") } func TestRunScanContainersRealtimeCommand_ContainersTestdata_Success(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} execCmdNilAssertion(t, "scan", "containers-realtime", "-s", "data/containers/testdata/Dockerfile") } func TestRunScanContainersRealtimeCommand_MissingFile_Fails(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} err := execCmdNotNilAssertion(t, "scan", "containers-realtime", "-s", "data/does-not-exist-Dockerfile") assert.NotNil(t, err) } func TestRunScanContainersRealtimeCommand_WithIgnoredFilePathFlag(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} // Empty/missing ignore file should still succeed (service fail-opens on ignore load). execCmdNilAssertion(t, "scan", "containers-realtime", diff --git a/internal/commands/hooks.go b/internal/commands/hooks.go index 65c9b5c46..f96c7e8c6 100644 --- a/internal/commands/hooks.go +++ b/internal/commands/hooks.go @@ -10,7 +10,7 @@ import ( ) // NewHooksCommand creates the hooks command with pre-commit subcommand -func NewHooksCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper, realtimeScannerWrapper wrappers.RealtimeScannerWrapper, telemetryWrapper wrappers.TelemetryWrapper) *cobra.Command { +func NewHooksCommand(jwtWrapper wrappers.JWTWrapper, realtimeScannerWrapper wrappers.RealtimeScannerWrapper, telemetryWrapper wrappers.TelemetryWrapper) *cobra.Command { hooksCmd := &cobra.Command{ Use: "hooks", Short: "Manage Git hooks and AI coding agent hooks", @@ -33,8 +33,8 @@ func NewHooksCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrapper } // Add pre-commit, pre-receive, and agenthooks management subcommands - hooksCmd.AddCommand(PreCommitCommand(jwtWrapper, featureFlagsWrapper)) - hooksCmd.AddCommand(PreReceiveCommand(jwtWrapper, featureFlagsWrapper)) + hooksCmd.AddCommand(PreCommitCommand(jwtWrapper)) + hooksCmd.AddCommand(PreReceiveCommand(jwtWrapper)) hooksCmd.AddCommand(NewAgentHooksCommand()) // Hidden machine-readable readiness probe: cx hooks check-auth @@ -45,21 +45,15 @@ func NewHooksCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrapper // Register all hidden hook dispatch subcommands so that cx itself acts as // the hook binary. Agents invoke: cx hooks // e.g. cx hooks claude-pre-tool-use - for _, dispatchCmd := range HookDispatchCommands(jwtWrapper, featureFlagsWrapper, realtimeScannerWrapper, telemetryWrapper) { + for _, dispatchCmd := range HookDispatchCommands(jwtWrapper, realtimeScannerWrapper, telemetryWrapper) { hooksCmd.AddCommand(dispatchCmd) } return hooksCmd } -func validateLicense(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) error { - scsLicensingV2Flag, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, wrappers.ScsLicensingV2Enabled) - var licenseName string - if scsLicensingV2Flag.Status { - licenseName = params.SecretDetectionLabel - } else { - licenseName = params.EnterpriseSecretsLabel - } +func validateLicense(jwtWrapper wrappers.JWTWrapper) error { + licenseName := params.SecretDetectionLabel logger.PrintIfVerbose("hooks: checking license for " + licenseName) diff --git a/internal/commands/iac-realtime-engine.go b/internal/commands/iac-realtime-engine.go index cf253471e..2dba6f0fa 100644 --- a/internal/commands/iac-realtime-engine.go +++ b/internal/commands/iac-realtime-engine.go @@ -11,7 +11,6 @@ import ( func RunScanIacRealtimeCommand( jwtWrapper wrappers.JWTWrapper, - featureFlagWrapper wrappers.FeatureFlagsWrapper, ) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, _ []string) error { fileSourceFlag, _ := cmd.Flags().GetString(commonParams.SourcesFlag) @@ -22,7 +21,7 @@ func RunScanIacRealtimeCommand( ignoredFilePathFlag, _ := cmd.Flags().GetString(commonParams.IgnoredFilePathFlag) engine, _ := cmd.Flags().GetString(commonParams.EngineFlag) - iacRealtimeService := iacrealtime.NewIacRealtimeService(jwtWrapper, featureFlagWrapper, iacrealtime.NewContainerManager()) + iacRealtimeService := iacrealtime.NewIacRealtimeService(jwtWrapper, iacrealtime.NewContainerManager()) results, err := iacRealtimeService.RunIacRealtimeScan(fileSourceFlag, engine, ignoredFilePathFlag) if err != nil { diff --git a/internal/commands/iac-realtime-engine_test.go b/internal/commands/iac-realtime-engine_test.go index 8c8c1aead..f37dedbaf 100644 --- a/internal/commands/iac-realtime-engine_test.go +++ b/internal/commands/iac-realtime-engine_test.go @@ -22,7 +22,6 @@ import ( func TestRunScanIacRealtimeCommand_MissingFileSource_Error(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -40,7 +39,6 @@ func TestRunScanIacRealtimeCommand_MissingFileSource_Error(t *testing.T) { func TestRunScanIacRealtimeCommand_EmptyFileSource_Error(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -75,9 +73,8 @@ func TestRunScanIacRealtimeCommand_ValidFileSource_Success(t *testing.T) { } jwtMock := &mock.JWTMockWrapper{} - flagsMock := &mock.FeatureFlagsMockWrapper{} - handler := RunScanIacRealtimeCommand(jwtMock, flagsMock) + handler := RunScanIacRealtimeCommand(jwtMock) cmd := &cobra.Command{} cmd.SetOut(bytes.NewBuffer([]byte{})) @@ -114,9 +111,8 @@ func TestRunScanIacRealtimeCommand_WithIgnoredFilePath(t *testing.T) { } jwtMock := &mock.JWTMockWrapper{} - flagsMock := &mock.FeatureFlagsMockWrapper{} - handler := RunScanIacRealtimeCommand(jwtMock, flagsMock) + handler := RunScanIacRealtimeCommand(jwtMock) cmd := &cobra.Command{} cmd.SetOut(bytes.NewBuffer([]byte{})) @@ -151,7 +147,6 @@ func TestRunScanIacRealtimeCommand_WithDocker_Engine(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -180,7 +175,6 @@ func TestRunScanIacRealtimeCommand_WithPodman_Engine(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -209,7 +203,6 @@ func TestRunScanIacRealtimeCommand_WithEmptyEngine_Default(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -241,7 +234,6 @@ func TestRunScanIacRealtimeCommand_OutputBuffer(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) outputBuffer := bytes.NewBuffer([]byte{}) @@ -268,7 +260,6 @@ func TestRunScanIacRealtimeCommand_OutputBuffer(t *testing.T) { func TestRunScanIacRealtimeCommand_NoFlagsSet_UsesDefaults(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -300,7 +291,6 @@ func TestRunScanIacRealtimeCommand_PathWithSpaces(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -329,7 +319,6 @@ func TestRunScanIacRealtimeCommand_AbsolutePath(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -361,7 +350,6 @@ func TestRunScanIacRealtimeCommand_FlagRetrieval_FileSourceExtracted(t *testing. // Track if the correct file source is used by checking for error handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -393,7 +381,6 @@ func TestRunScanIacRealtimeCommand_MultipleEngineTypes(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) cmd := &cobra.Command{} @@ -422,7 +409,6 @@ func TestRunScanIacRealtimeCommand_MultipleEngineTypes(t *testing.T) { func TestRunScanIacRealtimeCommand_ReturnsCobraErrorHandler(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) if handler == nil { @@ -447,9 +433,8 @@ func TestRunScanIacRealtimeCommand_ReturnsCobraErrorHandler(t *testing.T) { func TestRunScanIacRealtimeCommand_WithJWTWrapper(t *testing.T) { jwtWrapper := &mock.JWTMockWrapper{} - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - handler := RunScanIacRealtimeCommand(jwtWrapper, featureFlagsWrapper) + handler := RunScanIacRealtimeCommand(jwtWrapper) if handler == nil { t.Error("handler should be created with wrappers") @@ -465,17 +450,6 @@ func TestRunScanIacRealtimeCommand_WithJWTWrapper(t *testing.T) { } } -func TestRunScanIacRealtimeCommand_WithFeatureFlagsWrapper(t *testing.T) { - jwtWrapper := &mock.JWTMockWrapper{} - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - - handler := RunScanIacRealtimeCommand(jwtWrapper, featureFlagsWrapper) - - if handler == nil { - t.Error("handler should be created successfully") - } -} - // ============================================================================ // Integration Tests // ============================================================================ @@ -500,7 +474,6 @@ func TestRunScanIacRealtimeCommand_FullFlow_WithAllFlags(t *testing.T) { handler := RunScanIacRealtimeCommand( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, ) outputBuffer := bytes.NewBuffer([]byte{}) diff --git a/internal/commands/oss-realtime-engine.go b/internal/commands/oss-realtime-engine.go index 31d49d9e7..323248630 100644 --- a/internal/commands/oss-realtime-engine.go +++ b/internal/commands/oss-realtime-engine.go @@ -12,7 +12,6 @@ import ( func RunScanOssRealtimeCommand( realtimeScannerWrapper wrappers.RealtimeScannerWrapper, jwtWrapper wrappers.JWTWrapper, - featureFlagWrapper wrappers.FeatureFlagsWrapper, ) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, _ []string) error { fileSourceFlag, _ := cmd.Flags().GetString(commonParams.SourcesFlag) @@ -22,7 +21,7 @@ func RunScanOssRealtimeCommand( ignoredFilePathFlag, _ := cmd.Flags().GetString(commonParams.IgnoredFilePathFlag) - ossRealtimeService := ossrealtime.NewOssRealtimeService(jwtWrapper, featureFlagWrapper, realtimeScannerWrapper) + ossRealtimeService := ossrealtime.NewOssRealtimeService(jwtWrapper, realtimeScannerWrapper) packages, err := ossRealtimeService.RunOssRealtimeScan(fileSourceFlag, ignoredFilePathFlag) if err != nil { diff --git a/internal/commands/oss-realtime-engine_test.go b/internal/commands/oss-realtime-engine_test.go index 630fcb577..20c9c3ec2 100644 --- a/internal/commands/oss-realtime-engine_test.go +++ b/internal/commands/oss-realtime-engine_test.go @@ -3,13 +3,10 @@ package commands import ( "testing" - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/mock" "github.com/stretchr/testify/assert" ) func TestRunScanOssRealtimeCommand_RequirementsTxtFile_ScanSuccess(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} execCmdNilAssertion( t, "scan", "oss-realtime", "-s", "data/manifests/requirements.txt", @@ -17,7 +14,6 @@ func TestRunScanOssRealtimeCommand_RequirementsTxtFile_ScanSuccess(t *testing.T) } func TestRunScanOssRealtimeCommand_EmptyFilePath_ScanFailed(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} err := execCmdNotNilAssertion( t, "scan", "oss-realtime", "-s", "", @@ -26,7 +22,6 @@ func TestRunScanOssRealtimeCommand_EmptyFilePath_ScanFailed(t *testing.T) { } func TestRunScanOssRealtimeCommand_PackageJsonFile_ScanSuccess(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} execCmdNilAssertion( t, "scan", "oss-realtime", "-s", "data/manifests/package.json", @@ -34,7 +29,6 @@ func TestRunScanOssRealtimeCommand_PackageJsonFile_ScanSuccess(t *testing.T) { } func TestRunScanOssRealtimeCommand_UnsupportedFileType_ScanFailed(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} err := execCmdNotNilAssertion( t, "scan", "oss-realtime", "-s", "not-supported-extension.txt", diff --git a/internal/commands/pre-receive.go b/internal/commands/pre-receive.go index 4b7457c8d..2396f884c 100644 --- a/internal/commands/pre-receive.go +++ b/internal/commands/pre-receive.go @@ -15,7 +15,7 @@ const ( SuccessFullSecretsLicenceValidation = "License for pre-receive secret detection has been validated successfully" ) -func PreReceiveCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func PreReceiveCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { preReceiveCmd := &cobra.Command{ Use: "pre-receive", Short: "Manage pre-receive hooks and run secret detection scans", @@ -27,7 +27,7 @@ func PreReceiveCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrapp ), } preReceiveCmd.AddCommand(scanSecretsPreReceiveCommand()) - preReceiveCmd.AddCommand(validateSecretsLicence(jwtWrapper, featureFlagsWrapper)) + preReceiveCmd.AddCommand(validateSecretsLicence(jwtWrapper)) return preReceiveCmd } @@ -54,7 +54,7 @@ func scanSecretsPreReceiveCommand() *cobra.Command { return scanPrereceiveCmd } -func validateSecretsLicence(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func validateSecretsLicence(jwtWrapper wrappers.JWTWrapper) *cobra.Command { validateLicence := &cobra.Command{ Use: "validate", Short: "Validates the license for pre-receive secret detection", @@ -64,20 +64,14 @@ func validateSecretsLicence(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper $ cx hooks pre-receive validate `, ), - RunE: checkLicence(jwtWrapper, featureFlagsWrapper), + RunE: checkLicence(jwtWrapper), } return validateLicence } -func checkLicence(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) func(cmd *cobra.Command, args []string) error { +func checkLicence(jwtWrapper wrappers.JWTWrapper) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { - scsLicensingV2Flag, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, wrappers.ScsLicensingV2Enabled) - var licenseName string - if scsLicensingV2Flag.Status { - licenseName = params.SecretDetectionLabel - } else { - licenseName = params.EnterpriseSecretsLabel - } + licenseName := params.SecretDetectionLabel isAllowed, err := jwtWrapper.IsAllowedEngine(licenseName) if err != nil { diff --git a/internal/commands/pre_commit.go b/internal/commands/pre_commit.go index 44ff7c3ec..0d967d697 100644 --- a/internal/commands/pre_commit.go +++ b/internal/commands/pre_commit.go @@ -12,7 +12,7 @@ import ( // PreCommitCommand creates the pre-commit subcommand -func PreCommitCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func PreCommitCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { preCommitCmd := &cobra.Command{ Use: "pre-commit", Short: "Manage pre-commit hooks and run secret detection scans", @@ -26,11 +26,11 @@ func PreCommitCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappe } preCommitCmd.PersistentFlags().Bool("global", false, "Install the hook globally for all repositories") - preCommitCmd.AddCommand(secretsInstallGitHookCommand(jwtWrapper, featureFlagsWrapper)) + preCommitCmd.AddCommand(secretsInstallGitHookCommand(jwtWrapper)) preCommitCmd.AddCommand(secretsUninstallGitHookCommand()) - preCommitCmd.AddCommand(secretsUpdateGitHookCommand(jwtWrapper, featureFlagsWrapper)) - preCommitCmd.AddCommand(secretsScanCommand(jwtWrapper, featureFlagsWrapper)) - preCommitCmd.AddCommand(secretsIgnoreCommand(jwtWrapper, featureFlagsWrapper)) + preCommitCmd.AddCommand(secretsUpdateGitHookCommand(jwtWrapper)) + preCommitCmd.AddCommand(secretsScanCommand(jwtWrapper)) + preCommitCmd.AddCommand(secretsIgnoreCommand(jwtWrapper)) preCommitCmd.AddCommand(secretsHelpCommand()) return preCommitCmd @@ -38,7 +38,7 @@ func PreCommitCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappe // / validateLicense verifies the user has the required license for secret detection -func secretsInstallGitHookCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func secretsInstallGitHookCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { cmd := &cobra.Command{ Use: "secrets-install-git-hook", Short: "Install the pre-commit hook", @@ -49,7 +49,7 @@ func secretsInstallGitHookCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWr `, ), PreRunE: func(cmd *cobra.Command, args []string) error { - return validateLicense(jwtWrapper, featureFlagsWrapper) + return validateLicense(jwtWrapper) }, RunE: func(cmd *cobra.Command, args []string) error { global, _ := cmd.Flags().GetBool("global") @@ -79,7 +79,7 @@ func secretsUninstallGitHookCommand() *cobra.Command { return cmd } -func secretsUpdateGitHookCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func secretsUpdateGitHookCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { cmd := &cobra.Command{ Use: "secrets-update-git-hook", Short: "Update the pre-commit hook", @@ -90,7 +90,7 @@ func secretsUpdateGitHookCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWra `, ), PreRunE: func(cmd *cobra.Command, args []string) error { - return validateLicense(jwtWrapper, featureFlagsWrapper) + return validateLicense(jwtWrapper) }, RunE: func(cmd *cobra.Command, args []string) error { global, _ := cmd.Flags().GetBool("global") @@ -101,7 +101,7 @@ func secretsUpdateGitHookCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWra return cmd } -func secretsScanCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func secretsScanCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { return &cobra.Command{ Use: "secrets-scan", Short: "Run the real-time secret detection scan", @@ -112,7 +112,7 @@ func secretsScanCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrap `, ), PreRunE: func(cmd *cobra.Command, args []string) error { - return validateLicense(jwtWrapper, featureFlagsWrapper) + return validateLicense(jwtWrapper) }, RunE: func(cmd *cobra.Command, args []string) error { return precommit.Scan() @@ -120,7 +120,7 @@ func secretsScanCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrap } } -func secretsIgnoreCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func secretsIgnoreCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { var resultIds string var all bool @@ -135,7 +135,7 @@ func secretsIgnoreCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wr `, ), PreRunE: func(cmd *cobra.Command, args []string) error { - if err := validateLicense(jwtWrapper, featureFlagsWrapper); err != nil { + if err := validateLicense(jwtWrapper); err != nil { return err } diff --git a/internal/commands/pre_commit_test.go b/internal/commands/pre_commit_test.go index 00001f798..96bc74360 100644 --- a/internal/commands/pre_commit_test.go +++ b/internal/commands/pre_commit_test.go @@ -5,17 +5,15 @@ package commands import ( "testing" - "github.com/checkmarx/ast-cli/internal/wrappers" "github.com/checkmarx/ast-cli/internal/wrappers/mock" "github.com/stretchr/testify/assert" ) func TestNewHooksCommand(t *testing.T) { mockJWT := &mock.JWTMockWrapper{} - mockFF := &mock.FeatureFlagsMockWrapper{} mockRealtime := &mock.RealtimeScannerMockWrapper{} mockTelemetry := &mock.TelemetryMockWrapper{} - cmd := NewHooksCommand(mockJWT, mockFF, mockRealtime, mockTelemetry) + cmd := NewHooksCommand(mockJWT, mockRealtime, mockTelemetry) assert.NotNil(t, cmd) assert.Equal(t, "hooks", cmd.Use) @@ -24,8 +22,7 @@ func TestNewHooksCommand(t *testing.T) { func TestPreCommitCommand(t *testing.T) { mockJWT := &mock.JWTMockWrapper{} - mockFF := &mock.FeatureFlagsMockWrapper{} - cmd := PreCommitCommand(mockJWT, mockFF) + cmd := PreCommitCommand(mockJWT) assert.NotNil(t, cmd) assert.Equal(t, "pre-commit", cmd.Use) @@ -52,65 +49,36 @@ func TestPreCommitCommand(t *testing.T) { func TestValidateLicense(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - allowSecretDetection int - allowEnterpriseSecrets int - aiEnabled int - wantErr bool + name string + allowSecretDetection int + aiEnabled int + wantErr bool }{ { - name: "scsLicensing V2 ON and Secret Detection allowed", - scsLicensingV2: true, - allowSecretDetection: 0, - allowEnterpriseSecrets: mock.EnterpriseSecretsDisabled, - wantErr: false, + name: "Secret Detection allowed", + allowSecretDetection: 0, + wantErr: false, }, { - name: "scsLicensing V2 ON and Secret Detection denied", - scsLicensingV2: true, - allowSecretDetection: mock.SecretDetectionDisabled, - allowEnterpriseSecrets: 0, - wantErr: true, + name: "Secret Detection denied", + allowSecretDetection: mock.SecretDetectionDisabled, + wantErr: true, }, { - name: "scsLicensing V2 OFF and Enterprise Secrets allowed", - scsLicensingV2: false, - allowSecretDetection: mock.SecretDetectionDisabled, - allowEnterpriseSecrets: 0, - wantErr: false, - }, - { - name: "scsLicensing V2 OFF and Enterprise Secrets denied", - scsLicensingV2: false, - allowSecretDetection: 0, - allowEnterpriseSecrets: mock.EnterpriseSecretsDisabled, - wantErr: true, - }, - { - name: "AI enabled and secrets license disabled", - aiEnabled: 1, - allowEnterpriseSecrets: mock.EnterpriseSecretsDisabled, - allowSecretDetection: mock.SecretDetectionDisabled, - wantErr: true, + name: "AI enabled and secrets license disabled", + aiEnabled: 1, + allowSecretDetection: mock.SecretDetectionDisabled, + wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - wrappers.ClearCache() - mockFF := &mock.FeatureFlagsMockWrapper{} - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - mockJWT := &mock.JWTMockWrapper{} mockJWT.AIEnabled = tt.aiEnabled - mockJWT.EnterpriseSecretsEnabled = tt.allowEnterpriseSecrets mockJWT.SecretDetectionEnabled = tt.allowSecretDetection - err := validateLicense(mockJWT, mockFF) + err := validateLicense(mockJWT) if tt.wantErr { assert.Error(t, err) @@ -124,8 +92,7 @@ func TestValidateLicense(t *testing.T) { func TestSecretsIgnoreCommand(t *testing.T) { mockJWT := &mock.JWTMockWrapper{} - mockFF := &mock.FeatureFlagsMockWrapper{} - cmd := secretsIgnoreCommand(mockJWT, mockFF) + cmd := secretsIgnoreCommand(mockJWT) assert.NotNil(t, cmd) resultIdsFlag := cmd.Flag("resultIds") diff --git a/internal/commands/pre_receive_test.go b/internal/commands/pre_receive_test.go index f141cd478..e6618c68c 100644 --- a/internal/commands/pre_receive_test.go +++ b/internal/commands/pre_receive_test.go @@ -11,8 +11,7 @@ import ( func TestPreReceiveCommand(t *testing.T) { mockJWT := &mock.JWTMockWrapper{} - mockFF := &mock.FeatureFlagsMockWrapper{} - cmd := PreReceiveCommand(mockJWT, mockFF) + cmd := PreReceiveCommand(mockJWT) assert.NotNil(t, cmd) assert.Equal(t, "pre-receive", cmd.Use) subCmds := cmd.Commands() diff --git a/internal/commands/result.go b/internal/commands/result.go index c3fc8c636..02a254e05 100644 --- a/internal/commands/result.go +++ b/internal/commands/result.go @@ -241,7 +241,7 @@ func NewResultsCommand( codeBashingCmd := resultCodeBashing(codeBashingWrapper) bflResultCmd := resultBflSubCommand(bflWrapper) exitCodeSubcommand := exitCodeSubCommand(scanWrapper) - riskManagementSubCommand := riskManagementSubCommand(riskManagementWrapper, featureFlagsWrapper) + riskManagementSubCommand := riskManagementSubCommand(riskManagementWrapper) resultCmd.AddCommand( showResultCmd, bflResultCmd, codeBashingCmd, exitCodeSubcommand, riskManagementSubCommand, ) @@ -266,8 +266,7 @@ func exitCodeSubCommand(scanWrapper wrappers.ScansWrapper) *cobra.Command { return exitCodeCmd } -func riskManagementSubCommand(riskManagement wrappers.RiskManagementWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper, -) *cobra.Command { +func riskManagementSubCommand(riskManagement wrappers.RiskManagementWrapper) *cobra.Command { riskManagementCmd := &cobra.Command{ Use: "risk-management", Short: "Show risk-management results of a project", @@ -277,7 +276,7 @@ func riskManagementSubCommand(riskManagement wrappers.RiskManagementWrapper, fea $ cx results risk-management --project-id --scan-id --limit (1-50, default: 50) `, ), - RunE: runRiskManagementCommand(riskManagement, featureFlagsWrapper), + RunE: runRiskManagementCommand(riskManagement), } riskManagementCmd.PersistentFlags().String(commonParams.ProjectIDFlag, "", "Project ID") @@ -397,19 +396,13 @@ func runGetExitCodeCommand(scanWrapper wrappers.ScansWrapper) func(cmd *cobra.Co } } -func runRiskManagementCommand(riskManagement wrappers.RiskManagementWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper, -) func(cmd *cobra.Command, args []string) error { +func runRiskManagementCommand(riskManagement wrappers.RiskManagementWrapper) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, args []string) error { projectID, _ := cmd.Flags().GetString(commonParams.ProjectIDFlag) scanID, _ := cmd.Flags().GetString(commonParams.ScanIDFlag) limit, _ := cmd.Flags().GetInt(commonParams.LimitFlag) - flagResponse, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, wrappers.RiskManagementEnabled) - ASPMEnabled := flagResponse.Status - if !ASPMEnabled { - return errors.Errorf("%s", "Risk management results are currently unavailable for your tenant.") - } results, err := getRiskManagementResults(riskManagement, projectID, scanID) if err != nil { return err diff --git a/internal/commands/result_test.go b/internal/commands/result_test.go index 660074995..cb6740548 100644 --- a/internal/commands/result_test.go +++ b/internal/commands/result_test.go @@ -1546,16 +1546,7 @@ func TestRiskManagementHelp(t *testing.T) { execCmdNilAssertion(t, "help", "results", "risk-management") } -func TestRiskManagement_ShouldFFBeFalseAndReturnError(t *testing.T) { - clearFlags() - err := execCmdNotNilAssertion(t, "results", "risk-management") - assert.Equal(t, err.Error(), "Risk management results are currently unavailable for your tenant.", "Expected error message") - -} - func TestRiskManagement(t *testing.T) { - clearFlags() - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.RiskManagementEnabled, Status: true} execCmdNilAssertion(t, "results", "risk-management") } diff --git a/internal/commands/root.go b/internal/commands/root.go index 3b968210e..7340f9116 100644 --- a/internal/commands/root.go +++ b/internal/commands/root.go @@ -253,7 +253,7 @@ func NewAstCLI( triageCmd := NewResultsPredicatesCommand(resultsPredicatesWrapper, featureFlagsWrapper, customStatesWrapper) chatCmd := NewChatCommand(chatWrapper, tenantWrapper) - hooksCmd := NewHooksCommand(jwtWrapper, featureFlagsWrapper, realTimeWrapper, telemetryWrapper) + hooksCmd := NewHooksCommand(jwtWrapper, realTimeWrapper, telemetryWrapper) telemetryCmd := NewTelemetryCommand(telemetryWrapper) // MCP server — directly uses the exported guardrail functions from agenthooks.go. diff --git a/internal/commands/scan.go b/internal/commands/scan.go index 1b7424124..26465e938 100644 --- a/internal/commands/scan.go +++ b/internal/commands/scan.go @@ -137,7 +137,6 @@ const ( ScsScorecardUnsupportedHostWarningMsg = "SCS scan warning: Unable to run Scorecard scanner due to unsupported repo host. Currently, Scorecard can only run on GitHub Cloud repos." gitCommitHistoryInvalidValueErrorMsg = "Invalid value for --git-commit-history. Valid values are: 'true' or 'false'" - gitCommitHistoryNotAvailableWarningMsg = "Secret Detection scan warning: --git-commit-history flag ignored because git commit history scanning is not available." gitCommitHistoryNotSelectedWarningMsg = "Secret Detection scan warning: --git-commit-history flag ignored because scs was not specified in scan types." gitCommitHistoryNotApplicableWarningMsg = "Secret Detection scan warning: --git-commit-history flag ignored because secret detection wasn't run on this scan." gitCommitHistoryNoGitRepositoryWarningMsg = "Secret Detection scan warning: No Git history found. Secret Detection will scan the working tree only." @@ -259,13 +258,13 @@ func NewScanCommand( scaRealtimeCmd := scarealtime.NewScaRealtimeCommand(scaRealTimeWrapper) - ossRealtimeCmd := scanOssRealtimeSubCommand(realtimeScannerWrapper, jwtWrapper, featureFlagsWrapper) + ossRealtimeCmd := scanOssRealtimeSubCommand(realtimeScannerWrapper, jwtWrapper) - containersRealtimeCmd := scanContainersRealtimeSubCommand(realtimeScannerWrapper, jwtWrapper, featureFlagsWrapper) + containersRealtimeCmd := scanContainersRealtimeSubCommand(realtimeScannerWrapper, jwtWrapper) - secretsRealtimeCmd := scanSecretsRealtimeSubCommand(jwtWrapper, featureFlagsWrapper) + secretsRealtimeCmd := scanSecretsRealtimeSubCommand(jwtWrapper) - iacRealtimeCmd := scanIacRealtimeSubCommand(jwtWrapper, featureFlagsWrapper) + iacRealtimeCmd := scanIacRealtimeSubCommand(jwtWrapper) addFormatFlagToMultipleCommands( []*cobra.Command{listScansCmd, showScanCmd, workflowScanCmd}, @@ -512,7 +511,6 @@ func scanASCASubCommand(jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrap func scanOssRealtimeSubCommand( realtimeScannerWrapper wrappers.RealtimeScannerWrapper, jwtWrapper wrappers.JWTWrapper, - featureFlagsWrapper wrappers.FeatureFlagsWrapper, ) *cobra.Command { scanOssRealtimeCmd := &cobra.Command{ Hidden: true, @@ -531,7 +529,7 @@ func scanOssRealtimeSubCommand( `, ), }, - RunE: RunScanOssRealtimeCommand(realtimeScannerWrapper, jwtWrapper, featureFlagsWrapper), + RunE: RunScanOssRealtimeCommand(realtimeScannerWrapper, jwtWrapper), } scanOssRealtimeCmd.PersistentFlags().StringP( @@ -552,7 +550,6 @@ func scanOssRealtimeSubCommand( func scanIacRealtimeSubCommand( jwtWrapper wrappers.JWTWrapper, - featureFlagsWrapper wrappers.FeatureFlagsWrapper, ) *cobra.Command { scanIacRealtimeCmd := &cobra.Command{ Hidden: true, @@ -571,7 +568,7 @@ func scanIacRealtimeSubCommand( `, ), }, - RunE: RunScanIacRealtimeCommand(jwtWrapper, featureFlagsWrapper), + RunE: RunScanIacRealtimeCommand(jwtWrapper), } scanIacRealtimeCmd.PersistentFlags().StringP( @@ -596,7 +593,7 @@ func scanIacRealtimeSubCommand( return scanIacRealtimeCmd } -func scanContainersRealtimeSubCommand(realtimeScannerWrapper wrappers.RealtimeScannerWrapper, jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) *cobra.Command { +func scanContainersRealtimeSubCommand(realtimeScannerWrapper wrappers.RealtimeScannerWrapper, jwtWrapper wrappers.JWTWrapper) *cobra.Command { scanContainersRealtimeCmd := &cobra.Command{ Hidden: true, Use: "containers-realtime", @@ -615,7 +612,7 @@ func scanContainersRealtimeSubCommand(realtimeScannerWrapper wrappers.RealtimeSc `, ), }, - RunE: RunScanContainersRealtimeCommand(realtimeScannerWrapper, jwtWrapper, featureFlagsWrapper), + RunE: RunScanContainersRealtimeCommand(realtimeScannerWrapper, jwtWrapper), } scanContainersRealtimeCmd.PersistentFlags().StringP( @@ -631,7 +628,6 @@ func scanContainersRealtimeSubCommand(realtimeScannerWrapper wrappers.RealtimeSc func scanSecretsRealtimeSubCommand( jwtWrapper wrappers.JWTWrapper, - featureFlagsWrapper wrappers.FeatureFlagsWrapper, ) *cobra.Command { scanSecretsRealtimeCmd := &cobra.Command{ Hidden: true, @@ -647,7 +643,7 @@ func scanSecretsRealtimeSubCommand( https://docs.checkmarx.com/en/34965-68625-checkmarx-one-cli-commands.html `), }, - RunE: RunScanSecretsRealtimeCommand(jwtWrapper, featureFlagsWrapper), + RunE: RunScanSecretsRealtimeCommand(jwtWrapper), } scanSecretsRealtimeCmd.Flags().StringP(commonParams.SourcesFlag, "s", "", "Path to the file to scan") @@ -1060,14 +1056,14 @@ func setupScanTypeProjectAndConfig( } var SCSConfig, scsErr = addSCSScan(cmd, resubmitConfig, userAllowedEngines[commonParams.RepositoryHealthType], - userAllowedEngines[commonParams.SecretDetectionType], userAllowedEngines[commonParams.EnterpriseSecretsType], featureFlagsWrapper) + userAllowedEngines[commonParams.SecretDetectionType]) if scsErr != nil { return scsErr } else if SCSConfig != nil { configArr = append(configArr, SCSConfig) } - var aiscConfig = addAiscScan(featureFlagsWrapper, resubmitConfig) + var aiscConfig = addAiscScan(resubmitConfig) if aiscConfig != nil { configArr = append(configArr, aiscConfig) } @@ -1207,10 +1203,9 @@ func overrideSastConfigValue(sastFastScanChanged, sastIncrementalChanged, sastBa } } -func addAiscScan(featureFlagWrapper wrappers.FeatureFlagsWrapper, resubmitConfig []wrappers.Config) map[string]interface{} { +func addAiscScan(resubmitConfig []wrappers.Config) map[string]interface{} { // Add the aisc resubmit config, currently no value is passed in config - aiSupplyChainGAEnabled, _ := wrappers.GetSpecificFeatureFlag(featureFlagWrapper, wrappers.AISupplyChainGAEnabled) - if scanTypeEnabled(commonParams.AiscType) && aiSupplyChainGAEnabled.Status { + if scanTypeEnabled(commonParams.AiscType) { aiscMapConfig := make(map[string]interface{}) aiscConfig := wrappers.AISCConfig{} aiscMapConfig[resultsMapType] = commonParams.AiscType @@ -1468,14 +1463,12 @@ func isScorecardRunnable(isScsEnginesFlagSet, scsScorecardSelected bool, scsRepo } func addSCSScan(cmd *cobra.Command, resubmitConfig []wrappers.Config, hasRepositoryHealthLicense, - hasSecretDetectionLicense, hasEnterpriseSecretsLicense bool, featureFlagsWrapper wrappers.FeatureFlagsWrapper) (map[string]interface{}, error) { - scsLicensingV2Flag, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, wrappers.ScsLicensingV2Enabled) - scsEnabled := isScsEnabled(scsLicensingV2Flag.Status) - if !scsEnabled { + hasSecretDetectionLicense bool) (map[string]interface{}, error) { + if !isScsEnabled() { return nil, nil } - scsScorecardAllowed := isScsScorecardAllowed(scsLicensingV2Flag.Status, hasRepositoryHealthLicense) - scsSecretDetectionAllowed := isScsSecretDetectionAllowed(scsLicensingV2Flag.Status, hasSecretDetectionLicense, hasEnterpriseSecretsLicense) + scsScorecardAllowed := hasRepositoryHealthLicense + scsSecretDetectionAllowed := hasSecretDetectionLicense if !scsScorecardAllowed && !scsSecretDetectionAllowed { return nil, nil } @@ -1507,9 +1500,8 @@ func addSCSScan(cmd *cobra.Command, resubmitConfig []wrappers.Config, hasReposit if scsSecretDetectionSelected && scsSecretDetectionAllowed { scsConfig.Twoms = trueString - // Set git commit history based on FF and validations - commitHistoryFlag, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, wrappers.SscsCommitHistoryEnabled) - if gitCommitHistoryValue := getGitCommitHistoryValue(cmd, commitHistoryFlag.Status); gitCommitHistoryValue != "" { + // Set git commit history based on validations + if gitCommitHistoryValue := getGitCommitHistoryValue(cmd); gitCommitHistoryValue != "" { scsConfig.GitCommitHistory = gitCommitHistoryValue } } @@ -1537,33 +1529,14 @@ func addSCSScan(cmd *cobra.Command, resubmitConfig []wrappers.Config, hasReposit return scsMapConfig, nil } -func isScsEnabled(scsLicensingV2 bool) bool { - if scsLicensingV2 { - return scanTypeEnabled(commonParams.ScsType) || scanTypeEnabled(commonParams.SecretDetectionType) || - scanTypeEnabled(commonParams.RepositoryHealthType) - } - return scanTypeEnabled(commonParams.ScsType) -} - -func isScsScorecardAllowed(scsLicensingV2, hasRepositoryHealthLicense bool) bool { - if scsLicensingV2 { - return hasRepositoryHealthLicense - } - return true -} - -func isScsSecretDetectionAllowed(scsLicensingV2, hasSecretDetectionLicense, hasEnterpriseSecretsLicense bool) bool { - if scsLicensingV2 { - return hasSecretDetectionLicense - } - return hasEnterpriseSecretsLicense +func isScsEnabled() bool { + return scanTypeEnabled(commonParams.ScsType) || scanTypeEnabled(commonParams.SecretDetectionType) || + scanTypeEnabled(commonParams.RepositoryHealthType) } func validateScanTypes(cmd *cobra.Command, jwtWrapper wrappers.JWTWrapper, featureFlagsWrapper wrappers.FeatureFlagsWrapper) error { var scanTypes []string - scsLicensingV2Flag, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, wrappers.ScsLicensingV2Enabled) - allowedEngines, err := jwtWrapper.GetAllowedEngines(featureFlagsWrapper) logger.PrintIfVerbose(fmt.Sprintf("Allowed scan types: %v", allowedEngines)) @@ -1596,7 +1569,7 @@ func validateScanTypes(cmd *cobra.Command, jwtWrapper wrappers.JWTWrapper, featu } for _, scanType := range scanTypes { - if scanType == commonParams.ScsType && scsLicensingV2Flag.Status { + if scanType == commonParams.ScsType { // the SCS scan type is a special case because it contains two engines. // Before the new licensing model, the main license was named "scs". // Licenses are now separated for each engine, so this validation no longer makes sense. @@ -1612,7 +1585,7 @@ func validateScanTypes(cmd *cobra.Command, jwtWrapper wrappers.JWTWrapper, featu userSCSScanTypes, _ := cmd.Flags().GetString(commonParams.SCSEnginesFlag) if slices.Contains(scanTypes, commonParams.ScsType) { - err = validateSCSEngines(allowedEngines, userSCSScanTypes, scsLicensingV2Flag.Status) + err = validateSCSEngines(allowedEngines, userSCSScanTypes) if err != nil { return err } @@ -1637,21 +1610,17 @@ func validateScanTypes(cmd *cobra.Command, jwtWrapper wrappers.JWTWrapper, featu return nil } -func validateSCSEngines(allowedEngines map[string]bool, userSCSScanTypes string, scsLicensingV2 bool) error { +func validateSCSEngines(allowedEngines map[string]bool, userSCSScanTypes string) error { licensesAvailable := reflect.ValueOf(allowedEngines).MapKeys() scsScanTypes := strings.Split(userSCSScanTypes, ",") - if scsLicensingV2 { - secretDetectionAllowed := allowedEngines[commonParams.SecretDetectionType] - repositoryHeatlhAllowed := allowedEngines[commonParams.RepositoryHealthType] - if userSCSScanTypes == "" && !secretDetectionAllowed && !repositoryHeatlhAllowed { - return errors.Errorf(engineScsNotAllowed, licensesAvailable) - } else if slices.Contains(scsScanTypes, ScsSecretDetectionType) && !secretDetectionAllowed { - return errors.Errorf(engineNotAllowed, commonParams.SecretDetectionType, commonParams.SecretDetectionType, licensesAvailable) - } else if slices.Contains(scsScanTypes, ScsScoreCardType) && !repositoryHeatlhAllowed { - return errors.Errorf(engineNotAllowed, commonParams.RepositoryHealthType, commonParams.RepositoryHealthType, licensesAvailable) - } - } else if slices.Contains(scsScanTypes, ScsSecretDetectionType) && !allowedEngines[commonParams.EnterpriseSecretsType] { - return errors.Errorf(engineNotAllowed, ScsSecretDetectionType, ScsSecretDetectionType, licensesAvailable) + secretDetectionAllowed := allowedEngines[commonParams.SecretDetectionType] + repositoryHeatlhAllowed := allowedEngines[commonParams.RepositoryHealthType] + if userSCSScanTypes == "" && !secretDetectionAllowed && !repositoryHeatlhAllowed { + return errors.Errorf(engineScsNotAllowed, licensesAvailable) + } else if slices.Contains(scsScanTypes, ScsSecretDetectionType) && !secretDetectionAllowed { + return errors.Errorf(engineNotAllowed, commonParams.SecretDetectionType, commonParams.SecretDetectionType, licensesAvailable) + } else if slices.Contains(scsScanTypes, ScsScoreCardType) && !repositoryHeatlhAllowed { + return errors.Errorf(engineNotAllowed, commonParams.RepositoryHealthType, commonParams.RepositoryHealthType, licensesAvailable) } return nil } @@ -2579,8 +2548,7 @@ func uploadZip(uploadsWrapper wrappers.UploadsWrapper, zipFilePath string, unzip } logger.PrintIfVerbose(fmt.Sprintf("Zip size before upload: %.2fMB\n", float64(fileInfo.Size())/mbBytes)) - flagResponse, _ := featureFlagsWrapper.GetSpecificFlag(wrappers.IncreaseFileUploadLimit) - if flagResponse.Status && fileInfo.Size() > MaxSizeBytes { + if fileInfo.Size() > MaxSizeBytes { logger.PrintIfVerbose("Uploading source code in multiple parts.") preSignedURL, zipFilePathErr = uploadsWrapper.UploadFileInMultipart(zipFilePath, featureFlagsWrapper) } else { @@ -4410,13 +4378,8 @@ func validateGitCommitHistoryFlag(cmd *cobra.Command) error { return nil } -// getGitCommitHistoryValue determines the value for git commit history config based on flag and validations -func getGitCommitHistoryValue(cmd *cobra.Command, isFeatureFlagEnabled bool) string { - if !isFeatureFlagEnabled { - fmt.Println(gitCommitHistoryNotAvailableWarningMsg) - return "" - } - +// getGitCommitHistoryValue determines the value for git commit history config based on the flag and validations +func getGitCommitHistoryValue(cmd *cobra.Command) string { gitCommitHistory, _ := cmd.Flags().GetString(commonParams.GitCommitHistoryFlag) gitCommitHistoryValue := strings.ToLower(gitCommitHistory) diff --git a/internal/commands/scan_test.go b/internal/commands/scan_test.go index 76037be06..199a82992 100644 --- a/internal/commands/scan_test.go +++ b/internal/commands/scan_test.go @@ -871,23 +871,16 @@ func TestAddScaScan(t *testing.T) { } } -func TestAddAiscScan_WhenAiscEnabledAndFeatureFlagEnabled_ShouldReturnConfig(t *testing.T) { - wrappers.ClearCache() +func TestAddAiscScan_WhenAiscEnabled_ShouldReturnConfig(t *testing.T) { var resubmitConfig []wrappers.Config - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.AISupplyChainGAEnabled, - Status: true, - } - defer clearFlags() originalScanTypes := actualScanTypes actualScanTypes = commonParams.SastType + "," + commonParams.KicsType + "," + commonParams.ScaType + "," + commonParams.AiscType defer func() { actualScanTypes = originalScanTypes }() - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - result := addAiscScan(featureFlagsWrapper, resubmitConfig) + result := addAiscScan(resubmitConfig) - assert.Assert(t, result != nil, "Expected non-nil result when AISC is enabled and feature flag is true") + assert.Assert(t, result != nil, "Expected non-nil result when AISC is enabled") assert.Assert(t, result[resultsMapType] == commonParams.AiscType, "Expected type '%s', got '%v'", commonParams.AiscType, result[resultsMapType]) @@ -899,76 +892,38 @@ func TestAddAiscScan_WhenAiscEnabledAndFeatureFlagEnabled_ShouldReturnConfig(t * } func TestAddAiscScan_WhenAiscDisabled_ShouldReturnNil(t *testing.T) { - wrappers.ClearCache() var resubmitConfig []wrappers.Config - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.AISupplyChainGAEnabled, - Status: true, - } - defer clearFlags() originalScanTypes := actualScanTypes actualScanTypes = commonParams.SastType + "," + commonParams.KicsType + "," + commonParams.ScaType defer func() { actualScanTypes = originalScanTypes }() - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - result := addAiscScan(featureFlagsWrapper, resubmitConfig) + result := addAiscScan(resubmitConfig) assert.Assert(t, result == nil, "Expected nil result when AISC is disabled in scan types") } -func TestAddAiscScan_WhenFeatureFlagDisabled_ShouldReturnNil(t *testing.T) { - wrappers.ClearCache() - var resubmitConfig []wrappers.Config - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.AISupplyChainGAEnabled, - Status: false, - } - defer clearFlags() - originalScanTypes := actualScanTypes - actualScanTypes = commonParams.SastType + "," + commonParams.KicsType + "," + commonParams.ScaType + "," + commonParams.AiscType - defer func() { actualScanTypes = originalScanTypes }() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - result := addAiscScan(featureFlagsWrapper, resubmitConfig) - assert.Assert(t, result == nil, "Expected nil result when feature flag is disabled") -} - func TestAddAiscScan_WithResubmitConfig_ShouldHandleCorrectly(t *testing.T) { - wrappers.ClearCache() resubmitConfig := []wrappers.Config{ { Type: commonParams.AiscType, Value: map[string]interface{}{}, }, } - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.AISupplyChainGAEnabled, - Status: true, - } - defer clearFlags() originalScanTypes := actualScanTypes actualScanTypes = commonParams.SastType + "," + commonParams.KicsType + "," + commonParams.ScaType + "," + commonParams.AiscType defer func() { actualScanTypes = originalScanTypes }() - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - result := addAiscScan(featureFlagsWrapper, resubmitConfig) + result := addAiscScan(resubmitConfig) assert.Assert(t, result != nil, "Expected non-nil result with resubmit config") assert.Assert(t, result[resultsMapType] == commonParams.AiscType, "Expected type '%s'", commonParams.AiscType) } func TestAddAiscScan_ConfigStructure_ShouldHaveCorrectFormat(t *testing.T) { - wrappers.ClearCache() var resubmitConfig []wrappers.Config - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.AISupplyChainGAEnabled, - Status: true, - } - defer clearFlags() originalScanTypes := actualScanTypes actualScanTypes = commonParams.SastType + "," + commonParams.KicsType + "," + commonParams.ScaType + "," + commonParams.AiscType defer func() { actualScanTypes = originalScanTypes }() - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - result := addAiscScan(featureFlagsWrapper, resubmitConfig) + result := addAiscScan(resubmitConfig) expectedMapConfig := make(map[string]interface{}) expectedMapConfig[resultsMapType] = commonParams.AiscType @@ -983,25 +938,14 @@ func TestAddAiscScan_ConfigStructure_ShouldHaveCorrectFormat(t *testing.T) { func TestAddSCSScan_ResubmitWithoutScorecardFlags_ShouldPass(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1032,15 +976,8 @@ func TestAddSCSScan_ResubmitWithoutScorecardFlags_ShouldPass(t *testing.T) { }, } - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) expectedConfig := wrappers.SCSConfig{ Twoms: trueString, @@ -1060,25 +997,14 @@ func TestAddSCSScan_ResubmitWithoutScorecardFlags_ShouldPass(t *testing.T) { func TestAddSCSScan_ResubmitWithScorecardFlags_ShouldPass(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1109,15 +1035,8 @@ func TestAddSCSScan_ResubmitWithScorecardFlags_ShouldPass(t *testing.T) { }, } - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) expectedConfig := wrappers.SCSConfig{ Twoms: "true", @@ -1377,25 +1296,14 @@ func TestCreateScan_WithSCSScorecard_ShouldFail(t *testing.T) { func TestAddSCSScan_WithSCSSecretDetectionAndScorecard_scsMapHasBoth(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1416,15 +1324,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecard_scsMapHasBoth(t *testing. _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyRepo) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) scsConfig := wrappers.SCSConfig{ Twoms: "true", @@ -1445,25 +1346,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecard_scsMapHasBoth(t *testing. func TestAddSCSScan_WithoutSCSSecretDetection_scsMapNoSecretDetection(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: false, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: false, }, } @@ -1484,15 +1374,8 @@ func TestAddSCSScan_WithoutSCSSecretDetection_scsMapNoSecretDetection(t *testing _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyRepo) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) scsConfig := wrappers.SCSConfig{ Twoms: "", @@ -1513,25 +1396,14 @@ func TestAddSCSScan_WithoutSCSSecretDetection_scsMapNoSecretDetection(t *testing func TestAddSCSScan_WithSCSSecretDetection_scsMapHasSecretDetection(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1548,15 +1420,8 @@ func TestAddSCSScan_WithSCSSecretDetection_scsMapHasSecretDetection(t *testing.T _ = cmdCommand.Execute() _ = cmdCommand.Flags().Set(commonParams.SCSEnginesFlag, "secret-detection") - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) scsConfig := wrappers.SCSConfig{ Twoms: "true", @@ -1574,25 +1439,14 @@ func TestAddSCSScan_WithSCSSecretDetection_scsMapHasSecretDetection(t *testing.T func TestAddSCSScan_WithSCSSecretDetectionAndGitCommitHistoryFlag_scsMapHasSecretDetection(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1621,21 +1475,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndGitCommitHistoryFlag_scsMapHasSecre _ = cmdCommand.Flags().Set(commonParams.ScanTypes, "scs") _ = cmdCommand.Flags().Set(commonParams.SourcesFlag, tempDir) - mock.Flags = wrappers.FeatureFlagsResponseModel{ - { - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - }, - { - Name: wrappers.SscsCommitHistoryEnabled, - Status: true, - }, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) scsConfig := wrappers.SCSConfig{ Twoms: "true", @@ -1654,25 +1495,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndGitCommitHistoryFlag_scsMapHasSecre func TestAddSCSScan_WithSCSSecretDetectionAndScorecardWithScanTypesAndNoScorecardFlags_scsMapHasSecretDetection(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1695,15 +1525,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardWithScanTypesAndNoScorecar _ = cmdCommand.Execute() _ = cmdCommand.Flags().Set(commonParams.ScanTypeFlag, "scs") - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) scsConfig := wrappers.SCSConfig{ Twoms: "true", @@ -1737,25 +1560,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardWithScanTypesAndNoScorecar func TestAddSCSScan_WithSCSSecretDetectionAndWithoutScanTypes_scsMapHasSecretDetection(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: false, + hasSecretDetectionLicense: true, }, } @@ -1769,15 +1581,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndWithoutScanTypes_scsMapHasSecretDet Long: `Scan a project`, } - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) scsConfig := wrappers.SCSConfig{ Twoms: "true", @@ -1796,25 +1601,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndWithoutScanTypes_scsMapHasSecretDet func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepo_scsMapHasBoth(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1841,15 +1635,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepo_scsMap _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyShortenedGithubRepo) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) // Close the writer to signal that we are done capturing the output w.Close() @@ -1885,25 +1672,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepo_scsMap func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepoWithTokenInURL_scsMapHasBoth(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -1930,15 +1706,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepoWithTok _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyShortenedRepoWithToken) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) // Close the writer to signal that we are done capturing the output w.Close() @@ -1974,25 +1743,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepoWithTok func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGithubRepoWithTokenInURL_scsMapHasBoth(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -2019,15 +1777,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGithubRepoWithTokenInURL_s _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyRepoWithToken) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) // Close the writer to signal that we are done capturing the output w.Close() @@ -2063,25 +1814,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGithubRepoWithTokenInURL_s func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGithubRepoWithTokenAndUsernameInURL_scsMapHasBoth(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -2108,15 +1848,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGithubRepoWithTokenAndUser _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyRepoWithTokenAndUsername) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) // Close the writer to signal that we are done capturing the output w.Close() @@ -2152,25 +1885,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGithubRepoWithTokenAndUser func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepoWithTokenAndUsernameInURL_scsMapHasBoth(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -2197,15 +1919,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepoWithTok _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyShortenedRepoWithTokenAndUsername) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) // Close the writer to signal that we are done capturing the output w.Close() @@ -2241,25 +1956,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardShortenedGithubRepoWithTok func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGitLabRepo_scsMapHasSecretDetection(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -2286,15 +1990,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGitLabRepo_scsMapHasSecret _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummyGitlabRepo) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) // Close the writer to signal that we are done capturing the output w.Close() @@ -2330,25 +2027,14 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGitLabRepo_scsMapHasSecret func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGitSSHRepo_scsMapHasSecretDetection(t *testing.T) { tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool + name string + hasRepositoryHealthLicense bool + hasSecretDetectionLicense bool }{ { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - hasRepositoryHealthLicense: false, - hasSecretDetectionLicense: false, - hasEnterpriseSecretsLicense: true, - }, - { - name: "scsLicensingV2 enabled", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - hasSecretDetectionLicense: true, - hasEnterpriseSecretsLicense: false, + name: "licenses available", + hasRepositoryHealthLicense: true, + hasSecretDetectionLicense: true, }, } @@ -2375,15 +2061,8 @@ func TestAddSCSScan_WithSCSSecretDetectionAndScorecardGitSSHRepo_scsMapHasSecret _ = cmdCommand.Flags().Set(commonParams.SCSRepoTokenFlag, dummyToken) _ = cmdCommand.Flags().Set(commonParams.SCSRepoURLFlag, dummySSHRepo) - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() - - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} result, _ := addSCSScan(cmdCommand, resubmitConfig, - tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense, featureFlagsWrapper) + tt.hasRepositoryHealthLicense, tt.hasSecretDetectionLicense) // Close the writer to signal that we are done capturing the output w.Close() @@ -3903,7 +3582,6 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes string userSCSScanTypes string allowedEngines map[string]bool - scsLicensingV2 bool expectedError string }{ { @@ -3911,7 +3589,6 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes: "scs", userSCSScanTypes: "", allowedEngines: map[string]bool{"repository-health": false, "secret-detection": false}, - scsLicensingV2: true, expectedError: "This requires either the \"repository‑health\" or the \"secret‑detection\" package license", }, { @@ -3919,7 +3596,6 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes: "scs", userSCSScanTypes: "", allowedEngines: map[string]bool{"repository-health": true, "secret-detection": false}, - scsLicensingV2: true, expectedError: "", }, { @@ -3927,7 +3603,6 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes: "scs", userSCSScanTypes: "", allowedEngines: map[string]bool{"repository-health": false, "secret-detection": true}, - scsLicensingV2: true, expectedError: "", }, { @@ -3935,55 +3610,13 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes: "scs", userSCSScanTypes: "", allowedEngines: map[string]bool{"repository-health": true, "secret-detection": true}, - scsLicensingV2: true, - expectedError: "", - }, - { - name: "no specific micro engines selected with no licenses available using old sscs licensing", - userScanTypes: "scs", - userSCSScanTypes: "", - allowedEngines: map[string]bool{"scs": false, "enterprise-secrets": false}, - scsLicensingV2: false, - expectedError: "It looks like the \"scs\" scan type does not exist or", - }, - { - name: "no specific micro engines selected with scs license available using old sscs licensing", - userScanTypes: "scs", - userSCSScanTypes: "", - allowedEngines: map[string]bool{"scs": true, "enterprise-secrets": false}, - scsLicensingV2: false, - expectedError: "", - }, - { - name: "no specific micro engines selected with all licenses available using old sscs licensing", - userScanTypes: "scs", - userSCSScanTypes: "", - allowedEngines: map[string]bool{"scs": true, "enterprise-secrets": true}, - scsLicensingV2: false, expectedError: "", }, - { - name: "scorecard and secret-detection selected with no licenses available using old sscs licensing", - userScanTypes: "scs", - userSCSScanTypes: "scorecard,secret-detection", - allowedEngines: map[string]bool{"scs": false, "enterprise-secrets": false}, - scsLicensingV2: false, - expectedError: "It looks like the \"scs\" scan type does not exist or", - }, { name: "scorecard and secret-detection selected with no licenses available using new sscs licensing", userScanTypes: "scs", userSCSScanTypes: "scorecard,secret-detection", allowedEngines: map[string]bool{"repository-health": false, "secret-detection": false}, - scsLicensingV2: true, - expectedError: "It looks like the \"secret-detection\" scan type does not exist or", - }, - { - name: "secret-detection selected with SCS license available, secret-detection not available using old sscs licensing", - userScanTypes: "scs", - userSCSScanTypes: "secret-detection", - allowedEngines: map[string]bool{"scs": true, "enterprise-secrets": false}, - scsLicensingV2: false, expectedError: "It looks like the \"secret-detection\" scan type does not exist or", }, { @@ -3991,7 +3624,6 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes: "scs", userSCSScanTypes: "secret-detection", allowedEngines: map[string]bool{"repository-health": true, "secret-detection": false}, - scsLicensingV2: true, expectedError: "It looks like the \"secret-detection\" scan type does not exist or", }, { @@ -3999,23 +3631,13 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes: "scs", userSCSScanTypes: "scorecard", allowedEngines: map[string]bool{"repository-health": false, "secret-detection": true}, - scsLicensingV2: true, expectedError: "It looks like the \"repository-health\" scan type does not exist or", }, - { - name: "secret-detection selected with all licenses available using old sscs licensing", - userScanTypes: "scs", - userSCSScanTypes: "secret-detection", - allowedEngines: map[string]bool{"scs": true, "enterprise-secrets": true}, - scsLicensingV2: false, - expectedError: "", - }, { name: "secret-detection selected with secret-detection license available using new sscs licensing", userScanTypes: "scs", userSCSScanTypes: "secret-detection", allowedEngines: map[string]bool{"repository-health": false, "secret-detection": true}, - scsLicensingV2: true, expectedError: "", }, { @@ -4023,7 +3645,6 @@ func TestValidateScanTypes(t *testing.T) { userScanTypes: "scs", userSCSScanTypes: "scorecard", allowedEngines: map[string]bool{"repository-health": true, "secret-detection": false}, - scsLicensingV2: true, expectedError: "", }, } @@ -4031,11 +3652,6 @@ func TestValidateScanTypes(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { wrappers.ClearCache() - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.ScsLicensingV2Enabled, - Status: tt.scsLicensingV2, - } - defer clearFlags() cmd := &cobra.Command{} cmd.Flags().String(commonParams.ScanTypes, tt.userScanTypes, "") @@ -4058,82 +3674,6 @@ func TestValidateScanTypes(t *testing.T) { } } -func TestIsScsScorecardAllowed(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - hasRepositoryHealthLicense bool - expectedAllowed bool - }{ - { - name: "scsLicensingV2 disabled", - scsLicensingV2: false, - expectedAllowed: true, - }, - { - name: "scsLicensingV2 enabled and has repository health license", - scsLicensingV2: true, - hasRepositoryHealthLicense: true, - expectedAllowed: true, - }, - { - name: "scsLicensingV2 enabled and does not have repository health license", - scsLicensingV2: true, - hasRepositoryHealthLicense: false, - expectedAllowed: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualAllowed := isScsScorecardAllowed(tt.scsLicensingV2, tt.hasRepositoryHealthLicense) - assert.Equal(t, tt.expectedAllowed, actualAllowed) - }) - } -} - -func TestIsScsSecretDetectionAllowed(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - hasSecretDetectionLicense bool - hasEnterpriseSecretsLicense bool - expectedAllowed bool - }{ - { - name: "scsLicensingV2 disabled and has enterprise secrets license", - scsLicensingV2: false, - hasEnterpriseSecretsLicense: true, - expectedAllowed: true, - }, - { - name: "scsLicensingV2 disabled but does not have enterprise secrets license", - scsLicensingV2: false, - hasEnterpriseSecretsLicense: false, - expectedAllowed: false, - }, - { - name: "scsLicensingV2 enabled and has secret detection license", - scsLicensingV2: true, - hasSecretDetectionLicense: true, - expectedAllowed: true, - }, - { - name: "scsLicensingV2 enabled and does not have secret detection license", - scsLicensingV2: true, - hasSecretDetectionLicense: false, - expectedAllowed: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualAllowed := isScsSecretDetectionAllowed(tt.scsLicensingV2, tt.hasSecretDetectionLicense, tt.hasEnterpriseSecretsLicense) - assert.Equal(t, tt.expectedAllowed, actualAllowed) - }) - } -} - func TestCreateScanWith_ScaResolver_Source_as_Zip(t *testing.T) { clearFlags() baseArgs := []string{ @@ -4913,12 +4453,11 @@ func TestEnforceLocalResolutionForTarFiles_Integration(t *testing.T) { } } -func TestUploadZip_AsMultipartUpload_when_FF_Enable_ZIP_Exceeds_5GB(t *testing.T) { +func TestUploadZip_AsMultipartUpload_when_ZIP_Exceeds_5GB(t *testing.T) { // Simulate a file size > 5GB by setting MaxSizeBytes to less than actual size MaxSizeBytes = 1 defer func() { MaxSizeBytes = 5 * 1024 * 1024 * 1024 }() // Reset after test uploadWrapper := mock.UploadsMockWrapper{} - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.IncreaseFileUploadLimit, Status: true} featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} url, zipPath, err := uploadZip(&uploadWrapper, "data/sources.zip", false, true, featureFlagsWrapper) assert.NilError(t, err) @@ -4926,37 +4465,8 @@ func TestUploadZip_AsMultipartUpload_when_FF_Enable_ZIP_Exceeds_5GB(t *testing.T assert.Equal(t, url, "multiPart/path/to/nowhere") } -func TestUploadZip_AsMultipartUpload_when_FF_Disable_ZIP_Exceeds_5GB(t *testing.T) { - fileInfo, err := os.Stat("data/sources.zip") - if err != nil { - t.Fatalf("Failed to close zip file: %v", err) - } - // Simulate a file size > 5GB by setting MaxSizeBytes to less than actual size - MaxSizeBytes = fileInfo.Size() - 1 - defer func() { MaxSizeBytes = 5 * 1024 * 1024 * 1024 }() // Reset after test - - uploadWrapper := mock.UploadsMockWrapper{} - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.IncreaseFileUploadLimit, Status: false} - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - url, zipPath, err := uploadZip(&uploadWrapper, "data/sources.zip", false, true, featureFlagsWrapper) - assert.NilError(t, err) - assert.Equal(t, zipPath, "") - assert.Equal(t, url, "singlePart/path/to/nowhere") -} - -func TestUploadZip_AsMultipartUpload_when_FF_Enable_ZIP_LessThan_5GB(t *testing.T) { - uploadWrapper := mock.UploadsMockWrapper{} - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.IncreaseFileUploadLimit, Status: true} - featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} - url, zipPath, err := uploadZip(&uploadWrapper, "data/sources.zip", false, true, featureFlagsWrapper) - assert.NilError(t, err) - assert.Equal(t, zipPath, "") - assert.Equal(t, url, "singlePart/path/to/nowhere") -} - -func TestUploadZip_AsMultipartUpload_when_FF_Disable_ZIP_LessThan_5GB(t *testing.T) { +func TestUploadZip_AsSinglePartUpload_when_ZIP_LessThan_5GB(t *testing.T) { uploadWrapper := mock.UploadsMockWrapper{} - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.IncreaseFileUploadLimit, Status: false} featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} url, zipPath, err := uploadZip(&uploadWrapper, "data/sources.zip", false, true, featureFlagsWrapper) assert.NilError(t, err) @@ -4964,7 +4474,7 @@ func TestUploadZip_AsMultipartUpload_when_FF_Disable_ZIP_LessThan_5GB(t *testing assert.Equal(t, url, "singlePart/path/to/nowhere") } -func TestUploadZip_AsMultipartUpload_when_FF_Enable_ZIP_Exceeds_5GB_Error(t *testing.T) { +func TestUploadZip_AsMultipartUpload_when_ZIP_Exceeds_5GB_Error(t *testing.T) { // Create a temporary zip file dir := t.TempDir() zipPathTemp := filepath.Join(dir, "failureCaseLarge.zip") @@ -4998,7 +4508,6 @@ func TestUploadZip_AsMultipartUpload_when_FF_Enable_ZIP_Exceeds_5GB_Error(t *tes defer func() { MaxSizeBytes = 5 * 1024 * 1024 * 1024 }() // uploadWrapper := mock.UploadsMockWrapper{} - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.IncreaseFileUploadLimit, Status: true} featureFlagsWrapper := &mock.FeatureFlagsMockWrapper{} _, zipPath, err := uploadZip(&uploadWrapper, zipPathTemp, false, true, featureFlagsWrapper) assert.Assert(t, err != nil) @@ -5079,7 +4588,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes string scsEngines string source string - ffEnabled bool expectedValue string }{ { @@ -5088,7 +4596,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: tempDir, - ffEnabled: true, expectedValue: "true", }, { @@ -5097,7 +4604,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: tempDir, - ffEnabled: true, expectedValue: "false", }, { @@ -5106,7 +4612,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: tempDirWithSubGit, - ffEnabled: true, expectedValue: "true", }, { @@ -5115,7 +4620,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection,scorecard", source: tempDir, - ffEnabled: true, expectedValue: "true", }, { @@ -5124,7 +4628,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection,scorecard", source: tempDir, - ffEnabled: true, expectedValue: "false", }, { @@ -5133,7 +4636,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: "https://github.com/user/repo.git", - ffEnabled: true, expectedValue: "true", }, { @@ -5142,7 +4644,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: "https://gitlab.com/user/repo.git", - ffEnabled: true, expectedValue: "true", }, { @@ -5151,7 +4652,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: "git@github.com:user/repo.git", - ffEnabled: true, expectedValue: "true", }, { @@ -5160,7 +4660,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: "ssh://git@github.com/user/repo.git", - ffEnabled: true, expectedValue: "true", }, { @@ -5169,7 +4668,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: "https://github.com/user/repo.git", - ffEnabled: true, expectedValue: "false", }, { @@ -5178,7 +4676,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: "/path/to/source.zip", - ffEnabled: true, expectedValue: "true", }, { @@ -5187,7 +4684,6 @@ func TestGetGitCommitHistoryValue(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: "/path/to/source.zip", - ffEnabled: true, expectedValue: "false", }, } @@ -5210,7 +4706,7 @@ func TestGetGitCommitHistoryValue(t *testing.T) { _ = cmdCommand.Flags().Set(commonParams.SCSEnginesFlag, tt.scsEngines) _ = cmdCommand.Flags().Set(commonParams.SourcesFlag, tt.source) - result := getGitCommitHistoryValue(cmdCommand, tt.ffEnabled) + result := getGitCommitHistoryValue(cmdCommand) assert.Equal(t, tt.expectedValue, result, "Expected value=%s, got=%s", tt.expectedValue, result) }) @@ -5232,37 +4728,15 @@ func TestGetGitCommitHistoryValue_WithWarnings(t *testing.T) { scanTypes string scsEngines string source string - ffEnabled bool expectedValue string expectWarnings string }{ - { - name: "Flag true with FF disabled - returns empty with warning", - flagValue: "true", - scanTypes: "scs", - scsEngines: "secret-detection", - source: tempDir, - ffEnabled: false, - expectedValue: "", - expectWarnings: gitCommitHistoryNotAvailableWarningMsg, - }, - { - name: "Flag false with FF disabled - returns empty with warning", - flagValue: "false", - scanTypes: "scs", - scsEngines: "secret-detection", - source: tempDir, - ffEnabled: false, - expectedValue: "", - expectWarnings: gitCommitHistoryNotAvailableWarningMsg, - }, { name: "Flag true without SCS scan type - returns empty with warning", flagValue: "true", scanTypes: "sast", scsEngines: "secret-detection", source: tempDir, - ffEnabled: true, expectedValue: "", expectWarnings: gitCommitHistoryNotSelectedWarningMsg, }, @@ -5272,7 +4746,6 @@ func TestGetGitCommitHistoryValue_WithWarnings(t *testing.T) { scanTypes: "sast", scsEngines: "secret-detection", source: tempDir, - ffEnabled: true, expectedValue: "", expectWarnings: gitCommitHistoryNotSelectedWarningMsg, }, @@ -5282,7 +4755,6 @@ func TestGetGitCommitHistoryValue_WithWarnings(t *testing.T) { scanTypes: "scs", scsEngines: "scorecard", source: tempDir, - ffEnabled: true, expectedValue: "", expectWarnings: gitCommitHistoryNotApplicableWarningMsg, }, @@ -5292,7 +4764,6 @@ func TestGetGitCommitHistoryValue_WithWarnings(t *testing.T) { scanTypes: "scs", scsEngines: "scorecard", source: tempDir, - ffEnabled: true, expectedValue: "", expectWarnings: gitCommitHistoryNotApplicableWarningMsg, }, @@ -5302,7 +4773,6 @@ func TestGetGitCommitHistoryValue_WithWarnings(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: tempDirNoGit, - ffEnabled: true, expectedValue: "", expectWarnings: gitCommitHistoryNoGitRepositoryWarningMsg, }, @@ -5312,7 +4782,6 @@ func TestGetGitCommitHistoryValue_WithWarnings(t *testing.T) { scanTypes: "scs", scsEngines: "secret-detection", source: tempDirNoGit, - ffEnabled: true, expectedValue: "", expectWarnings: gitCommitHistoryNoGitRepositoryWarningMsg, }, @@ -5341,7 +4810,7 @@ func TestGetGitCommitHistoryValue_WithWarnings(t *testing.T) { r, w, _ := os.Pipe() os.Stdout = w - result := getGitCommitHistoryValue(cmdCommand, tt.ffEnabled) + result := getGitCommitHistoryValue(cmdCommand) w.Close() os.Stdout = oldStdout diff --git a/internal/commands/secrets-realtime.go b/internal/commands/secrets-realtime.go index d309197f5..68e532e95 100644 --- a/internal/commands/secrets-realtime.go +++ b/internal/commands/secrets-realtime.go @@ -11,7 +11,6 @@ import ( func RunScanSecretsRealtimeCommand( jwtWrapper wrappers.JWTWrapper, - featureFlagWrapper wrappers.FeatureFlagsWrapper, ) func(cmd *cobra.Command, args []string) error { return func(cmd *cobra.Command, _ []string) error { fileSourceFlag, _ := cmd.Flags().GetString(commonParams.SourcesFlag) @@ -21,7 +20,7 @@ func RunScanSecretsRealtimeCommand( ignoredFilePathFlag, _ := cmd.Flags().GetString(commonParams.IgnoredFilePathFlag) - secretsRealtimeService := secretsrealtime.NewSecretsRealtimeService(jwtWrapper, featureFlagWrapper) + secretsRealtimeService := secretsrealtime.NewSecretsRealtimeService(jwtWrapper) results, err := secretsRealtimeService.RunSecretsRealtimeScan(fileSourceFlag, ignoredFilePathFlag) if err != nil { diff --git a/internal/commands/secrets-realtime_test.go b/internal/commands/secrets-realtime_test.go index 096dfefda..e482441b4 100644 --- a/internal/commands/secrets-realtime_test.go +++ b/internal/commands/secrets-realtime_test.go @@ -3,14 +3,11 @@ package commands import ( "testing" - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/mock" "github.com/stretchr/testify/assert" ) func TestRunScanSecretsRealtimeCommand_TxtFile_ScanSuccess(t *testing.T) { clearFlags() - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} execCmdNilAssertion( t, "scan", "secrets-realtime", "-s", "data/secret-exposed.txt", "--ignored-file-path", "", @@ -19,20 +16,9 @@ func TestRunScanSecretsRealtimeCommand_TxtFile_ScanSuccess(t *testing.T) { func TestRunScanSecretsRealtimeCommand_EmptyFilePath_ScanFailed(t *testing.T) { clearFlags() - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} err := execCmdNotNilAssertion( t, "scan", "secrets-realtime", "-s", "", "--ignored-file-path", "", ) assert.NotNil(t, err) } - -func TestRunScanSecretsRealtimeCommand_FFDisable_ScanFailed(t *testing.T) { - clearFlags() - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: false} - err := execCmdNotNilAssertion( - t, - "scan", "secrets-realtime", "-s", "data/secret-exposed.txt", "--ignored-file-path", "", - ) - assert.NotNil(t, err) -} diff --git a/internal/commands/telemetry_test.go b/internal/commands/telemetry_test.go index 539929235..109f4c1d2 100644 --- a/internal/commands/telemetry_test.go +++ b/internal/commands/telemetry_test.go @@ -2,13 +2,9 @@ package commands import ( "testing" - - "github.com/checkmarx/ast-cli/internal/wrappers" - "github.com/checkmarx/ast-cli/internal/wrappers/mock" ) func TestRunTelemetryAI_SendToLogSuccess(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} execCmdNilAssertion( t, "telemetry", "ai", "--ai-provider", "Cursor", "--problem-severity", "Critical", "--type", "click", "--sub-type", "ast-results.viewPackageDetails", "--agent", "Cursor", "--engine", "secrets") diff --git a/internal/constants/errors/errors.go b/internal/constants/errors/errors.go index e9cc42627..674b328e0 100644 --- a/internal/constants/errors/errors.go +++ b/internal/constants/errors/errors.go @@ -33,7 +33,6 @@ const ( // Realtime RealtimeEngineErrFormat = "realtime engine error: %s" - RealtimeEngineNotAvailable = "Realtime engine is not available for this tenant" RealtimeEngineFilePathRequired = "file path is required for realtime scan" ) diff --git a/internal/constants/errors/errors_test.go b/internal/constants/errors/errors_test.go index fc5fbe6c4..056f3ecf1 100644 --- a/internal/constants/errors/errors_test.go +++ b/internal/constants/errors/errors_test.go @@ -56,7 +56,6 @@ func TestErrorConstants_NonEmpty(t *testing.T) { ApplicationNotFound, ErrMissingAIFeatureLicense, FileExtensionIsRequired, - RealtimeEngineNotAvailable, RealtimeEngineFilePathRequired, } for _, c := range consts { diff --git a/internal/params/flags.go b/internal/params/flags.go index 5b322ff39..2e24a2081 100644 --- a/internal/params/flags.go +++ b/internal/params/flags.go @@ -344,8 +344,6 @@ const ( SCSSecretDetectionType = "sscs-secret-detection" SecretDetectionType = "secret-detection" SecretDetectionLabel = "Secret Detection" - EnterpriseSecretsLabel = "Enterprise Secrets" - EnterpriseSecretsType = "enterprise-secrets" RepositoryHealthType = "repository-health" RepositoryHealthLabel = "Repository Health" SCSScorecardOverviewType = "Scorecard" diff --git a/internal/services/realtimeengine/common.go b/internal/services/realtimeengine/common.go index 9537a1eb2..9e9c6d97c 100644 --- a/internal/services/realtimeengine/common.go +++ b/internal/services/realtimeengine/common.go @@ -9,15 +9,6 @@ import ( "github.com/pkg/errors" ) -// IsFeatureFlagEnabled checks if a specific feature flag is enabled. -func IsFeatureFlagEnabled(flagWrapper wrappers.FeatureFlagsWrapper, flagName string) (bool, error) { - enabled, err := flagWrapper.GetSpecificFlag(flagName) - if err != nil { - return false, errors.Wrap(err, "failed to get feature flag") - } - return enabled.Status, nil -} - // EnsureLicense validates that a valid JWT wrapper is available. func EnsureLicense(jwtWrapper wrappers.JWTWrapper) error { if jwtWrapper == nil { diff --git a/internal/services/realtimeengine/common_test.go b/internal/services/realtimeengine/common_test.go index 20919f52d..c27e53a16 100644 --- a/internal/services/realtimeengine/common_test.go +++ b/internal/services/realtimeengine/common_test.go @@ -11,34 +11,6 @@ import ( "github.com/stretchr/testify/assert" ) -func TestIsFeatureFlagEnabled_Success(t *testing.T) { - // nolint:gocritic // resetting shared mock package state between tests - mock.FFErr = nil - defer func() { - // nolint:gocritic // resetting shared mock package state between tests - mock.FFErr = nil - }() - mock.Flag.Name = "SOME_FLAG" - mock.Flag.Status = true - - enabled, err := IsFeatureFlagEnabled(&mock.FeatureFlagsMockWrapper{}, "SOME_FLAG") - assert.NoError(t, err) - assert.True(t, enabled) -} - -func TestIsFeatureFlagEnabled_WrapperError_ReturnsWrappedError(t *testing.T) { - mock.FFErr = errors.New("feature flag lookup failed") //nolint:gocritic // resetting shared mock package state between tests - defer func() { - // nolint:gocritic // resetting shared mock package state between tests - mock.FFErr = nil - }() - - enabled, err := IsFeatureFlagEnabled(&mock.FeatureFlagsMockWrapper{}, "SOME_FLAG") - assert.Error(t, err) - assert.Contains(t, err.Error(), "failed to get feature flag") - assert.False(t, enabled) -} - func TestEnsureLicense_NilWrapper_ReturnsError(t *testing.T) { err := EnsureLicense(nil) assert.Error(t, err) diff --git a/internal/services/realtimeengine/containersrealtime/containers-realtime.go b/internal/services/realtimeengine/containersrealtime/containers-realtime.go index afdc026ed..8dad95a98 100644 --- a/internal/services/realtimeengine/containersrealtime/containers-realtime.go +++ b/internal/services/realtimeengine/containersrealtime/containers-realtime.go @@ -22,19 +22,16 @@ const defaultTag = "latest" // ContainersRealtimeService is the service responsible for performing real-time container scanning. type ContainersRealtimeService struct { JwtWrapper wrappers.JWTWrapper - FeatureFlagWrapper wrappers.FeatureFlagsWrapper RealtimeScannerWrapper wrappers.RealtimeScannerWrapper } // NewContainersRealtimeService creates a new ContainersRealtimeService. func NewContainersRealtimeService( jwtWrapper wrappers.JWTWrapper, - featureFlagWrapper wrappers.FeatureFlagsWrapper, realtimeScannerWrapper wrappers.RealtimeScannerWrapper, ) *ContainersRealtimeService { return &ContainersRealtimeService{ JwtWrapper: jwtWrapper, - FeatureFlagWrapper: featureFlagWrapper, RealtimeScannerWrapper: realtimeScannerWrapper, } } @@ -77,9 +74,6 @@ func (c *ContainersRealtimeService) RunContainersRealtimeScan(filePath, ignoredF if filePath == "" { return nil, errorconstants.NewRealtimeEngineError("file path is required").Error() } - if enabled, err := realtimeengine.IsFeatureFlagEnabled(c.FeatureFlagWrapper, wrappers.OssRealtimeEnabled); err != nil || !enabled { - return nil, errorconstants.NewRealtimeEngineError(errorconstants.RealtimeEngineNotAvailable).Error() - } if err := realtimeengine.EnsureLicense(c.JwtWrapper); err != nil { return nil, errorconstants.NewRealtimeEngineError(err.Error()).Error() } diff --git a/internal/services/realtimeengine/containersrealtime/containers-realtime_test.go b/internal/services/realtimeengine/containersrealtime/containers-realtime_test.go index de193081d..7ba48e6cc 100644 --- a/internal/services/realtimeengine/containersrealtime/containers-realtime_test.go +++ b/internal/services/realtimeengine/containersrealtime/containers-realtime_test.go @@ -13,10 +13,8 @@ import ( const testImageName = "nginx" func TestRunContainersRealtimeScan_ValidLicenseAndFile_Success(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := NewContainersRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{ CustomScanImages: func(images *wrappers.ContainerImageRequest) (*wrappers.ContainerImageResponse, error) { return &wrappers.ContainerImageResponse{ @@ -41,10 +39,8 @@ func TestRunContainersRealtimeScan_ValidLicenseAndFile_Success(t *testing.T) { } func TestRunContainersRealtimeScan_EmptyFilePath_Fails(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := NewContainersRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) result, err := service.RunContainersRealtimeScan("", "") @@ -54,10 +50,8 @@ func TestRunContainersRealtimeScan_EmptyFilePath_Fails(t *testing.T) { } func TestRunContainersRealtimeScan_InvalidLicense_Fails(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := NewContainersRealtimeService( nil, // Invalid JWT wrapper - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) result, err := service.RunContainersRealtimeScan("../../../commands/data/containers/testdata/Dockerfile", "") @@ -66,24 +60,9 @@ func TestRunContainersRealtimeScan_InvalidLicense_Fails(t *testing.T) { assert.Contains(t, err.Error(), "JWT wrapper is not initialized, cannot ensure license") } -func TestRunContainersRealtimeScan_FeatureFlagDisabled_Fails(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: false} - service := NewContainersRealtimeService( - &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, - &mock.RealtimeScannerMockWrapper{}, - ) - result, err := service.RunContainersRealtimeScan("../../../commands/data/containers/testdata/Dockerfile", "") - assert.Error(t, err) - assert.Nil(t, result) - assert.Contains(t, err.Error(), "realtime engine error: Realtime engine is not available for this tenant") -} - func TestRunContainersRealtimeScan_InvalidFilePath_Fails(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := NewContainersRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) result, err := service.RunContainersRealtimeScan("/non/existent/Dockerfile", "") @@ -93,10 +72,8 @@ func TestRunContainersRealtimeScan_InvalidFilePath_Fails(t *testing.T) { } func TestRunContainersRealtimeScan_NoImagesFound_ReturnsEmpty(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := NewContainersRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) result, err := service.RunContainersRealtimeScan("../../../commands/data/containers/emptytestdata/Dockerfile", "") @@ -106,10 +83,8 @@ func TestRunContainersRealtimeScan_NoImagesFound_ReturnsEmpty(t *testing.T) { } func TestRunContainersRealtimeScan_ScanError_ReturnsError(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := NewContainersRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{ CustomScanImages: func(images *wrappers.ContainerImageRequest) (*wrappers.ContainerImageResponse, error) { return nil, errors.New("mock scan error") @@ -123,10 +98,8 @@ func TestRunContainersRealtimeScan_ScanError_ReturnsError(t *testing.T) { } func TestRunContainersRealtimeScan_ImageVulnerabilityMapping(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := NewContainersRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{ CustomScanImages: func(images *wrappers.ContainerImageRequest) (*wrappers.ContainerImageResponse, error) { return &wrappers.ContainerImageResponse{ @@ -217,13 +190,11 @@ func TestSplitLocationsToSeparateResults_NoLocations(t *testing.T) { } func TestRunContainersRealtimeScan_WithIgnoreFile_FiltersResult(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} ignoreFile := "../../../commands/data/containers/testdata/ignoredContainers.json" service := NewContainersRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) diff --git a/internal/services/realtimeengine/iacrealtime/iac-realtime.go b/internal/services/realtimeengine/iacrealtime/iac-realtime.go index a0290b92b..1b6ec80a6 100644 --- a/internal/services/realtimeengine/iacrealtime/iac-realtime.go +++ b/internal/services/realtimeengine/iacrealtime/iac-realtime.go @@ -24,19 +24,17 @@ const ( type IacRealtimeService struct { JwtWrapper wrappers.JWTWrapper - FeatureFlagWrapper wrappers.FeatureFlagsWrapper fileHandler *FileHandler containerManager IContainerManager scanner *Scanner } -func NewIacRealtimeService(jwt wrappers.JWTWrapper, flags wrappers.FeatureFlagsWrapper, containerManager IContainerManager) *IacRealtimeService { +func NewIacRealtimeService(jwt wrappers.JWTWrapper, containerManager IContainerManager) *IacRealtimeService { fileHandler := NewFileHandler() scanner := NewScanner(containerManager) return &IacRealtimeService{ JwtWrapper: jwt, - FeatureFlagWrapper: flags, fileHandler: fileHandler, containerManager: containerManager, scanner: scanner, @@ -114,10 +112,6 @@ func (svc *IacRealtimeService) RunIacRealtimeScan(filePath, engine, ignoredFileP } func (svc *IacRealtimeService) runValidations(filePath string) error { - if err := svc.checkFeatureFlag(); err != nil { - return err - } - if err := svc.ensureLicense(); err != nil { return err } @@ -128,14 +122,6 @@ func (svc *IacRealtimeService) runValidations(filePath string) error { return nil } -func (svc *IacRealtimeService) checkFeatureFlag() error { - enabled, err := realtimeengine.IsFeatureFlagEnabled(svc.FeatureFlagWrapper, wrappers.OssRealtimeEnabled) - if err != nil || !enabled { - return errorconstants.NewRealtimeEngineError(errorconstants.RealtimeEngineNotAvailable).Error() - } - return nil -} - func (svc *IacRealtimeService) ensureLicense() error { if err := realtimeengine.EnsureLicense(svc.JwtWrapper); err != nil { return errorconstants.NewRealtimeEngineError("failed to ensure license").Error() diff --git a/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go b/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go index 17181e83d..fa44beb8f 100644 --- a/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go +++ b/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go @@ -8,7 +8,6 @@ import ( "testing" commonParams "github.com/checkmarx/ast-cli/internal/params" - "github.com/checkmarx/ast-cli/internal/wrappers" "github.com/checkmarx/ast-cli/internal/wrappers/mock" ) @@ -19,9 +18,8 @@ const ( func TestNewIacRealtimeService(t *testing.T) { mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) if service == nil { t.Error("NewIacRealtimeService() should not return nil") @@ -32,10 +30,6 @@ func TestNewIacRealtimeService(t *testing.T) { t.Error("NewIacRealtimeService() should set JwtWrapper") } - if service.FeatureFlagWrapper == nil { - t.Error("NewIacRealtimeService() should set FeatureFlagWrapper") - } - if service.fileHandler == nil { t.Error("NewIacRealtimeService() should initialize fileHandler") } @@ -49,57 +43,6 @@ func TestNewIacRealtimeService(t *testing.T) { } } -func TestIacRealtimeService_checkFeatureFlag(t *testing.T) { - tests := []struct { - name string - setupMock func() - expectErr bool - }{ - { - name: "Feature flag enabled", - setupMock: func() { - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.OssRealtimeEnabled, - Status: true, - } - }, - expectErr: false, - }, - { - name: "Feature flag disabled", - setupMock: func() { - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.OssRealtimeEnabled, - Status: false, - } - }, - expectErr: true, - }, - } - - for _, tt := range tests { - ttt := tt - t.Run(tt.name, func(t *testing.T) { - // Setup mock - ttt.setupMock() - - mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) - err := service.checkFeatureFlag() - - if ttt.expectErr && err == nil { - t.Error("checkFeatureFlag() expected error but got none") - } - - if !ttt.expectErr && err != nil { - t.Errorf("checkFeatureFlag() unexpected error: %v", err) - } - }) - } -} - func TestIacRealtimeService_ensureLicense(t *testing.T) { tests := []struct { name string @@ -121,9 +64,8 @@ func TestIacRealtimeService_ensureLicense(t *testing.T) { ttt.setupMock() mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) err := service.ensureLicense() if ttt.expectErr && err == nil { @@ -139,8 +81,7 @@ func TestIacRealtimeService_ensureLicense(t *testing.T) { func TestIacRealtimeService_validateFilePath(t *testing.T) { mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) // Create a real test file for valid path testing testFile, err := os.CreateTemp("", "validate-test-*.yaml") @@ -198,78 +139,11 @@ func TestIacRealtimeService_validateFilePath(t *testing.T) { } } -func TestIacRealtimeService_RunIacRealtimeScan_FeatureFlagValidation(t *testing.T) { - tests := []struct { - name string - setupMock func() - expectErr bool - errorCheck func(error) bool - }{ - { - name: "Feature flag disabled should fail", - setupMock: func() { - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.OssRealtimeEnabled, - Status: false, - } - }, - expectErr: true, - errorCheck: func(err error) bool { - return err != nil // Should get a realtime engine error - }, - }, - { - name: "Feature flag enabled should proceed to next validation", - setupMock: func() { - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.OssRealtimeEnabled, - Status: true, - } - }, - expectErr: true, // Will fail at file validation stage since file doesn't exist - errorCheck: func(err error) bool { - return err != nil // Should get to file validation and fail there - }, - }, - } - - for _, tt := range tests { - ttt := tt - t.Run(tt.name, func(t *testing.T) { - ttt.setupMock() - - mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) - - _, err := service.RunIacRealtimeScan("test.yaml", "docker", "") - - if ttt.expectErr && err == nil { - t.Error("RunIacRealtimeScan() expected error but got none") - } - - if !ttt.expectErr && err != nil { - t.Errorf("RunIacRealtimeScan() unexpected error: %v", err) - } - - if ttt.errorCheck != nil && !ttt.errorCheck(err) { - t.Errorf("RunIacRealtimeScan() error doesn't match expected pattern: %v", err) - } - }) - } -} - func TestIacRealtimeService_RunIacRealtimeScan_FilePathValidation(t *testing.T) { // Setup feature flag to be enabled so we get to file path validation - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.OssRealtimeEnabled, - Status: true, - } mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) tests := []struct { name string @@ -306,10 +180,6 @@ func TestIacRealtimeService_RunIacRealtimeScan_FilePathValidation(t *testing.T) func TestIacRealtimeService_RunIacRealtimeScan_WithRealFile(t *testing.T) { // Setup mocks for successful validation - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.OssRealtimeEnabled, - Status: true, - } // Setup supported file extensions for testing originalFilters := commonParams.KicsBaseFilters @@ -319,8 +189,7 @@ func TestIacRealtimeService_RunIacRealtimeScan_WithRealFile(t *testing.T) { }() mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) // Create a real test file testContent := "`apiVersion: v1\nkind: Pod\nmetadata:\n name: test-pod" @@ -353,25 +222,16 @@ func TestIacRealtimeService_RunIacRealtimeScan_WithRealFile(t *testing.T) { func TestIacRealtimeService_Integration(t *testing.T) { // Setup successful mocks - mock.Flag = wrappers.FeatureFlagResponseModel{ - Name: wrappers.OssRealtimeEnabled, - Status: true, - } mockJWT := &mock.JWTMockWrapper{} - mockFlags := &mock.FeatureFlagsMockWrapper{} - service := NewIacRealtimeService(mockJWT, mockFlags, NewMockContainerManager()) + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) // Test service initialization if service.JwtWrapper == nil { t.Error("Service should have JWT wrapper") } - if service.FeatureFlagWrapper == nil { - t.Error("Service should have feature flag wrapper") - } - if service.fileHandler == nil { t.Error("Service should have file handler") } @@ -385,10 +245,6 @@ func TestIacRealtimeService_Integration(t *testing.T) { } // Test individual validation methods - if err := service.checkFeatureFlag(); err != nil { - t.Errorf("checkFeatureFlag() should succeed with enabled flag: %v", err) - } - if err := service.ensureLicense(); err != nil { t.Errorf("ensureLicense() should succeed with valid JWT: %v", err) } diff --git a/internal/services/realtimeengine/ossrealtime/oss-realtime.go b/internal/services/realtimeengine/ossrealtime/oss-realtime.go index 5cd10397b..f462f7093 100644 --- a/internal/services/realtimeengine/ossrealtime/oss-realtime.go +++ b/internal/services/realtimeengine/ossrealtime/oss-realtime.go @@ -42,19 +42,16 @@ func convertLocations(locations []models.Location) []realtimeengine.Location { // OssRealtimeService is the service responsible for performing real-time OSS scanning. type OssRealtimeService struct { JwtWrapper wrappers.JWTWrapper - FeatureFlagWrapper wrappers.FeatureFlagsWrapper RealtimeScannerWrapper wrappers.RealtimeScannerWrapper } // NewOssRealtimeService creates a new OssRealtimeService. func NewOssRealtimeService( jwtWrapper wrappers.JWTWrapper, - featureFlagWrapper wrappers.FeatureFlagsWrapper, realtimeScannerWrapper wrappers.RealtimeScannerWrapper, ) *OssRealtimeService { return &OssRealtimeService{ JwtWrapper: jwtWrapper, - FeatureFlagWrapper: featureFlagWrapper, RealtimeScannerWrapper: realtimeScannerWrapper, } } @@ -65,11 +62,6 @@ func (o *OssRealtimeService) RunOssRealtimeScan(filePath, ignoredFilePath string return nil, errorconstants.NewRealtimeEngineError("file path is required").Error() } - if enabled, err := realtimeengine.IsFeatureFlagEnabled(o.FeatureFlagWrapper, wrappers.OssRealtimeEnabled); err != nil || !enabled { - logger.PrintfIfVerbose("Containers Realtime scan is not available (feature flag disabled or error: %v)", err) - return nil, errorconstants.NewRealtimeEngineError(errorconstants.RealtimeEngineNotAvailable).Error() - } - if err := realtimeengine.EnsureLicense(o.JwtWrapper); err != nil { return nil, errorconstants.NewRealtimeEngineError(err.Error()).Error() } diff --git a/internal/services/realtimeengine/ossrealtime/oss-realtime_test.go b/internal/services/realtimeengine/ossrealtime/oss-realtime_test.go index 9c5daa637..6b153f06e 100644 --- a/internal/services/realtimeengine/ossrealtime/oss-realtime_test.go +++ b/internal/services/realtimeengine/ossrealtime/oss-realtime_test.go @@ -37,10 +37,8 @@ func cleanCacheFile(t *testing.T) { } func TestRunOssRealtimeScan_ValidLicenseAndManifest_ScanSuccess(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) @@ -57,7 +55,6 @@ func TestRunOssRealtimeScan_InvalidLicenseAndValidManifest_ScanFail(t *testing.T t.Skip() // Skip this test for now, no license check implemented ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{AIEnabled: mock.AIProtectionDisabled}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) @@ -70,10 +67,8 @@ func TestRunOssRealtimeScan_InvalidLicenseAndValidManifest_ScanFail(t *testing.T } func TestRunOssRealtimeScan_ValidLicenseAndInvalidManifest_ScanFail(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) @@ -86,10 +81,8 @@ func TestRunOssRealtimeScan_ValidLicenseAndInvalidManifest_ScanFail(t *testing.T } func TestRunOssRealtimeScan_WithIgnoredPackage_IgnoresPackage(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) @@ -107,10 +100,8 @@ func TestRunOssRealtimeScan_WithIgnoredPackage_IgnoresPackage(t *testing.T) { } func TestRunOssRealtimeScan_WithEmptyIgnoreFile_AllPackagesIncluded(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) @@ -133,10 +124,8 @@ func TestRunOssRealtimeScan_WithEmptyIgnoreFile_AllPackagesIncluded(t *testing.T } func TestRunOssRealtimeScan_IgnoredPackageWithDifferentVersion_IsNotIgnored(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) @@ -162,7 +151,6 @@ func TestRunOssRealtimeScan_IgnoredPackageWithDifferentVersion_IsNotIgnored(t *t } func TestPrepareScan_CacheExistsAndContainsPartialResults_RealtimeScannerRequestIsCalledPartially(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} cleanCacheFile(t) allPackages := setupPackages() storedPackages := []osscache.PackageEntry{ @@ -185,7 +173,6 @@ func TestPrepareScan_CacheExistsAndContainsPartialResults_RealtimeScannerRequest } func TestPrepareScan_CacheExpiredAndContainsPartialResults_RealtimeScannerRequestIsCalledFully(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} cleanCacheFile(t) allPackages := setupPackages() storedPackages := []osscache.PackageEntry{ @@ -205,7 +192,6 @@ func TestPrepareScan_CacheExpiredAndContainsPartialResults_RealtimeScannerReques } func TestPrepareScan_NoCache_RealtimeScannerRequestIsCalledFully(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} cleanCacheFile(t) allPackages := setupPackages() @@ -219,7 +205,6 @@ func TestPrepareScan_NoCache_RealtimeScannerRequestIsCalledFully(t *testing.T) { } func TestPrepareScan_AllDataInCache_RealtimeScannerRequestIsEmpty(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} cleanCacheFile(t) singlePackage := setupSinglePackage() storedPackages := []osscache.PackageEntry{ @@ -242,11 +227,9 @@ func TestPrepareScan_AllDataInCache_RealtimeScannerRequestIsEmpty(t *testing.T) } func TestScanAndCache_NoCacheAndScanSuccess_CacheUpdated(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} cleanCacheFile(t) ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{ CustomScanPackages: func(packages *wrappers.RealtimeScannerPackageRequest) (*wrappers.RealtimeScannerPackageResponse, error) { var response wrappers.RealtimeScannerPackageResponse @@ -278,12 +261,10 @@ func TestScanAndCache_NoCacheAndScanSuccess_CacheUpdated(t *testing.T) { } func TestScanAndCache_CacheExistsAndScanSuccess_CacheUpdated(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} cleanCacheFile(t) ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) @@ -341,10 +322,8 @@ func TestScanAndCache_CacheExistsAndScanSuccess_CacheUpdated(t *testing.T) { func TestOssRealtimeScan_CsprojFile_ReturnsLocations(t *testing.T) { // Arrange - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} ossRealtimeService := NewOssRealtimeService( &mock.JWTMockWrapper{}, - &mock.FeatureFlagsMockWrapper{}, &mock.RealtimeScannerMockWrapper{}, ) response, err := ossRealtimeService.RunOssRealtimeScan("../../../commands/data/manifests/test.csproj", "") diff --git a/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go b/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go index 406261caf..2c05f333d 100644 --- a/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go +++ b/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go @@ -28,17 +28,14 @@ const ( type SecretsRealtimeService struct { JwtWrapper wrappers.JWTWrapper - FeatureFlagWrapper wrappers.FeatureFlagsWrapper RealtimeScannerWrapper wrappers.RealtimeScannerWrapper } func NewSecretsRealtimeService( jwtWrapper wrappers.JWTWrapper, - featureFlagWrapper wrappers.FeatureFlagsWrapper, ) *SecretsRealtimeService { return &SecretsRealtimeService{ JwtWrapper: jwtWrapper, - FeatureFlagWrapper: featureFlagWrapper, } } @@ -112,10 +109,6 @@ func (s *SecretsRealtimeService) ScanContent(sourcePath, content, ignoredFilePat } func (s *SecretsRealtimeService) ensureReady() error { - if enabled, err := realtimeengine.IsFeatureFlagEnabled(s.FeatureFlagWrapper, wrappers.OssRealtimeEnabled); err != nil || !enabled { - logger.PrintfIfVerbose("Failed to print OSS Realtime scan results: %v", err) - return errorconstants.NewRealtimeEngineError(errorconstants.RealtimeEngineNotAvailable).Error() - } if err := realtimeengine.EnsureLicense(s.JwtWrapper); err != nil { return errorconstants.NewRealtimeEngineError(err.Error()).Error() } diff --git a/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go b/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go index 4eb3b93fc..52eddd8f9 100644 --- a/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go +++ b/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go @@ -8,26 +8,22 @@ import ( "github.com/checkmarx/2ms/v3/lib/reporting" "github.com/checkmarx/2ms/v3/lib/secrets" - "github.com/checkmarx/ast-cli/internal/wrappers" "github.com/checkmarx/ast-cli/internal/wrappers/mock" "github.com/stretchr/testify/assert" ) func TestNewSecretsRealtimeService(t *testing.T) { jwtWrapper := &mock.JWTMockWrapper{} - featureFlagWrapper := &mock.FeatureFlagsMockWrapper{} - service := NewSecretsRealtimeService(jwtWrapper, featureFlagWrapper) + service := NewSecretsRealtimeService(jwtWrapper) assert.NotNil(t, service) assert.Equal(t, jwtWrapper, service.JwtWrapper) - assert.Equal(t, featureFlagWrapper, service.FeatureFlagWrapper) } func TestRunSecretsRealtimeScan_EmptyFilePath_ReturnsError(t *testing.T) { service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, + JwtWrapper: &mock.JWTMockWrapper{}, } results, err := service.RunSecretsRealtimeScan("", "") @@ -37,27 +33,10 @@ func TestRunSecretsRealtimeScan_EmptyFilePath_ReturnsError(t *testing.T) { assert.Contains(t, err.Error(), "file path is required") } -func TestRunSecretsRealtimeScan_FeatureFlagDisabled_ReturnsError(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: false} - - service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, - } - - results, err := service.RunSecretsRealtimeScan("test.txt", "") - - assert.Nil(t, results) - assert.NotNil(t, err) - assert.Contains(t, err.Error(), "Realtime engine is not available") -} - func TestRunSecretsRealtimeScan_FileNotFound_ReturnsError(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, + JwtWrapper: &mock.JWTMockWrapper{}, } results, err := service.RunSecretsRealtimeScan("nonexistent-file.txt", "") @@ -68,7 +47,6 @@ func TestRunSecretsRealtimeScan_FileNotFound_ReturnsError(t *testing.T) { } func TestRunSecretsRealtimeScan_WithIgnoreFile_FiltersResult(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} tempDir := t.TempDir() @@ -84,8 +62,7 @@ func TestRunSecretsRealtimeScan_WithIgnoreFile_FiltersResult(t *testing.T) { assert.NoError(t, os.WriteFile(ignoreFile, data, 0644)) service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, + JwtWrapper: &mock.JWTMockWrapper{}, } results, err := service.RunSecretsRealtimeScan(testFile, ignoreFile) @@ -98,7 +75,6 @@ func TestRunSecretsRealtimeScan_WithIgnoreFile_FiltersResult(t *testing.T) { } func TestRunSecretsRealtimeScan_PatVulAndGenericVul_ReturnedOnlyPathVul(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} tempDir := t.TempDir() @@ -107,8 +83,7 @@ func TestRunSecretsRealtimeScan_PatVulAndGenericVul_ReturnedOnlyPathVul(t *testi assert.NoError(t, os.WriteFile(testFile, []byte(testContent), 0644)) service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, + JwtWrapper: &mock.JWTMockWrapper{}, } results, err := service.RunSecretsRealtimeScan(testFile, "") @@ -121,7 +96,6 @@ func TestRunSecretsRealtimeScan_PatVulAndGenericVul_ReturnedOnlyPathVul(t *testi } func TestRunSecretsRealtimeScan_ValidFile_Success(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} // Create a temporary file for testing tempDir := t.TempDir() @@ -131,8 +105,7 @@ func TestRunSecretsRealtimeScan_ValidFile_Success(t *testing.T) { assert.NoError(t, err) service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, + JwtWrapper: &mock.JWTMockWrapper{}, } results, err := service.RunSecretsRealtimeScan(tempFile, "") @@ -142,7 +115,6 @@ func TestRunSecretsRealtimeScan_ValidFile_Success(t *testing.T) { } func TestRunSecretsRealtimeScan_MultiLineResult_Success(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} value := "PRIVATE_KEY = \"\"\"\n-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA7v8wF+SECRETKEYEXAMPLE+QIDAQABAoIBAQC0\n-----END RSA PRIVATE KEY-----\n\"\"\"" // Create a temporary file for testing tempDir := t.TempDir() @@ -152,8 +124,7 @@ func TestRunSecretsRealtimeScan_MultiLineResult_Success(t *testing.T) { assert.NoError(t, err) service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, + JwtWrapper: &mock.JWTMockWrapper{}, } results, err := service.RunSecretsRealtimeScan(tempFile, "") @@ -346,11 +317,9 @@ func TestGetSeverity_EmptyStatus_ReturnsHigh(t *testing.T) { } func TestScanContent_ReportsSourcePathAndHonorsIgnoreFile(t *testing.T) { - mock.Flag = wrappers.FeatureFlagResponseModel{Name: wrappers.OssRealtimeEnabled, Status: true} service := &SecretsRealtimeService{ - JwtWrapper: &mock.JWTMockWrapper{}, - FeatureFlagWrapper: &mock.FeatureFlagsMockWrapper{}, + JwtWrapper: &mock.JWTMockWrapper{}, } content := "token = \"ghp_1234567890abcdef1234567890abcdef12345678\"" results, err := service.ScanContent("app.env", content, "") diff --git a/internal/wrappers/feature-flags.go b/internal/wrappers/feature-flags.go index c4008f64e..710769a82 100644 --- a/internal/wrappers/feature-flags.go +++ b/internal/wrappers/feature-flags.go @@ -12,22 +12,14 @@ const PackageEnforcementEnabled = "PACKAGE_ENFORCEMENT_ENABLED" const CVSSV3Enabled = "CVSS_V3_ENABLED" const MinioEnabled = "MINIO_ENABLED" const SastCustomStateEnabled = "SAST_CUSTOM_STATES_ENABLED" -const RiskManagementEnabled = "RISK_MANAGEMENT_IDES_PROJECT_RESULTS_SCORES_API_ENABLED" -const OssRealtimeEnabled = "OSS_REALTIME_ENABLED" -const ScsLicensingV2Enabled = "SSCS_NEW_LICENSING_ENABLED" -const SscsCommitHistoryEnabled = "SSCS_COMMIT_HISTORY_ENABLED" const DirectAssociationEnabled = "DIRECT_APP_ASSOCIATION_ENABLED" const DaMigrationEnabled = "DA_MIGRATION_ENABLED" const maxRetries = 3 -const IncreaseFileUploadLimit = "INCREASE_FILE_UPLOAD_LIMIT" const ScaDeltaScanEnabled = "SCA_DELTASCAN_ENABLED" // RepostoreCustomerContributorsCsvEnabled is the feature flag for generating contributors.csv and metadata.json. const RepostoreCustomerContributorsCsvEnabled = "REPOSTORE_CUSTOMER_CONTRIBUTORS_CSV_ENABLED" -// AISupplyChainGAEnabled is the feature flag for AI Supply Chain Engine GA. -const AISupplyChainGAEnabled = "AI_SUPPLY_CHAIN_ENGINE_GA_ENABLED" - var DefaultFFLoad bool = false var FeatureFlagsBaseMap = []CommandFlags{ @@ -78,15 +70,6 @@ var FeatureFlagsBaseMap = []CommandFlags{ }, }, }, - { - CommandName: "cx results risk-management", - FeatureFlags: []FlagBase{ - { - Name: RiskManagementEnabled, - Default: false, - }, - }, - }, } var featureFlags = map[string]bool{} diff --git a/internal/wrappers/jwt-helper.go b/internal/wrappers/jwt-helper.go index 566a88303..7b1b5f58b 100644 --- a/internal/wrappers/jwt-helper.go +++ b/internal/wrappers/jwt-helper.go @@ -40,49 +40,37 @@ func NewJwtWrapper() JWTWrapper { return &JWTStruct{} } -func getEnabledEngines(scsLicensingV2 bool) (enabledEngines []string) { - enabledEngines = []string{"sast", "sca", "api-security", "iac-security", "containers", "aisc"} - if scsLicensingV2 { - enabledEngines = append(enabledEngines, commonParams.RepositoryHealthType, commonParams.SecretDetectionType) - } else { - enabledEngines = append(enabledEngines, commonParams.ScsType, commonParams.EnterpriseSecretsType) - } - return enabledEngines +func getEnabledEngines() []string { + return []string{"sast", "sca", "api-security", "iac-security", "containers", "aisc", + commonParams.RepositoryHealthType, commonParams.SecretDetectionType} } -func getDefaultEngines(scsLicensingV2 bool) (defaultEngines map[string]bool) { - defaultEngines = map[string]bool{ - "sast": true, - "sca": true, - "api-security": true, - "iac-security": true, - "containers": true, - "aisc": true, - } - if scsLicensingV2 { - defaultEngines[commonParams.RepositoryHealthType] = true - defaultEngines[commonParams.SecretDetectionType] = true - } else { - defaultEngines[commonParams.ScsType] = true - defaultEngines[commonParams.EnterpriseSecretsType] = true +func getDefaultEngines() map[string]bool { + return map[string]bool{ + "sast": true, + "sca": true, + "api-security": true, + "iac-security": true, + "containers": true, + "aisc": true, + commonParams.RepositoryHealthType: true, + commonParams.SecretDetectionType: true, } - return defaultEngines } // GetAllowedEngines will return a map with user allowed engines func (*JWTStruct) GetAllowedEngines(featureFlagsWrapper FeatureFlagsWrapper) (allowedEngines map[string]bool, err error) { - scsLicensingV2Flag, _ := GetSpecificFeatureFlag(featureFlagsWrapper, ScsLicensingV2Enabled) flagResponse, _ := GetSpecificFeatureFlag(featureFlagsWrapper, PackageEnforcementEnabled) if flagResponse.Status { jwtStruct, err := getJwtStruct() if err != nil { return nil, err } - allowedEngines = prepareEngines(jwtStruct.AstLicense.LicenseData.AllowedEngines, scsLicensingV2Flag.Status) + allowedEngines = prepareEngines(jwtStruct.AstLicense.LicenseData.AllowedEngines) return allowedEngines, nil } - return getDefaultEngines(scsLicensingV2Flag.Status), nil + return getDefaultEngines(), nil } func (*JWTStruct) GetLicenseDetails() (licenseDetails map[string]string, err error) { @@ -140,20 +128,16 @@ func (*JWTStruct) IsAllowedEngine(engine string) (bool, error) { return false, nil } -func prepareEngines(engines []string, scsLicensingV2 bool) map[string]bool { +func prepareEngines(engines []string) map[string]bool { m := make(map[string]bool) for _, value := range engines { engine := strings.Replace(strings.ToLower(value), strings.ToLower(commonParams.APISecurityLabel), commonParams.APISecurityType, 1) engine = strings.Replace(strings.ToLower(engine), commonParams.KicsType, commonParams.IacType, 1) - if scsLicensingV2 { - engine = strings.Replace(strings.ToLower(engine), strings.ToLower(commonParams.RepositoryHealthLabel), commonParams.RepositoryHealthType, 1) - engine = strings.Replace(strings.ToLower(engine), strings.ToLower(commonParams.SecretDetectionLabel), commonParams.SecretDetectionType, 1) - } else { - engine = strings.Replace(strings.ToLower(engine), strings.ToLower(commonParams.EnterpriseSecretsLabel), commonParams.EnterpriseSecretsType, 1) - } + engine = strings.Replace(strings.ToLower(engine), strings.ToLower(commonParams.RepositoryHealthLabel), commonParams.RepositoryHealthType, 1) + engine = strings.Replace(strings.ToLower(engine), strings.ToLower(commonParams.SecretDetectionLabel), commonParams.SecretDetectionType, 1) // Current limitation, CxOne is including non-engines in the JWT - enabledEngines := getEnabledEngines(scsLicensingV2) + enabledEngines := getEnabledEngines() if utils.Contains(enabledEngines, strings.ToLower(engine)) { m[strings.ToLower(engine)] = true } diff --git a/internal/wrappers/jwt-helper_test.go b/internal/wrappers/jwt-helper_test.go index 9356921ef..1f2aad388 100644 --- a/internal/wrappers/jwt-helper_test.go +++ b/internal/wrappers/jwt-helper_test.go @@ -10,69 +10,33 @@ import ( ) func TestGetDefaultEngines(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - expectedEngines map[string]bool - }{ - { - name: "using new sscs licensing", - scsLicensingV2: true, - expectedEngines: map[string]bool{ - "sast": true, - "sca": true, - "api-security": true, - "iac-security": true, - "containers": true, - "repository-health": true, - "secret-detection": true, - }, - }, - { - name: "using old sscs licensing", - scsLicensingV2: false, - expectedEngines: map[string]bool{ - "sast": true, - "sca": true, - "api-security": true, - "iac-security": true, - "containers": true, - "scs": true, - "enterprise-secrets": true, - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualEngines := getDefaultEngines(tt.scsLicensingV2) - assert.Equal(t, tt.expectedEngines, actualEngines) - }) + expectedEngines := map[string]bool{ + "sast": true, + "sca": true, + "api-security": true, + "iac-security": true, + "containers": true, + "aisc": true, + "repository-health": true, + "secret-detection": true, } + assert.DeepEqual(t, expectedEngines, getDefaultEngines()) } func TestGetEnabledEngines(t *testing.T) { - tests := []struct { - name string - scsLicensingV2 bool - expectedEngines []string - }{ - { - name: "using new sscs licensing", - scsLicensingV2: true, - expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "repository-health", "secret-detection"}, - }, - { - name: "using old sscs licensing", - scsLicensingV2: false, - expectedEngines: []string{"sast", "sca", "api-security", "iac-security", "containers", "scs", "enterprise-secrets"}, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - actualEngines := getDefaultEngines(tt.scsLicensingV2) - assert.Equal(t, tt.expectedEngines, actualEngines) - }) + expectedEngines := []string{"sast", "sca", "api-security", "iac-security", "containers", "aisc", "repository-health", "secret-detection"} + assert.DeepEqual(t, expectedEngines, getEnabledEngines()) +} + +func TestPrepareEngines(t *testing.T) { + licenseEngines := []string{"SAST", "Secret Detection", "Repository Health", "KICS", "Enterprise Secrets", "Checkmarx One Assist"} + expectedEngines := map[string]bool{ + "sast": true, + "secret-detection": true, + "repository-health": true, + "iac-security": true, } + assert.DeepEqual(t, expectedEngines, prepareEngines(licenseEngines)) } func TestGetUniqueID(t *testing.T) { diff --git a/internal/wrappers/mock/jwt-helper-mock.go b/internal/wrappers/mock/jwt-helper-mock.go index b487a959f..36abed9ae 100644 --- a/internal/wrappers/mock/jwt-helper-mock.go +++ b/internal/wrappers/mock/jwt-helper-mock.go @@ -10,7 +10,6 @@ import ( type JWTMockWrapper struct { AIEnabled int - EnterpriseSecretsEnabled int SecretDetectionEnabled int CheckmarxOneAssistEnabled int DastEnabled bool @@ -20,10 +19,9 @@ type JWTMockWrapper struct { const AIProtectionDisabled = 1 const CheckmarxOneAssistDisabled = 1 -const EnterpriseSecretsDisabled = 1 const SecretDetectionDisabled = 1 -var engines = []string{"sast", "sca", "api-security", "iac-security", "scs", "containers", "enterprise-secrets"} +var engines = []string{"sast", "sca", "api-security", "iac-security", "containers", "repository-health", "secret-detection"} const licenseEnabledValue = "true" @@ -57,13 +55,6 @@ func (j *JWTMockWrapper) IsAllowedEngine(engine string) (bool, error) { return true, nil } - if engine == params.EnterpriseSecretsLabel { - if j.EnterpriseSecretsEnabled == EnterpriseSecretsDisabled { - return false, nil - } - return true, nil - } - if engine == params.SecretDetectionLabel { if j.SecretDetectionEnabled == SecretDetectionDisabled { return false, nil diff --git a/test/integration/scan_test.go b/test/integration/scan_test.go index f9062be1e..211cdf58b 100644 --- a/test/integration/scan_test.go +++ b/test/integration/scan_test.go @@ -325,12 +325,12 @@ func TestScanCreate_FolderWithSymbolicLinkWithAbsolutePath_CreateScanSuccessfull func TestScanCreate_IaCWithPresetID_CreateScanSuccessfully(t *testing.T) { bindKeysToEnvAndDefault(t) - // The createPreset(...) function requires these feature flags to be ON. - // If ast-cli runs with these flags OFF, the KICS engine in CxOne will ignore + // The createPreset(...) function requires this feature flag to be ON. + // If ast-cli runs with this flag OFF, the KICS engine in CxOne will ignore // the submitted preset and perform a full scan instead. - // Since this test is only meaningful when the flags are ON, it is skipped otherwise. - if !isFFEnabled(t, "NEW_PRESET_MANAGEMENT_ENABLED") || !isFFEnabled(t, "KICS_PRESETS_MANAGER_ENABLED") { - t.Skip("Preset FFs are not enabled... Skipping test") + // Since this test is only meaningful when the flag is ON, it is skipped otherwise. + if !isFFEnabled(t, "NEW_PRESET_MANAGEMENT_ENABLED") { + t.Skip("Preset FF is not enabled... Skipping test") } requestData := CreatePresetRequest{ From 8aa6ce8c7cba9efd03477f251782b23fbbb52816 Mon Sep 17 00:00:00 2001 From: atishj99 Date: Sat, 31 Oct 2026 00:03:43 +0530 Subject: [PATCH 2/4] Fix Trivy and lint issues and add unit test coverage Add tests for missing licenses and empty source paths in IaC and secrets realtime scans. Update golang.org/x/net and add missing Go documentation comments. --- go.mod | 2 +- go.sum | 4 +- internal/commands/agenthooks.go | 1 + internal/commands/pre-receive.go | 1 + internal/commands/pre_commit.go | 1 - .../iacrealtime/iac-realtime.go | 17 +++++---- .../iacrealtime/iac-realtime_test.go | 32 ++++++++++++++++ .../secretsrealtime/secrets-realtime.go | 2 +- .../secretsrealtime/secrets-realtime_test.go | 38 +++++++++++++++++++ 9 files changed, 85 insertions(+), 13 deletions(-) diff --git a/go.mod b/go.mod index 14f990e9d..a4d97b191 100644 --- a/go.mod +++ b/go.mod @@ -296,7 +296,7 @@ require ( go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect golang.org/x/mod v0.41.0 // indirect - golang.org/x/net v0.60.0 // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/term v0.47.0 // indirect diff --git a/go.sum b/go.sum index daf8984ba..8329de7c7 100644 --- a/go.sum +++ b/go.sum @@ -1201,8 +1201,8 @@ golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= diff --git a/internal/commands/agenthooks.go b/internal/commands/agenthooks.go index 7c1a66dfc..7a89197a0 100644 --- a/internal/commands/agenthooks.go +++ b/internal/commands/agenthooks.go @@ -160,6 +160,7 @@ func NewHookCheckAuthCommand(jwt wrappers.JWTWrapper) *cobra.Command { // Routes are declared per-agent in cxhooks.Agents (cx package). // ============================================================================= +// HookDispatchCommands returns the hidden dispatch subcommands, one per agent hook route. func HookDispatchCommands(jwt wrappers.JWTWrapper, realtimeScanner wrappers.RealtimeScannerWrapper, telemetryWrapper wrappers.TelemetryWrapper) []*cobra.Command { var cmds []*cobra.Command for _, agent := range cxhooks.Agents { diff --git a/internal/commands/pre-receive.go b/internal/commands/pre-receive.go index 2396f884c..a349e9486 100644 --- a/internal/commands/pre-receive.go +++ b/internal/commands/pre-receive.go @@ -15,6 +15,7 @@ const ( SuccessFullSecretsLicenceValidation = "License for pre-receive secret detection has been validated successfully" ) +// PreReceiveCommand creates the pre-receive subcommand func PreReceiveCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { preReceiveCmd := &cobra.Command{ Use: "pre-receive", diff --git a/internal/commands/pre_commit.go b/internal/commands/pre_commit.go index 0d967d697..2d9c88b63 100644 --- a/internal/commands/pre_commit.go +++ b/internal/commands/pre_commit.go @@ -11,7 +11,6 @@ import ( ) // PreCommitCommand creates the pre-commit subcommand - func PreCommitCommand(jwtWrapper wrappers.JWTWrapper) *cobra.Command { preCommitCmd := &cobra.Command{ Use: "pre-commit", diff --git a/internal/services/realtimeengine/iacrealtime/iac-realtime.go b/internal/services/realtimeengine/iacrealtime/iac-realtime.go index 1b6ec80a6..e2a412e4b 100644 --- a/internal/services/realtimeengine/iacrealtime/iac-realtime.go +++ b/internal/services/realtimeengine/iacrealtime/iac-realtime.go @@ -23,21 +23,22 @@ const ( ) type IacRealtimeService struct { - JwtWrapper wrappers.JWTWrapper - fileHandler *FileHandler - containerManager IContainerManager - scanner *Scanner + JwtWrapper wrappers.JWTWrapper + fileHandler *FileHandler + containerManager IContainerManager + scanner *Scanner } +// NewIacRealtimeService creates a new IacRealtimeService. func NewIacRealtimeService(jwt wrappers.JWTWrapper, containerManager IContainerManager) *IacRealtimeService { fileHandler := NewFileHandler() scanner := NewScanner(containerManager) return &IacRealtimeService{ - JwtWrapper: jwt, - fileHandler: fileHandler, - containerManager: containerManager, - scanner: scanner, + JwtWrapper: jwt, + fileHandler: fileHandler, + containerManager: containerManager, + scanner: scanner, } } diff --git a/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go b/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go index fa44beb8f..fd279a34b 100644 --- a/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go +++ b/internal/services/realtimeengine/iacrealtime/iac-realtime_test.go @@ -1074,3 +1074,35 @@ func TestIsEngineRunning_UnresolvableEngine(t *testing.T) { t.Error("IsEngineRunning should be false for an engine that is not installed") } } + +func TestIacRealtimeService_ensureLicense_NoLicense_ReturnsError(t *testing.T) { + mockJWT := &mock.JWTMockWrapper{ + CustomIsAllowedEngine: func(engine string) (bool, error) { return false, nil }, + } + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) + + err := service.ensureLicense() + + if err == nil { + t.Fatal("ensureLicense() expected an error when no license is allowed") + } + if !strings.Contains(err.Error(), "failed to ensure license") { + t.Errorf("unexpected error: %v", err) + } +} + +func TestIacRealtimeService_RunIacRealtimeScan_NoLicense_ReturnsError(t *testing.T) { + mockJWT := &mock.JWTMockWrapper{ + CustomIsAllowedEngine: func(engine string) (bool, error) { return false, nil }, + } + service := NewIacRealtimeService(mockJWT, NewMockContainerManager()) + + results, err := service.RunIacRealtimeScan("test.yaml", "docker", "") + + if err == nil { + t.Fatal("RunIacRealtimeScan() expected an error when no license is allowed") + } + if results != nil { + t.Errorf("expected nil results, got %v", results) + } +} diff --git a/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go b/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go index 2c05f333d..d4513f95c 100644 --- a/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go +++ b/internal/services/realtimeengine/secretsrealtime/secrets-realtime.go @@ -35,7 +35,7 @@ func NewSecretsRealtimeService( jwtWrapper wrappers.JWTWrapper, ) *SecretsRealtimeService { return &SecretsRealtimeService{ - JwtWrapper: jwtWrapper, + JwtWrapper: jwtWrapper, } } diff --git a/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go b/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go index 52eddd8f9..329ee2232 100644 --- a/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go +++ b/internal/services/realtimeengine/secretsrealtime/secrets-realtime_test.go @@ -337,3 +337,41 @@ func TestScanContent_ReportsSourcePathAndHonorsIgnoreFile(t *testing.T) { assert.NoError(t, err) assert.Empty(t, filtered) } + +func TestRunSecretsRealtimeScan_NoLicense_ReturnsLicenseError(t *testing.T) { + service := &SecretsRealtimeService{ + JwtWrapper: &mock.JWTMockWrapper{ + CustomIsAllowedEngine: func(engine string) (bool, error) { return false, nil }, + }, + } + + results, err := service.RunSecretsRealtimeScan("test.txt", "") + + assert.Nil(t, results) + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "required license") +} + +func TestScanContent_EmptySourcePath_ReturnsError(t *testing.T) { + service := &SecretsRealtimeService{JwtWrapper: &mock.JWTMockWrapper{}} + + results, err := service.ScanContent("", "content", "") + + assert.Nil(t, results) + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "file path is required") +} + +func TestScanContent_NoLicense_ReturnsLicenseError(t *testing.T) { + service := &SecretsRealtimeService{ + JwtWrapper: &mock.JWTMockWrapper{ + CustomIsAllowedEngine: func(engine string) (bool, error) { return false, nil }, + }, + } + + results, err := service.ScanContent("test.txt", "content", "") + + assert.Nil(t, results) + assert.NotNil(t, err) + assert.Contains(t, err.Error(), "required license") +} From 65f9ebf2260f4a9043eefcdbb2a99d9b8ae956de Mon Sep 17 00:00:00 2001 From: atishj99 Date: Mon, 2 Nov 2026 11:12:23 +0530 Subject: [PATCH 3/4] Increase unit test timeout to 35m Allow more time for the unit test suite to complete in the CI script. --- internal/commands/.scripts/up.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/commands/.scripts/up.sh b/internal/commands/.scripts/up.sh index 8d6e57764..e9002f8d2 100755 --- a/internal/commands/.scripts/up.sh +++ b/internal/commands/.scripts/up.sh @@ -6,4 +6,4 @@ rm -rf ScaResolver-linux64.tar.gz # ignore mock, wrappers, cmd, logger, and osinstaller packages, as they checked by integration tests gotestsum --junitfile junit.xml --format testname -- \ $(go list ./... | grep -v "mock" | grep -v "wrappers" | grep -v "bitbucketserver" | grep -v "logger" | grep -v "cmd" | grep -v "osinstaller") \ - -timeout 25m -coverprofile cover.out \ No newline at end of file + -timeout 35m -coverprofile cover.out \ No newline at end of file From 16701c0021067d913b81eeac77c25f56965c061a Mon Sep 17 00:00:00 2001 From: Rahul Pidde <206018639+cx-rahul-pidde@users.noreply.github.com> Date: Thu, 5 Nov 2026 18:14:57 +0530 Subject: [PATCH 4/4] Staging (#1606) * Honour the VS Code Checkmarx Self-Healing setting in Copilot agent hooks (AST-180812) (#1603) * AST-180812 - Detect VS Code Copilot CLI sessions from GITHUB_COPILOT_INTEGRATION_ID (#1604) * Feature/ast 180812 vscode copilot cli host (#1607) * Update brotli dependency to v1.2.7 (AST-189161) (#1610) * Update github.com/andybalholm/brotli from v1.2.0 to v1.2.7 (AST-189161) Indirect dependency pulled in via anchore/syft -> anchore/archiver. No API removals; archiver only uses NewWriterLevel/NewReader, which are unchanged. Co-Authored-By: Claude Fable 5.1 * Update Docker base image checkmarx/bash:5.3 to latest digest (AST-189161) Bumps the SHA256-pinned base image to the 5.3-r14 build pushed on 2026-11-04. Co-Authored-By: Claude Fable 5.1 * Replace .trivyignore entries with current binary findings (AST-189161) Ignore GO-2026-5932 (x/crypto/openpgp via helm provenance), CVE-2026-78661 and CVE-2026-97045 (x/net/html via syft Maven cataloger). Remove the previous Wolfi base-image and syft/docker entries, which no longer apply. Co-Authored-By: Claude Fable 5.1 * Restore syft and docker entries in .trivyignore (AST-189161) CVE-2026-33481 (syft temp cleanup) and CVE-2026-33997 (moby plugin privilege bypass) are still reported against the binary. Neither has an adoptable fix: syft >= 1.42.3 reintroduces the binary-size regression reverted in AST-188320 and docker/docker has no 29.x release on its module path. Justifications and reachability analysis are recorded in the file. Co-Authored-By: Claude Fable 5.1 * Bump golang.org/x/net to v0.62.0 and trim .trivyignore (AST-189161) Bump the indirect golang.org/x/net dependency to v0.62.0, which fixes CVE-2026-78661 and CVE-2026-97045, so their ignore entries are dropped. Keep only the ignores that cannot be fixed directly: GO-2026-5932 (x/crypto openpgp, via helm), CVE-2026-33481 (syft) and CVE-2026-33997 (docker). Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Claude Fable 5.1 Co-authored-by: atishj99 * revret exclude git config changes (#1609) Co-authored-by: Aniket Shinde * Use self-repository syntax for reusable workflow in nightly-parallel (AST-189161) Replace `uses: ./.github/workflows/ci-tests.yml` with the `$/` form to satisfy the zizmor `self-repository` audit (added in zizmor v1.30.0). Co-Authored-By: Claude Sonnet 5.5 --------- Co-authored-by: Anurag Dalke Co-authored-by: Claude Fable 5.1 Co-authored-by: atishj99 Co-authored-by: Sumit Morchhale Co-authored-by: Aniket Shinde --- .github/workflows/nightly-parallel.yml | 2 +- .trivyignore | 51 ++----- Dockerfile | 2 +- go.mod | 4 +- go.sum | 8 +- internal/commands/agenthooks/cx/hooks.go | 42 +++++- .../agenthooks/cx/vscode_self_healing_test.go | 127 +++++++++++++++++ .../agenthooks/guardrails/asca/asca.go | 3 +- .../agenthooks/guardrails/kics/kics.go | 3 +- .../agenthooks/guardrails/secrets/secrets.go | 3 +- .../commands/agenthooks/hostenv/hostenv.go | 82 +++++++++++ .../agenthooks/hostenv/hostenv_test.go | 98 +++++++++++++ .../agenthooks/scannerconfig/scannerconfig.go | 129 ++++++++++++++++-- .../scannerconfig/scannerconfig_test.go | 128 +++++++++++++++++ internal/commands/scan.go | 14 -- internal/params/filters.go | 5 - 16 files changed, 613 insertions(+), 88 deletions(-) create mode 100644 internal/commands/agenthooks/cx/vscode_self_healing_test.go create mode 100644 internal/commands/agenthooks/hostenv/hostenv.go create mode 100644 internal/commands/agenthooks/hostenv/hostenv_test.go diff --git a/.github/workflows/nightly-parallel.yml b/.github/workflows/nightly-parallel.yml index 77bc9eea9..4f6c38e03 100644 --- a/.github/workflows/nightly-parallel.yml +++ b/.github/workflows/nightly-parallel.yml @@ -18,6 +18,6 @@ permissions: jobs: integration-tests: # zizmor: ignore[anonymous-definition] - uses: ./.github/workflows/ci-tests.yml + uses: $/.github/workflows/ci-tests.yml # ci-tests.yml requires ~20 CX/SCM secrets; it's a same-repo reusable workflow, not a fork/third-party target. secrets: inherit # zizmor: ignore[secrets-inherit] diff --git a/.trivyignore b/.trivyignore index 58ab2c148..cd0e4ebc9 100644 --- a/.trivyignore +++ b/.trivyignore @@ -1,44 +1,6 @@ # Trivy Ignore Configuration -# These vulnerabilities are in the Wolfi Linux base image or have compatibility issues - -# ============================================================================ -# BASE IMAGE VULNERABILITIES (Wolfi) - Cannot be patched by CLI code -# ============================================================================ - -# CVE-2026-8674: glibc DNS stub resolver DoS via long search domain -# Severity: MEDIUM -# Component: zlib 1.3.2-r6 (in Wolfi base image) -# Impact: Local DNS parsing issue - requires malformed DNS configuration -# Reason: Base image vulnerability - awaiting Wolfi update to zlib 1.3.2.1_rc20260601-r0 -CVE-2026-8674 - -# CVE-2026-86805: glibc TOCTOU privilege escalation -# Severity: MEDIUM -# Component: glibc 2.44-r7 (in base image) -# Impact: Local attacker with file system access - requires race condition exploit -# Reason: Base image vulnerability - awaiting Wolfi update to glibc 2.44-r8 -CVE-2026-86805 - -# CVE-2026-89092: glibc nscd stack overflow -# Severity: MEDIUM -# Component: glibc 2.44-r7 (in base image) -# Impact: Local DoS via nscd service - requires nscd to be running -# Reason: Base image vulnerability - awaiting Wolfi update to glibc 2.44-r8 -CVE-2026-89092 - -# CVE-2026-95818: glibc local DoS and information disclosure -# Severity: MEDIUM -# Component: glibc 2.44-r7 (in base image) -# Impact: Local attacker can cause denial of service -# Reason: Base image vulnerability - awaiting Wolfi update to glibc 2.44-r8 -CVE-2026-95818 - -# CVE-2026-85091: zlib heap buffer overflow -# Severity: MEDIUM -# Component: zlib 1.3.2-r6 (in Wolfi base image) -# Impact: Heap buffer overflow in compression library -# Reason: Base image vulnerability - awaiting Wolfi update to 1.3.2.1_rc20260601-r0 -CVE-2026-85091 +# These vulnerabilities are in Go dependencies that cannot be updated or fixed directly. +# Review periodically and remove entries once the underlying dependency is upgraded. # ============================================================================ # BINARY VULNERABILITIES - Compatibility Issues (Not Updated) @@ -62,3 +24,12 @@ CVE-2026-33481 # Docker plugin system - uses only core Docker SDK for container scanning. # Status: Risk accepted - vulnerability not exploitable in CLI usage pattern CVE-2026-33997 + +# GO-2026-5932: golang.org/x/crypto/openpgp is unmaintained and unsafe by design +# Severity: UNKNOWN +# Component: golang.org/x/crypto v0.58.0 (transitive via helm.sh/helm/v3/pkg/provenance) +# Reason: Not imported by ast-cli directly; the "fixed" version is an untagged pseudo-version. +# Awaiting Helm to drop x/crypto/openpgp. +# Impact: CLI does not perform OpenPGP signing/verification. +# Status: Risk accepted +GO-2026-5932 diff --git a/Dockerfile b/Dockerfile index 04f46d280..2c4c92c77 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM checkmarx/bash:5.3-r14-365aa4c3c7b3fc@sha256:365aa4c3c7b3fcb580687c427e90ee9cda26e75cd12cae3a2b521777c0b4d3f3 +FROM checkmarx/bash:5.3-r14-e52a196c3a914c@sha256:e52a196c3a914c6496c72465ad4a8f7efd1ff8ad988b328cbb92018652c23c7d USER nonroot COPY cx /app/bin/cx diff --git a/go.mod b/go.mod index 14f990e9d..ae7728e63 100644 --- a/go.mod +++ b/go.mod @@ -102,7 +102,7 @@ require ( github.com/anchore/packageurl-go v0.1.1-0.20250220190351-d62adb6e1115 // indirect github.com/anchore/stereoscope v0.1.0 // indirect github.com/anchore/syft v1.21.0 // indirect - github.com/andybalholm/brotli v1.2.0 // indirect + github.com/andybalholm/brotli v1.2.7 // indirect github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/aquasecurity/go-pep440-version v0.0.1 // indirect github.com/aquasecurity/go-version v0.0.1 // indirect @@ -296,7 +296,7 @@ require ( go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect golang.org/x/mod v0.41.0 // indirect - golang.org/x/net v0.60.0 // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/oauth2 v0.36.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/term v0.47.0 // indirect diff --git a/go.sum b/go.sum index daf8984ba..93a244506 100644 --- a/go.sum +++ b/go.sum @@ -151,8 +151,8 @@ github.com/anchore/stereoscope v0.1.0/go.mod h1:3vasimie0IJOXvMbMpjwvwIHBDA1+192 github.com/anchore/syft v1.21.0 h1:JHmYOnEbCJsElROCCfg+3oIODw1LQLfXGkIrmXNZYsI= github.com/anchore/syft v1.21.0/go.mod h1:8i8Yp/MiSOdqID0+6eiwE9bOJWM7fEBYitINZyr2G6s= github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= -github.com/andybalholm/brotli v1.2.0 h1:ukwgCxwYrmACq68yiUqwIWnGY0cTPox/M94sVwToPjQ= -github.com/andybalholm/brotli v1.2.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/andybalholm/brotli v1.2.7 h1:UgafRPGMam5ySHfRkhthMqOFA6IFoeF3D7mWIDLjG5A= +github.com/andybalholm/brotli v1.2.7/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8= github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= @@ -1201,8 +1201,8 @@ golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qx golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= diff --git a/internal/commands/agenthooks/cx/hooks.go b/internal/commands/agenthooks/cx/hooks.go index 9fb7e3317..dbe0b0d65 100644 --- a/internal/commands/agenthooks/cx/hooks.go +++ b/internal/commands/agenthooks/cx/hooks.go @@ -12,9 +12,11 @@ import ( "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/asca" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/kics" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/guardrails/secrets" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/sca" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/scannerconfig" "github.com/checkmarx/ast-cli/internal/commands/agenthooks/sessiontally" + "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/wrappers" ) @@ -113,6 +115,9 @@ func cxBeforeToolCall(ev agenthooks.ToolCallEvent) agenthooks.ToolVerdict { // or if the file exceeds the policy size cap. Reads do NOT count toward // the blast-radius budget (that limit is about writes). func cxBeforeFileEdit(ev agenthooks.FileEditEvent) agenthooks.FileEditVerdict { + if selfHealingOff(ev.Agent, "pre-file-write") { + return agenthooks.AcceptEdit() + } bindThreshold(ev.Agent) if ev.Agent == agenthooks.AgentCursor && len(ev.Changes) == 0 { if reason := guardrails.ScanFileForSecrets(ev.FilePath); reason != "" { @@ -290,7 +295,7 @@ func logRemediationTelemetry(agent, engine, severity, sessionID string) { telemetryData := &wrappers.DataForAITelemetry{ AIProvider: agent, - Agent: agent + "-cli", + Agent: hostenv.TelemetryAgent(agent), Engine: engine, ScanType: strings.ToLower(engine), UniqueID: wrappers.GetUniqueID(), @@ -325,14 +330,41 @@ func secretsApply(agent agenthooks.AgentID) bool { return switchesApply(agent) } -// scannerOn is scannerconfig.Enabled, limited to the agents the switches apply to. +// scannerOn is scannerconfig.Enabled, limited to the agents the switches apply to. GitHub Copilot inside +// VS Code takes the switches from the VS Code extension's IDE file instead, while that file is valid. func scannerOn(agent agenthooks.AgentID, s scannerconfig.Scanner) bool { - return !switchesApply(agent) || scannerconfig.Enabled(s) + if !switchesApply(agent) { + return true + } + if agent == agenthooks.AgentCopilotCLI && hostenv.InVSCode() { + return scannerconfig.IDEEnabled(s) + } + return scannerconfig.Enabled(s) +} + +// selfHealingOff reports whether this GitHub Copilot hook runs inside VS Code with the VS Code extension's +// "Checkmarx Self-Healing" setting unticked (a valid IDE file saying cx_self_healing_enabled=false). The +// file-write scans then stand down without telemetry; shell commands and prompts are handled as before. +// The plugin's own hook scripts already stop before running cx in that case; this covers hooks that +// call cx directly. A missing or invalid IDE file means on, and the terminal Copilot CLI never reads it. +func selfHealingOff(agent agenthooks.AgentID, hook string) bool { + if agent != agenthooks.AgentCopilotCLI || !hostenv.InVSCode() || scannerconfig.SelfHealingEnabled() { + return false + } + logger.PrintfIfVerbose("hooks: copilot-cli %s allowed without scanning host=vscode skip_reason=self_healing_disabled", hook) + return true } -// belowThreshold is scannerconfig.BelowThreshold, limited to the agents the switches apply to. +// belowThreshold is scannerconfig.BelowThreshold, limited to the agents the switches apply to. GitHub +// Copilot inside VS Code has no threshold setting, so it uses the IDE file's threshold, low when unset. func belowThreshold(agent agenthooks.AgentID, severity string) bool { - return switchesApply(agent) && scannerconfig.BelowThreshold(severity) + if !switchesApply(agent) { + return false + } + if agent == agenthooks.AgentCopilotCLI && hostenv.InVSCode() { + return scannerconfig.IDEBelowThreshold(severity) + } + return scannerconfig.BelowThreshold(severity) } // agentToString converts agenthooks.AgentID enum to string representation for telemetry. diff --git a/internal/commands/agenthooks/cx/vscode_self_healing_test.go b/internal/commands/agenthooks/cx/vscode_self_healing_test.go new file mode 100644 index 000000000..61a15c9a9 --- /dev/null +++ b/internal/commands/agenthooks/cx/vscode_self_healing_test.go @@ -0,0 +1,127 @@ +//go:build !integration + +package cx + +import ( + "os" + "path/filepath" + "testing" + + agenthooks "github.com/Checkmarx/ast-cx-hooks" + + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/scannerconfig" +) + +// PLUGIN_ROOT values as the hosts set them (AST-186850 PoC; Windows paths, any user name). +const ( + rootVSCodeFromCLIInstall = `C:\Users\u\AppData\Roaming\Code\agentPlugins\file-c-3A-Users-u-copilot-installed-plugins-cx-devassist-marketplace-cx-devassist\1a15407167c` + rootVSCodeFromMarketplace = `C:\Users\u\AppData\Roaming\Code\agentPlugins\file-c-3A-Users-u-vscode-agent-plugins-marketplace-repositories-github-com-Checkmarx-cx-agentic-ai\1a1542d091b` + rootCLI = `C:\Users\u\.copilot\installed-plugins\cx-devassist-marketplace\cx-devassist` +) + +// useHost sets the hook environment the host would inject. +func useHost(t *testing.T, pluginRoot, integrationID string) { + t.Helper() + t.Setenv("PLUGIN_ROOT", pluginRoot) + t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", integrationID) +} + +// useIDEConfig points the user's home at a temp dir holding ~/.checkmarx/cx-onboarding-ide.properties +// (and optionally cx-onboarding.properties); an empty body means no file at all. +func useIDEConfig(t *testing.T, ideBody, cliBody string) { + t.Helper() + dir := t.TempDir() + t.Cleanup(setHomeDir(dir)) + cxDir := filepath.Join(dir, ".checkmarx") + if err := os.MkdirAll(cxDir, 0o755); err != nil { + t.Fatal(err) + } + for name, body := range map[string]string{"cx-onboarding-ide.properties": ideBody, "cx-onboarding.properties": cliBody} { + if body == "" { + continue + } + if err := os.WriteFile(filepath.Join(cxDir, name), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } +} + +func TestCxBeforeFileEdit_SelfHealingOff(t *testing.T) { + const secret = "ghp_self_healing_test_secret_value" + const off = "cx_schema_version=1\ncx_self_healing_enabled=false\n" + cases := []struct { + name string + agent agenthooks.AgentID + root string + ide string + wantBlock bool + }{ + {"VS Code + OFF allows without scanning", agenthooks.AgentCopilotCLI, rootVSCodeFromMarketplace, off, false}, + {"VS Code + ON scans", agenthooks.AgentCopilotCLI, rootVSCodeFromCLIInstall, "cx_self_healing_enabled=true\n", true}, + {"VS Code + no IDE file scans (default ON)", agenthooks.AgentCopilotCLI, rootVSCodeFromCLIInstall, "", true}, + {"VS Code + unknown schema scans", agenthooks.AgentCopilotCLI, rootVSCodeFromCLIInstall, "cx_schema_version=2\ncx_self_healing_enabled=false\n", true}, + {"terminal ignores the IDE file", agenthooks.AgentCopilotCLI, rootCLI, off, true}, + {"other agents ignore it", agenthooks.AgentWindsurf, rootVSCodeFromCLIInstall, off, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + resetHookGlobals(t) + useIDEConfig(t, tc.ide, "") + useHost(t, tc.root, "") + secretsScanner = stubSecretsScanner(secret) + v := cxBeforeFileEdit(secretsEdit(secret, tc.agent)) + if v.Permit == tc.wantBlock { + t.Fatalf("Permit=%v, wantBlock=%v", v.Permit, tc.wantBlock) + } + }) + } +} + +func TestScannerOn_VSCodeUsesIDEFile(t *testing.T) { + const ideSecretsOff = "cx_schema_version=1\ncx_secret_scanner_enabled=false\n" + const cliSecretsOff = "cx_secret_scanner_enabled=false\n" + cases := []struct { + name string + root string + ide, cli string + want bool + }{ + {"VS Code follows the IDE file", rootVSCodeFromCLIInstall, ideSecretsOff, "", false}, + {"VS Code IDE file missing key is on, even if the terminal file is off", rootVSCodeFromCLIInstall, "cx_schema_version=1\n", cliSecretsOff, true}, + {"VS Code without a valid IDE file falls back to the terminal file", rootVSCodeFromCLIInstall, "", cliSecretsOff, false}, + {"terminal never reads the IDE file", rootCLI, ideSecretsOff, "", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + useIDEConfig(t, tc.ide, tc.cli) + useHost(t, tc.root, "") + if got := scannerOn(agenthooks.AgentCopilotCLI, scannerconfig.Secrets); got != tc.want { + t.Fatalf("scannerOn = %v, want %v", got, tc.want) + } + }) + } +} + +func TestBelowThreshold_VSCodeDefaultsToLow(t *testing.T) { + const cliHigh = "cx_severity_threshold=high\n" + cases := []struct { + name string + root string + ide, cli string + want bool + }{ + {"VS Code without a threshold blocks Medium (low)", rootVSCodeFromCLIInstall, "cx_schema_version=1\n", cliHigh, false}, + {"VS Code without an IDE file blocks Medium (low)", rootVSCodeFromMarketplace, "", cliHigh, false}, + {"VS Code honours a threshold in the IDE file", rootVSCodeFromCLIInstall, "cx_schema_version=1\n" + cliHigh, "", true}, + {"terminal keeps the terminal threshold", rootCLI, "cx_schema_version=1\n", cliHigh, true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + useIDEConfig(t, tc.ide, tc.cli) + useHost(t, tc.root, "") + if got := belowThreshold(agenthooks.AgentCopilotCLI, "Medium"); got != tc.want { + t.Fatalf("belowThreshold = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/internal/commands/agenthooks/guardrails/asca/asca.go b/internal/commands/agenthooks/guardrails/asca/asca.go index 09f10301f..2427913e0 100644 --- a/internal/commands/agenthooks/guardrails/asca/asca.go +++ b/internal/commands/agenthooks/guardrails/asca/asca.go @@ -6,6 +6,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/params" "github.com/checkmarx/ast-cli/internal/services" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" @@ -192,7 +193,7 @@ func logASCATelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session } telemetryData := &wrappers.DataForAITelemetry{ - Agent: agent + "-cli", + Agent: hostenv.TelemetryAgent(agent), AIProvider: agent, Engine: "Asca", TotalCount: totalCount, diff --git a/internal/commands/agenthooks/guardrails/kics/kics.go b/internal/commands/agenthooks/guardrails/kics/kics.go index 17f630322..684f4ee01 100644 --- a/internal/commands/agenthooks/guardrails/kics/kics.go +++ b/internal/commands/agenthooks/guardrails/kics/kics.go @@ -7,6 +7,7 @@ import ( "strings" agenthooks "github.com/Checkmarx/ast-cx-hooks" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/params" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/iacrealtime" @@ -170,7 +171,7 @@ func logKicsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, session } telemetryData := &wrappers.DataForAITelemetry{ - Agent: agent + "-cli", + Agent: hostenv.TelemetryAgent(agent), AIProvider: agent, Engine: "IaC", TotalCount: totalCount, diff --git a/internal/commands/agenthooks/guardrails/secrets/secrets.go b/internal/commands/agenthooks/guardrails/secrets/secrets.go index b5a73c853..b4c3bbd8e 100644 --- a/internal/commands/agenthooks/guardrails/secrets/secrets.go +++ b/internal/commands/agenthooks/guardrails/secrets/secrets.go @@ -4,6 +4,7 @@ import ( "os" agenthooks "github.com/Checkmarx/ast-cx-hooks" + "github.com/checkmarx/ast-cli/internal/commands/agenthooks/hostenv" "github.com/checkmarx/ast-cli/internal/logger" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/ignore" "github.com/checkmarx/ast-cli/internal/services/realtimeengine/secretsrealtime" @@ -121,7 +122,7 @@ func logSecretsTelemetry(telemetryWrapper wrappers.TelemetryWrapper, agent, sess } telemetryData := &wrappers.DataForAITelemetry{ - Agent: agent + "-cli", + Agent: hostenv.TelemetryAgent(agent), AIProvider: agent, Engine: "Secrets", TotalCount: totalCount, diff --git a/internal/commands/agenthooks/hostenv/hostenv.go b/internal/commands/agenthooks/hostenv/hostenv.go new file mode 100644 index 000000000..c00641bca --- /dev/null +++ b/internal/commands/agenthooks/hostenv/hostenv.go @@ -0,0 +1,82 @@ +// Package hostenv tells where a GitHub Copilot hook runs — the terminal Copilot CLI or GitHub Copilot +// inside VS Code — and derives the telemetry agent label from it. Shared by the cx hook handlers and the +// guardrail packages so they cannot drift apart. Mirrors the cx-devassist Copilot plugin's +// _in_vscode / cx_in_vscode. +package hostenv + +import ( + "os" + "strings" +) + +// Where a Copilot hook runs. +const ( + HostUnknown = "" + HostCLI = "cli" + HostVSCode = "vscode" + HostOther = "other" // a VS Code fork (Cursor, Windsurf, Kiro, Devin, ...): never treated as VS Code +) + +// copilotAgent is the agent name the hook handlers use for GitHub Copilot (see cx.agentToString). +const copilotAgent = "Copilot" + +// VSCodeIntegrationID is the GITHUB_COPILOT_INTEGRATION_ID VS Code sets on the Copilot CLI engine it bundles. +const VSCodeIntegrationID = "vscode-chat" + +// pluginHostEnv is set by the cx-devassist Copilot plugin's hooks/cx_run.sh to "vscode" when its own host +// check (which also reads the process tree) finds VS Code. VS Code's Copilot CLI chat sessions run the +// 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". +const agentVSCode = "Copilot-VSCode" + +// 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 +// ~/Library/Application Support/Code/agentPlugins, Linux ~/.config/Code/agentPlugins, Insiders +// likewise), whether the plugin was installed by the Copilot CLI or from VS Code's marketplace; the +// terminal Copilot CLI (also when started in VS Code's integrated terminal) runs it from +// ~/.copilot/installed-plugins/. Hashes and user names in the path are ignored. Any other PLUGIN_ROOT +// (a VS Code fork, JetBrains, Visual Studio, ...) is HostOther. When PLUGIN_ROOT is under +// ~/.copilot/installed-plugins/ or not set, CX_COPILOT_HOST=vscode (from the plugin) marks VS Code. Only +// when PLUGIN_ROOT is not set at all does GITHUB_COPILOT_INTEGRATION_ID=vscode-chat mark VS Code too +// (VS Code's Copilot CLI chat sessions); otherwise no PLUGIN_ROOT is HostUnknown. +func PluginHost() string { + root := strings.ToLower(strings.ReplaceAll(os.Getenv("PLUGIN_ROOT"), `\`, "/")) + pluginSaysVSCode := strings.EqualFold(strings.TrimSpace(os.Getenv(pluginHostEnv)), HostVSCode) + // The terminal marker is checked first: VS Code's folder names encode the source path with dashes + // (…-copilot-installed-plugins-…), so they never contain it, while a terminal path could contain + // "agentPlugins" by chance (a user or folder name). Only VS Code's own user-data folder ("Code", + // "Code - Insiders") counts: VS Code forks keep their agentPlugins copies under their own folder. + switch { + case strings.Contains(root, "/.copilot/installed-plugins/"): + if pluginSaysVSCode { + return HostVSCode + } + return HostCLI + case strings.Contains(root, "/code/agentplugins/"), strings.Contains(root, "/code - insiders/agentplugins/"): + return HostVSCode + case strings.TrimSpace(root) != "": + // Any other plugin folder (a VS Code fork's agentPlugins, JetBrains, Visual Studio, ...) is not + // VS Code, and the fallback below must not override that. + return HostOther + case pluginSaysVSCode, strings.TrimSpace(os.Getenv("GITHUB_COPILOT_INTEGRATION_ID")) == VSCodeIntegrationID: + return HostVSCode + } + return HostUnknown +} + +// InVSCode reports whether this hook runs inside VS Code. +func InVSCode() bool { + return PluginHost() == HostVSCode +} + +// 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". +func TelemetryAgent(agent string) string { + if agent != copilotAgent || !InVSCode() { + return agent + "-cli" + } + return agentVSCode +} diff --git a/internal/commands/agenthooks/hostenv/hostenv_test.go b/internal/commands/agenthooks/hostenv/hostenv_test.go new file mode 100644 index 000000000..df4fa597e --- /dev/null +++ b/internal/commands/agenthooks/hostenv/hostenv_test.go @@ -0,0 +1,98 @@ +//go:build !integration + +package hostenv + +import ( + "testing" +) + +// PLUGIN_ROOT values as the hosts set them (AST-186850 PoC; Windows paths, any user name). +const ( + rootVSCodeFromCLIInstall = `C:\Users\u\AppData\Roaming\Code\agentPlugins\file-c-3A-Users-u-copilot-installed-plugins-cx-devassist-marketplace-cx-devassist\1a15407167c` + rootVSCodeFromMarketplace = `C:\Users\u\AppData\Roaming\Code\agentPlugins\file-c-3A-Users-u-vscode-agent-plugins-marketplace-repositories-github-com-Checkmarx-cx-agentic-ai\1a1542d091b` + rootCLI = `C:\Users\u\.copilot\installed-plugins\cx-devassist-marketplace\cx-devassist` +) + +func useHost(t *testing.T, pluginRoot, integrationID string) { + t.Helper() + t.Setenv("PLUGIN_ROOT", pluginRoot) + t.Setenv("GITHUB_COPILOT_INTEGRATION_ID", integrationID) + t.Setenv(pluginHostEnv, "") +} + +func TestPluginHost(t *testing.T) { + cases := []struct { + name, root, integrationID, want string + }{ + {"VS Code copy of a Copilot CLI install", rootVSCodeFromCLIInstall, "", HostVSCode}, + {"VS Code marketplace install", rootVSCodeFromMarketplace, "", HostVSCode}, + {"Linux VS Code", "/home/u/.config/Code/agentPlugins/x/1a", "", HostVSCode}, + {"macOS VS Code Insiders", "/Users/u/Library/Application Support/Code - Insiders/agentPlugins/x/1a", "", HostVSCode}, + {"terminal Copilot CLI", rootCLI, "", HostCLI}, + {"terminal path with the VS Code integration id", rootCLI, "vscode-chat", HostCLI}, + {"Windsurf copy is not VS Code", `C:\Users\u\AppData\Roaming\Windsurf\agentPlugins\x\1a`, "vscode-chat", HostOther}, + {"Cursor copy is not VS Code", "/Users/u/Library/Application Support/Cursor/agentPlugins/x/1a", "", HostOther}, + {"Kiro copy is not VS Code", "/home/u/.config/Kiro/agentPlugins/x/1a", "", HostOther}, + {"terminal path containing agentPlugins by chance", `C:\Users\agentPlugins\.copilot\installed-plugins\m\cx-devassist`, "", HostCLI}, + {"terminal path under an agentPlugins folder", `/home/u/agentPlugins/.copilot/installed-plugins/m/cx-devassist`, "", HostCLI}, + {"other plugin folder (JetBrains, Visual Studio, ...) is not VS Code", `D:\other\plugin`, "vscode-chat", HostOther}, + {"VS Code Copilot CLI session (integration id, no PLUGIN_ROOT)", "", "vscode-chat", HostVSCode}, + {"integration id with surrounding spaces", "", " vscode-chat ", HostVSCode}, + {"nothing set", "", "", HostUnknown}, + {"other integration id", "", "copilot-developer-cli", HostUnknown}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + useHost(t, tc.root, tc.integrationID) + if got := PluginHost(); got != tc.want { + t.Fatalf("PluginHost() = %q, want %q", got, tc.want) + } + }) + } +} + +func TestPluginHostFromPlugin(t *testing.T) { + cases := []struct { + name, root, pluginHost, want string + }{ + {"VS Code Copilot CLI session from the terminal's folder", rootCLI, "vscode", HostVSCode}, + {"plugin value is trimmed and case-insensitive", rootCLI, " VSCode ", HostVSCode}, + {"terminal Copilot CLI (plugin leaves it unset)", rootCLI, "", HostCLI}, + {"other plugin value is ignored", rootCLI, "cli", HostCLI}, + {"no PLUGIN_ROOT", "", "vscode", HostVSCode}, + {"VS Code copy stays VS Code", rootVSCodeFromCLIInstall, "", HostVSCode}, + {"VS Code fork is never VS Code", `C:\Users\u\AppData\Roaming\Windsurf\agentPlugins\x\1a`, "vscode", HostOther}, + {"other plugin folder is never VS Code", `D:\other\plugin`, "vscode", HostOther}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + useHost(t, tc.root, "") + t.Setenv(pluginHostEnv, tc.pluginHost) + if got := PluginHost(); got != tc.want { + t.Fatalf("PluginHost() = %q, want %q", got, tc.want) + } + }) + } +} + +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"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + useHost(t, tc.root, "") + if got := TelemetryAgent(tc.agent); got != tc.want { + t.Fatalf("TelemetryAgent(%q) = %q, want %q", tc.agent, got, tc.want) + } + }) + } +} diff --git a/internal/commands/agenthooks/scannerconfig/scannerconfig.go b/internal/commands/agenthooks/scannerconfig/scannerconfig.go index aafaf7b2e..2e96c3972 100644 --- a/internal/commands/agenthooks/scannerconfig/scannerconfig.go +++ b/internal/commands/agenthooks/scannerconfig/scannerconfig.go @@ -2,6 +2,11 @@ // ~/.checkmarx/cx-onboarding.properties (seeded by the agent plugins). Every scanner is ENABLED // unless its key is explicitly set to a false-like value, and any read problem also means enabled: // the switches can only narrow what the hooks do, never make them block. +// +// GitHub Copilot agent mode in VS Code has its own state file, +// ~/.checkmarx/cx-onboarding-ide.properties, written by the VS Code extension: the Self-Healing +// switch (cx_self_healing_enabled) and the scanner switches the VS Code settings set. It is read +// only for events from VS Code; the terminal hosts never read it. package scannerconfig import ( @@ -28,18 +33,33 @@ const ( const ( fileName = "cx-onboarding.properties" + // ideFileName is the VS Code extension's state file (see IDEPath). + ideFileName = "cx-onboarding-ide.properties" // maxBytes mirrors the plugins' reader: an oversized file is treated as unreadable (all enabled). maxBytes = 8192 utf8BOM = "\xef\xbb\xbf" + + ideSchemaKey = "cx_schema_version" + ideSchemaVersion = "1" + ideSelfHealingKey = "cx_self_healing_enabled" ) // Path returns ~/.checkmarx/cx-onboarding.properties, or "" when the home directory is unknown. func Path() string { + return homeFile(fileName) +} + +// IDEPath returns ~/.checkmarx/cx-onboarding-ide.properties, or "" when the home directory is unknown. +func IDEPath() string { + return homeFile(ideFileName) +} + +func homeFile(name string) string { home, err := os.UserHomeDir() if err != nil || home == "" { return "" } - return filepath.Join(home, ".checkmarx", fileName) + return filepath.Join(home, ".checkmarx", name) } // Enabled reports whether the scanner is switched on in the user's config file. @@ -55,31 +75,88 @@ func enabledIn(path string, s Scanner) bool { // valueIn returns the last `key=value` for key in the file, or found=false when the file is missing, // unreadable, oversized or does not set the key. Same parsing rules as the plugins' readers. func valueIn(path, key string) (value string, found bool) { - if path == "" { + props, ok := readProps(path) + if !ok { return "", false } + value, found = props[key] + return value, found +} + +// readProps parses the file's `key=value` lines (last occurrence wins, # comments, BOM stripped). +// ok is false when the file is missing, unreadable or oversized. +func readProps(path string) (props map[string]string, ok bool) { + if path == "" { + return nil, false + } f, err := os.Open(path) if err != nil { - return "", false + return nil, false } defer func() { _ = f.Close() }() raw, err := io.ReadAll(io.LimitReader(f, maxBytes+1)) if err != nil || len(raw) > maxBytes { - return "", false + return nil, false } + props = map[string]string{} sc := bufio.NewScanner(strings.NewReader(strings.TrimPrefix(string(raw), utf8BOM))) for sc.Scan() { // last occurrence wins line := strings.TrimSpace(sc.Text()) if line == "" || strings.HasPrefix(line, "#") { continue } - k, v, ok := strings.Cut(line, "=") - if !ok || strings.TrimSpace(k) != key { + k, v, found := strings.Cut(line, "=") + if !found { continue } - value, found = v, true + props[strings.TrimSpace(k)] = v } - return value, found + return props, true +} + +// ideProps returns the VS Code state file's keys when the file is valid: it exists, is readable, is at +// most 8 KB, and its cx_schema_version is absent or 1. An invalid file returns ok=false. +func ideProps(path string) (props map[string]string, ok bool) { + props, ok = readProps(path) + if !ok { + return nil, false + } + if v, set := props[ideSchemaKey]; set && strings.TrimSpace(v) != ideSchemaVersion { + return nil, false + } + return props, true +} + +// SelfHealingEnabled reports whether Checkmarx Self-Healing is on in VS Code. It is OFF only when the +// VS Code state file is valid and cx_self_healing_enabled is a false-like value; a missing, unreadable +// or unknown-schema file, a missing key or any other value means ON. +func SelfHealingEnabled() bool { + return selfHealingIn(IDEPath()) +} + +func selfHealingIn(path string) bool { + props, ok := ideProps(path) + if !ok { + return true + } + v, set := props[ideSelfHealingKey] + return !set || !isFalse(v) +} + +// IDEEnabled is Enabled for events from VS Code: when the VS Code state file is valid its +// cx_*_scanner_enabled keys decide (a missing key means enabled); otherwise it falls back to the +// terminal's ~/.checkmarx/cx-onboarding.properties, exactly like Enabled. +func IDEEnabled(s Scanner) bool { + return ideEnabledIn(IDEPath(), Path(), s) +} + +func ideEnabledIn(idePath, cliPath string, s Scanner) bool { + props, ok := ideProps(idePath) + if !ok { + return enabledIn(cliPath, s) + } + v, set := props[string(s)] + return !set || !isFalse(v) } func isFalse(v string) bool { @@ -103,19 +180,45 @@ func Threshold() int { } func thresholdIn(path string) int { - value, found := valueIn(path, thresholdKey) - if !found { - return 1 - } + value, _ := valueIn(path, thresholdKey) + return thresholdRank(value) +} + +// thresholdRank is the rank of a cx_severity_threshold value; blank or invalid means low (1). +func thresholdRank(value string) int { if rank, ok := severityRank[strings.ToLower(strings.TrimSpace(value))]; ok { return rank } return 1 } +// IDEThreshold is Threshold for events from VS Code. The VS Code extension writes cx_severity_threshold=low +// to the VS Code state file, so only that file's cx_severity_threshold counts; a missing file, key or invalid +// value is low (nothing filtered). The terminal's ~/.checkmarx/cx-onboarding.properties threshold never applies to VS Code. +func IDEThreshold() int { + return ideThresholdIn(IDEPath()) +} + +func ideThresholdIn(path string) int { + props, ok := ideProps(path) + if !ok { + return 1 + } + return thresholdRank(props[thresholdKey]) +} + // BelowThreshold reports whether a deny whose highest severity is `severity` should be let through // because it is under cx_severity_threshold. An unranked severity returns false (keep blocking). func BelowThreshold(severity string) bool { + return belowRank(severity, Threshold()) +} + +// IDEBelowThreshold is BelowThreshold for events from VS Code, against IDEThreshold. +func IDEBelowThreshold(severity string) bool { + return belowRank(severity, IDEThreshold()) +} + +func belowRank(severity string, threshold int) bool { rank, ok := severityRank[strings.ToLower(strings.TrimSpace(severity))] - return ok && rank < Threshold() + return ok && rank < threshold } diff --git a/internal/commands/agenthooks/scannerconfig/scannerconfig_test.go b/internal/commands/agenthooks/scannerconfig/scannerconfig_test.go index 3353059f9..78aecd9cf 100644 --- a/internal/commands/agenthooks/scannerconfig/scannerconfig_test.go +++ b/internal/commands/agenthooks/scannerconfig/scannerconfig_test.go @@ -136,3 +136,131 @@ func TestBelowThreshold(t *testing.T) { t.Error("blank threshold must filter nothing") } } + +func writeIDE(t *testing.T, body string) string { + t.Helper() + p := filepath.Join(t.TempDir(), ideFileName) + if err := os.WriteFile(p, []byte(body), 0o600); err != nil { + t.Fatal(err) + } + return p +} + +func TestSelfHealingIn(t *testing.T) { + cases := []struct { + name string + body string + want bool + }{ + {"key missing is on", "cx_schema_version=1\n", true}, + {"explicit true is on", "cx_self_healing_enabled=true\n", true}, + {"garbage is on", "cx_self_healing_enabled=flase\n", true}, + {"empty value is on", "cx_self_healing_enabled=\n", true}, + {"false is off", "cx_schema_version=1\ncx_self_healing_enabled=false\n", false}, + {"no schema key, off", "cx_self_healing_enabled=false\n", false}, + {"caps / spaces / CRLF / BOM, off", "\xef\xbb\xbfcx_schema_version= 1 \r\ncx_self_healing_enabled= Disabled \r\n", false}, + {"0 / no / off are off", "cx_self_healing_enabled=0\ncx_self_healing_enabled=no\ncx_self_healing_enabled=off\n", false}, + {"last occurrence wins", "cx_self_healing_enabled=false\ncx_self_healing_enabled=true\n", true}, + {"commented key ignored", "# cx_self_healing_enabled=false\n", true}, + {"unknown schema is on", "cx_schema_version=2\ncx_self_healing_enabled=false\n", true}, + {"blank schema is on", "cx_schema_version=\ncx_self_healing_enabled=false\n", true}, + {"oversized is on", strings.Repeat("# pad\n", 5000) + "cx_self_healing_enabled=false\n", true}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := selfHealingIn(writeIDE(t, tc.body)); got != tc.want { + t.Fatalf("selfHealingIn(%q) = %v, want %v", tc.body, got, tc.want) + } + }) + } + if !selfHealingIn(filepath.Join(t.TempDir(), "missing")) || !selfHealingIn("") { + t.Error("missing file / path must mean on") + } + if !selfHealingIn(t.TempDir()) { + t.Error("unreadable (directory) must mean on") + } +} + +func TestIDEEnabledIn(t *testing.T) { + cli := write(t, "cx_asca_scanner_enabled=false\n") // terminal: ASCA off, others on + cases := []struct { + name string + ide string // "" = no IDE file + s Scanner + want bool + }{ + {"no IDE file falls back to CLI (off)", "", ASCA, false}, + {"no IDE file falls back to CLI (on)", "", KICS, true}, + {"valid IDE file, key missing is on despite CLI off", "cx_schema_version=1\n", ASCA, true}, + {"valid IDE file, key off", "cx_kics_scanner_enabled=false\n", KICS, false}, + {"valid IDE file, key on", "cx_asca_scanner_enabled=true\n", ASCA, true}, + {"valid IDE file, garbage is on", "cx_sca_scanner_enabled=banana\n", SCA, true}, + {"valid IDE file, secrets off", "cx_secret_scanner_enabled=OFF\n", Secrets, false}, + {"unknown schema falls back to CLI", "cx_schema_version=9\ncx_asca_scanner_enabled=true\n", ASCA, false}, + {"oversized IDE file falls back to CLI", strings.Repeat("# pad\n", 5000), ASCA, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ide := filepath.Join(t.TempDir(), "missing") + if tc.ide != "" { + ide = writeIDE(t, tc.ide) + } + if got := ideEnabledIn(ide, cli, tc.s); got != tc.want { + t.Fatalf("ideEnabledIn(%s) = %v, want %v", tc.s, got, tc.want) + } + }) + } +} + +func TestIDEPathUsesHome(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) + if got := IDEPath(); got != filepath.Join(dir, ".checkmarx", "cx-onboarding-ide.properties") { + t.Errorf("unexpected path %q", got) + } + if !SelfHealingEnabled() || !IDEEnabled(ASCA) { + t.Error("no files under home must mean on") + } + _ = os.MkdirAll(filepath.Join(dir, ".checkmarx"), 0o755) + _ = os.WriteFile(IDEPath(), []byte("cx_self_healing_enabled=false\ncx_kics_scanner_enabled=false\n"), 0o600) + if SelfHealingEnabled() || IDEEnabled(KICS) || !IDEEnabled(ASCA) { + t.Error("SelfHealingEnabled / IDEEnabled should read the IDE file under the user's home") + } + if !Enabled(KICS) { + t.Error("Enabled (terminal) must never read the IDE file") + } +} + +func TestIDEThresholdIn(t *testing.T) { + cases := map[string]int{ + "cx_schema_version=1\n": 1, // VS Code writes no threshold: low + "cx_severity_threshold=high\n": 3, + "cx_schema_version=1\ncx_severity_threshold=\n": 1, // blank + "cx_severity_threshold=hihg\n": 1, // invalid + "cx_schema_version=2\ncx_severity_threshold=high\n": 1, // unknown schema: file ignored + } + for body, want := range cases { + if got := ideThresholdIn(writeIDE(t, body)); got != want { + t.Errorf("%q: got %d, want %d", body, got, want) + } + } + if ideThresholdIn(filepath.Join(t.TempDir(), "missing")) != 1 || ideThresholdIn("") != 1 { + t.Error("missing IDE file / path must mean low") + } +} + +func TestIDEBelowThresholdIgnoresTerminalThreshold(t *testing.T) { + dir := t.TempDir() + t.Setenv("HOME", dir) + t.Setenv("USERPROFILE", dir) + _ = os.MkdirAll(filepath.Join(dir, ".checkmarx"), 0o755) + _ = os.WriteFile(Path(), []byte("cx_severity_threshold=critical\n"), 0o600) + _ = os.WriteFile(IDEPath(), []byte("cx_schema_version=1\ncx_self_healing_enabled=true\n"), 0o600) + if !BelowThreshold("High") { + t.Error("terminal: a critical threshold must relax High") + } + if IDEBelowThreshold("Low") || IDEBelowThreshold("High") { + t.Error("VS Code without a threshold must block at every severity (low)") + } +} diff --git a/internal/commands/scan.go b/internal/commands/scan.go index 1b7424124..37931d163 100644 --- a/internal/commands/scan.go +++ b/internal/commands/scan.go @@ -1821,20 +1821,6 @@ func addDirFilesIgnoreFilter(zipWriter *zip.Writer, baseDir, parentDir string) e err = addDirFilesIgnoreFilter(zipWriter, newBase, newParent) } else { fileName := parentDir + file.Name() - relPath := filepath.ToSlash(baseDir + file.Name()) - - excluded := false - for _, pattern := range commonParams.BaseExcludedFiles { - if relPath == pattern || strings.HasSuffix(relPath, pattern) { - excluded = true - logger.PrintIfVerbose("Excluded: " + fileName) - break - } - } - if excluded { - continue - } - logger.PrintIfVerbose("Included: " + fileName) dat, _ := ioutil.ReadFile(fileName) diff --git a/internal/params/filters.go b/internal/params/filters.go index 7536621be..65b1aee46 100644 --- a/internal/params/filters.go +++ b/internal/params/filters.go @@ -203,11 +203,6 @@ var BaseExcludeFilters = []string{ "!node_modules", } -// BaseExcludedFiles defines the base set of files to exclude from ZIP archives during scans. -var BaseExcludedFiles = []string{ - ".git/config", -} - var KicsBaseFilters = []string{ ".tf", ".yaml",