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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .trivyignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,11 @@ CVE-2026-84243
# Reason: Fixed in Go 1.26.11 / 1.27.4.
# Status: Temporary ignore - remove once go.mod / CI toolchain is bumped to Go >= 1.26.11
CVE-2026-97054

# CVE-2026-128085: OpenTelemetry-Go denial of service via attribute truncation bypass
# Severity: MEDIUM
# Component: go.opentelemetry.io/otel/trace v1.45.0 (indirect dependency)
# Current Version: v1.45.0 (fixed in 1.47.0)
# Reason: Indirect dependency; not yet bumped in go.mod.
# Status: Temporary ignore - remove once go.opentelemetry.io/otel modules are bumped to >= 1.47.0
CVE-2026-128085
2 changes: 1 addition & 1 deletion internal/commands/chat-sast.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ func GetTenantConfigurationResponses(tenantWrapper wrappers.TenantConfigurationW
func GetTenantConfiguration(tenantConfigurationResponses *[]*wrappers.TenantConfigurationResponse, configKey string) (string, error) {
if tenantConfigurationResponses != nil {
for _, resp := range *tenantConfigurationResponses {
if resp.Key == configKey {
if resp != nil && resp.Key == configKey {
return resp.Value, nil
}
}
Expand Down
175 changes: 175 additions & 0 deletions internal/commands/file_size_limit_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
//go:build !integration

package commands

import (
"bytes"
"log"
"os"
"path/filepath"
"strings"
"testing"

"github.com/checkmarx/ast-cli/internal/filtering"
commonParams "github.com/checkmarx/ast-cli/internal/params"
"github.com/checkmarx/ast-cli/internal/services/realtimeengine/ossrealtime"
"gotest.tools/assert"
)

const testSizeLimitBytes = 64

// withTestSizeLimit lowers the default filter size limit to testSizeLimitBytes for the duration of the test.
func withTestSizeLimit(t *testing.T) {
t.Helper()
previous := MaxDefaultFilterFileSizeBytes
MaxDefaultFilterFileSizeBytes = testSizeLimitBytes
t.Cleanup(func() { MaxDefaultFilterFileSizeBytes = previous })
}

// writeSizedFiles creates each file with the given number of bytes and returns the root with a trailing separator.
func writeSizedFiles(t *testing.T, files map[string]int) string {
t.Helper()
root := t.TempDir()
for rel, size := range files {
p := filepath.Join(root, filepath.FromSlash(rel))
assert.NilError(t, os.MkdirAll(filepath.Dir(p), 0o755))
assert.NilError(t, os.WriteFile(p, []byte(strings.Repeat("a", size)), 0o600))
}
return root + string(os.PathSeparator)
}

func compressWith(t *testing.T, root, userInclude string, skipDefaultFilter bool) []string {
t.Helper()
zipPath, err := compressFolder(root, "", userInclude, "", filtering.NopMatcher{}, skipDefaultFilter, false, false,
commonParams.DefaultIncludeFilters(true))
assert.NilError(t, err)
t.Cleanup(func() { _ = os.Remove(zipPath) })
data, err := os.ReadFile(zipPath)
assert.NilError(t, err)
return zipEntryNames(t, data)
}

func TestIsScaFile(t *testing.T) {
scaFiles := []string{
"pom.xml", "package.json", "package-lock.json", "npm-shrinkwrap.json", "yarn.lock", "pnpm-lock.yaml",
"go.mod", "go.sum", "build.gradle", "build.gradle.kts", "libs.versions.toml", "build.sbt",
"requirements.txt", "requirements-dev.txt", "dev-requirements.txt", "constraints.txt", "packages.txt",
"setup.py", "setup.cfg", "pyproject.toml", "poetry.lock", "App.csproj", "APP.CSPROJ", "packages.config",
"packages.lock.json", "Directory.Packages.props", "Directory.Build.props", "Gemfile", "Gemfile.lock",
"composer.json", "composer.lock", "Podfile", "Podfile.lock", "Lib.podspec", "Lib.podspec.json", "Cartfile", "Cartfile.private",
"Package.swift", "Package@swift-5.9.swift", "pubspec.yaml", "bower.json", "lib.jar", ".cxsca-results.json", "scan.cxsca.sig",
}
for _, name := range scaFiles {
assert.Assert(t, isScaFile(name), "expected an SCA file: %s", name)
}

otherFiles := []string{"Main.java", "app.js", "data.json", "config.yaml", "notes.txt", "Main.swift", "lib.dll", "deploy.sh", "app.war", "Pipfile"}
for _, name := range otherFiles {
assert.Assert(t, !isScaFile(name), "expected a non-SCA file: %s", name)
}
}

// Every manifest the OSS realtime scanner accepts must be treated as an SCA file.
func TestScaFilePatterns_CoverOssRealtimeManifests(t *testing.T) {
manifests := []string{
"pom.xml", "package.json", "bower.json", "Directory.Packages.props", "packages.config", "App.csproj", "go.mod",
"build.gradle", "build.gradle.kts", "libs.versions.toml", "build.sbt", "setup.cfg", "setup.py", "pyproject.toml",
"requirements.txt", "packages.txt", "constraints.txt", "Podfile", "Lib.podspec", "Lib.podspec.json", "Cartfile",
"Cartfile.private", "Gemfile", "composer.json", "pubspec.yaml", "Package.swift", "Package@swift-5.9.swift",
}
for _, name := range manifests {
assert.Assert(t, ossrealtime.IsSupportedManifestFile(name), "not an OSS realtime manifest: %s", name)
assert.Assert(t, isScaFile(name), "OSS realtime manifest not treated as an SCA file: %s", name)
}
}

// SCA patterns must come from existing code: the OSS realtime manifest list or the default include filter.
func TestScaFilePatterns_ComeFromExistingCode(t *testing.T) {
for _, pattern := range commonParams.ScaFilePatterns {
name := strings.ReplaceAll(pattern, "*", "x")
assert.Assert(t, ossrealtime.IsSupportedManifestFile(name) || filterMatched(commonParams.BaseIncludeFilters, name),
"SCA pattern is neither an OSS realtime manifest nor in the default include filter: %s", pattern)
}
}

func TestExceedsDefaultFilterSizeLimit(t *testing.T) {
withTestSizeLimit(t)
big := int64(testSizeLimitBytes + 1)

assert.Assert(t, exceedsDefaultFilterSizeLimit(true, "Main.java", big))
assert.Assert(t, !exceedsDefaultFilterSizeLimit(true, "Main.java", testSizeLimitBytes), "a file at the limit is kept")
assert.Assert(t, !exceedsDefaultFilterSizeLimit(true, "pom.xml", big), "SCA files are exempt")
assert.Assert(t, !exceedsDefaultFilterSizeLimit(false, "Main.java", big), "no limit with --skip-default-filter")
}

func TestCompressFolder_SkipsOversizedFilesExceptSca(t *testing.T) {
withTestSizeLimit(t)
big := testSizeLimitBytes + 1
root := writeSizedFiles(t, map[string]int{
"src/Main.java": big,
"src/App.java": testSizeLimitBytes,
"deploy.sh": big,
"pom.xml": big,
"package-lock.json": big,
"requirements-dev.txt": big,
"libs/dependency.jar": big,
"web/yarn.lock": big,
"custom.xyz": big,
"go.sum": big,
"ios/Package.resolved": big,
"dotnet/App.csproj": big,
"dotnet/data.json": big,
"dotnet/appsettings.cs": 1,
})

assert.DeepEqual(t, compressWith(t, root, "", false), []string{
"dotnet/App.csproj", "dotnet/appsettings.cs", "go.sum", "libs/dependency.jar",
"package-lock.json", "pom.xml", "requirements-dev.txt", "src/App.java", "web/yarn.lock",
})

// Files matched by --file-include are limited too, SCA files stay exempt.
entries := compressWith(t, root, "*.xyz,*.lock", false)
assert.Assert(t, !contains(entries, "custom.xyz"))
assert.Assert(t, !contains(entries, "src/Main.java"))
assert.Assert(t, contains(entries, "web/yarn.lock"))

// A small file matched by --file-include is kept.
small := writeSizedFiles(t, map[string]int{"custom.xyz": 1})
assert.Assert(t, contains(compressWith(t, small, "*.xyz", false), "custom.xyz"))

// --skip-default-filter turns the limit off.
entries = compressWith(t, root, "", true)
assert.Assert(t, contains(entries, "src/Main.java"))
assert.Assert(t, contains(entries, "dotnet/data.json"))
assert.Assert(t, contains(compressWith(t, root, "*.xyz", true), "custom.xyz"))
}

func TestCompressFolder_AllFilesOversizedAddsPlaceholder(t *testing.T) {
withTestSizeLimit(t)
root := writeSizedFiles(t, map[string]int{"Main.java": testSizeLimitBytes + 1})

logs := captureStdLog(t)

assert.DeepEqual(t, compressWith(t, root, "", false), []string{".container-scan"})
assert.Equal(t, strings.Count(logs.String(), "Excluded (larger than 100MB)"), 1)
assert.Assert(t, strings.Contains(logs.String(), "Main.java"))
}

func TestCompressFolder_OversizedFileLoggedOnceWhenOtherFilesIncluded(t *testing.T) {
withTestSizeLimit(t)
root := writeSizedFiles(t, map[string]int{"Big.java": testSizeLimitBytes + 1, "Small.java": 1})
logs := captureStdLog(t)

assert.DeepEqual(t, compressWith(t, root, "", false), []string{"Small.java"})
assert.Equal(t, strings.Count(logs.String(), "Excluded (larger than 100MB)"), 1)
assert.Assert(t, strings.Contains(logs.String(), "Big.java"))
}

// captureStdLog redirects the standard logger, which logger.Print writes to, for the duration of the test.
func captureStdLog(t *testing.T) *bytes.Buffer {
t.Helper()
var buf bytes.Buffer
log.SetOutput(&buf)
t.Cleanup(func() { log.SetOutput(os.Stderr) })
return &buf
}
97 changes: 97 additions & 0 deletions internal/commands/linguist_filters_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
//go:build !integration

package commands

import (
"archive/zip"
"bytes"
"os"
"path/filepath"
"sort"
"strings"
"testing"

"github.com/checkmarx/ast-cli/internal/filtering"
commonParams "github.com/checkmarx/ast-cli/internal/params"
"gotest.tools/assert"
)

func TestFilterMatchedMatchesEveryBaseIncludeFilter(t *testing.T) {
for _, f := range commonParams.BaseIncludeFilters {
name := strings.NewReplacer("*", "x", "?", "y").Replace(f)
assert.Assert(t, filterMatched(commonParams.BaseIncludeFilters, name), "file %q should match filter %q", name, f)
assert.Assert(t, filterMatched(commonParams.BaseIncludeFilters, strings.ToUpper(name)),
"file %q should match filter %q case-insensitively", strings.ToUpper(name), f)
}
}

func TestFilterMatchedLinguistFiles(t *testing.T) {
included := []string{"deploy.sh", "build.PS1", "run.bat", "notebook.ipynb", "tmpl.j2", "Jenkinsfile", "Makefile", "GNUmakefile",
"Containerfile", "Rakefile", ".bash_history", "BUILD.bazel", "Deploy.SH", "JENKINSFILE"}
for _, name := range included {
assert.Assert(t, filterMatched(commonParams.BaseIncludeFilters, name), "%q should be included", name)
}
excluded := []string{"logo.png", "archive.zip", "makefile.bak", "jenkinsfile.txt", "data.bin", "sh"}
for _, name := range excluded {
assert.Assert(t, !filterMatched(commonParams.BaseIncludeFilters, name), "%q should not be included", name)
}
}

func TestFilterMatchedExcludeWinsOverLinguistInclude(t *testing.T) {
filters := append([]string{"!*.min.sh"}, commonParams.BaseIncludeFilters...)
assert.Assert(t, filterMatched(filters, "deploy.sh"))
assert.Assert(t, !filterMatched(filters, "deploy.min.sh"), "exclude filter must win over Linguist include")
assert.Assert(t, !filterMatched(commonParams.BaseExcludeFilters, ".vscode"))
}

// writeLinguistTree builds a source tree mixing Linguist files, SAST files and files that must be skipped.
func writeLinguistTree(t *testing.T, files []string) string {
t.Helper()
root := t.TempDir()
for _, rel := range files {
p := filepath.Join(root, filepath.FromSlash(rel))
assert.NilError(t, os.MkdirAll(filepath.Dir(p), 0o755))
assert.NilError(t, os.WriteFile(p, []byte("content of "+rel), 0o600))
}
return root
}

func zipEntryNames(t *testing.T, data []byte) []string {
t.Helper()
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
assert.NilError(t, err)
names := make([]string, 0, len(zr.File))
for _, f := range zr.File {
names = append(names, f.Name)
}
sort.Strings(names)
return names
}

func TestAddDirFilesIncludesLinguistFiles(t *testing.T) {
root := writeLinguistTree(t, []string{
"deploy.sh", "Jenkinsfile", "Makefile", "build.ps1", "Main.java", "scripts/run.bat",
"logo.png", "data.bin", "node_modules/dep.sh", ".idea/config.sh",
})
var out bytes.Buffer
zw := zip.NewWriter(&out)

err := addDirFiles(zw, "", root+string(os.PathSeparator), commonParams.BaseExcludeFilters, commonParams.BaseIncludeFilters, true,
filtering.NopMatcher{}, false)
assert.NilError(t, err)
assert.NilError(t, zw.Close())

assert.DeepEqual(t, []string{"Jenkinsfile", "Main.java", "Makefile", "build.ps1", "deploy.sh", "scripts/run.bat"}, zipEntryNames(t, out.Bytes()))
}

func TestIsDirEmptyWithLinguistFiles(t *testing.T) {
onlyLinguist := writeLinguistTree(t, []string{"logo.png", "ci/deploy.sh"})
empty, err := isDirEmpty(onlyLinguist, commonParams.BaseExcludeFilters, commonParams.BaseIncludeFilters, true, filtering.NopMatcher{})
assert.NilError(t, err)
assert.Assert(t, !empty, "a Linguist-only file must count as scannable content")

onlyBinary := writeLinguistTree(t, []string{"logo.png", "data.bin", "node_modules/dep.sh"})
empty, err = isDirEmpty(onlyBinary, commonParams.BaseExcludeFilters, commonParams.BaseIncludeFilters, true, filtering.NopMatcher{})
assert.NilError(t, err)
assert.Assert(t, empty, "files outside the filters and excluded directories must not count")
}
96 changes: 96 additions & 0 deletions internal/commands/llm_settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
package commands

import (
"strings"

"github.com/checkmarx/ast-cli/internal/logger"
commonParams "github.com/checkmarx/ast-cli/internal/params"
"github.com/checkmarx/ast-cli/internal/wrappers"
)

const (
// allowAiUsageKey is the tenant setting that must be on before the LLM-based scanning settings are checked.
allowAiUsageKey = "scan.config.ai.allowAiUsage"
// sastExtendedAnalysisKey is the LLM-based scanning setting, available at tenant and project level.
sastExtendedAnalysisKey = "scan.config.sast.extendedAnalysis"
)

// resolveDefaultIncludeFilters returns the default include filter for the source zip. The Linguist patterns are
// added only when Allow AI Usage is on and LLM-based scanning is enabled, with the project setting overriding the
// tenant setting; any failure to read the tenant settings falls back to the SAST patterns so the scan runs as before.
func resolveDefaultIncludeFilters(
tenantWrapper wrappers.TenantConfigurationWrapper,
projectsWrapper wrappers.ProjectsWrapper,
projectID string,
) []string {
enabled := isLlmScanningEnabled(tenantWrapper, projectsWrapper, projectID)
if enabled {
logger.PrintIfVerbose("LLM-based scanning is enabled: adding Linguist patterns to the default include filter.")
} else {
logger.PrintIfVerbose("LLM-based scanning is disabled: using the default SAST include filter only.")
}
return commonParams.DefaultIncludeFilters(enabled)
}

// isLlmScanningEnabled reports whether LLM-based scanning is enabled for the scan.
func isLlmScanningEnabled(tenantWrapper wrappers.TenantConfigurationWrapper, projectsWrapper wrappers.ProjectsWrapper, projectID string) bool {
tenantConfig, err := GetTenantConfigurationResponses(tenantWrapper)
if err != nil {
logger.PrintfIfVerbose("Failed to read the tenant configuration, LLM-based scanning treated as disabled: %v", err)
return false
}
if !isTenantSettingTrue(tenantConfig, allowAiUsageKey) {
logger.PrintIfVerbose("Allow AI Usage is off at tenant level.")
return false
}
if projectID != "" {
if enabled, ok := projectLlmScanningSetting(projectsWrapper, projectID); ok {
logger.PrintfIfVerbose("LLM-based scanning is %s at project level.", enabledText(enabled))
return enabled
}
}
enabled := isTenantSettingTrue(tenantConfig, sastExtendedAnalysisKey)
logger.PrintfIfVerbose("LLM-based scanning is %s at tenant level.", enabledText(enabled))
return enabled
}

// projectLlmScanningSetting returns the project's LLM-based scanning setting; ok is false when the project does not
// set it or its settings cannot be read.
func projectLlmScanningSetting(projectsWrapper wrappers.ProjectsWrapper, projectID string) (enabled, ok bool) {
projectConfig, errorModel, err := projectsWrapper.GetConfiguration(projectID)
if err != nil || errorModel != nil {
logger.PrintfIfVerbose("Failed to read the project configuration, using the tenant setting: %v %v", err, errorModel)
return false, false
}
value := projectSettingsMap(projectConfig)[sastExtendedAnalysisKey]
if strings.TrimSpace(value) == "" {
return false, false
}
return isTrueValue(value), true
}

func enabledText(enabled bool) string {
if enabled {
return "enabled"
}
return "disabled"
}

// isTenantSettingTrue reports whether a tenant setting is on; a missing setting is off.
func isTenantSettingTrue(tenantConfig *[]*wrappers.TenantConfigurationResponse, key string) bool {
value, _ := GetTenantConfiguration(tenantConfig, key)
return isTrueValue(value)
}

// isTrueValue reports whether a setting value is "true", ignoring case and surrounding spaces.
func isTrueValue(value string) bool {
return strings.EqualFold(strings.TrimSpace(value), "true")
}

func projectSettingsMap(config []wrappers.ProjectConfiguration) map[string]string {
settings := make(map[string]string, len(config))
for _, c := range config {
settings[c.Key] = c.Value
}
return settings
}
Loading
Loading