Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 2 additions & 2 deletions cli-v2.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ func main() {
}
}

// Check if command is init/update/version/help - these don't require configuration
// Check if command is init/update/version/help/container-scan - these don't require configuration
if len(os.Args) > 1 {
cmdName := os.Args[1]
if cmdName == "init" || cmdName == "update" || cmdName == "version" || cmdName == "help" {
if cmdName == "init" || cmdName == "update" || cmdName == "version" || cmdName == "help" || cmdName == "container-scan" {
cmd.Execute()
return
}
Expand Down
155 changes: 155 additions & 0 deletions cmd/container_scan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package cmd

Check notice on line 1 in cmd/container_scan.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/container_scan.go#L1

should have a package comment

import (
"fmt"
"os"
"os/exec"

"codacy/cli-v2/utils/logger"

"github.com/fatih/color"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

// Flag variables for container-scan command
var (
severityFlag string
pkgTypesFlag string
ignoreUnfixedFlag bool
)

func init() {
containerScanCmd.Flags().StringVar(&severityFlag, "severity", "", "Comma-separated list of severities to scan for (default: HIGH,CRITICAL)")
containerScanCmd.Flags().StringVar(&pkgTypesFlag, "pkg-types", "", "Comma-separated list of package types to scan (default: os)")
containerScanCmd.Flags().BoolVar(&ignoreUnfixedFlag, "ignore-unfixed", true, "Ignore unfixed vulnerabilities")
rootCmd.AddCommand(containerScanCmd)
}

var containerScanCmd = &cobra.Command{
Use: "container-scan [FLAGS] <IMAGE_NAME>",
Short: "Scan container images for vulnerabilities using Trivy",
Long: `Scan container images for vulnerabilities using Trivy.

By default, scans for HIGH and CRITICAL vulnerabilities in OS packages,
ignoring unfixed issues. Use flags to override these defaults.

The --exit-code 1 flag is always applied (not user-configurable) to ensure
the command fails when vulnerabilities are found.`,
Example: ` # Default behavior (HIGH,CRITICAL severity, os packages only)
codacy-cli container-scan myapp:latest

# Scan only for CRITICAL vulnerabilities
codacy-cli container-scan --severity CRITICAL myapp:latest

# Scan all severities and package types
codacy-cli container-scan --severity LOW,MEDIUM,HIGH,CRITICAL --pkg-types os,library myapp:latest

# Include unfixed vulnerabilities
codacy-cli container-scan --ignore-unfixed=false myapp:latest`,
Args: cobra.ExactArgs(1),
Run: runContainerScan,
}

func runContainerScan(cmd *cobra.Command, args []string) {

Check warning on line 54 in cmd/container_scan.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/container_scan.go#L54

Method runContainerScan has 52 lines of code (limit is 50)

Check warning on line 54 in cmd/container_scan.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/container_scan.go#L54

parameter 'cmd' seems to be unused, consider removing or renaming it as _
imageName := args[0]

logger.Info("Starting container scan", logrus.Fields{
"image": imageName,
})

// Check if Trivy is installed
trivyPath, err := exec.LookPath("trivy")
if err != nil {
logger.Error("Trivy not found", logrus.Fields{
"error": err.Error(),
})
color.Red("❌ Error: Trivy is not installed or not found in PATH")
fmt.Println("Please install Trivy to use container scanning.")
fmt.Println("Visit: https://trivy.dev/latest/getting-started/installation/")
os.Exit(1)
}

logger.Info("Found Trivy", logrus.Fields{
"path": trivyPath,
})

// Build Trivy command arguments
trivyArgs := buildTrivyArgs(imageName)

trivyCmd := exec.Command(trivyPath, trivyArgs...)

Check failure on line 80 in cmd/container_scan.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/container_scan.go#L80

OS command injection is a critical vulnerability that can lead to a full system compromise as it may allow an adversary to pass in arbitrary commands or arguments to be executed.
trivyCmd.Stdout = os.Stdout
trivyCmd.Stderr = os.Stderr

logger.Info("Running Trivy container scan", logrus.Fields{
"command": trivyCmd.String(),
})

fmt.Printf("🔍 Scanning container image: %s\n\n", imageName)

err = trivyCmd.Run()
if err != nil {
// Check if the error is due to exit code 1 (vulnerabilities found)
if exitError, ok := err.(*exec.ExitError); ok {
exitCode := exitError.ExitCode()
logger.Warn("Container scan completed with vulnerabilities", logrus.Fields{
"image": imageName,
"exit_code": exitCode,
})
if exitCode == 1 {
fmt.Println()
color.Red("❌ Scanning failed: vulnerabilities found in the container image")
os.Exit(1)
}
}
Copy link

Copilot AI Jan 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error handling logic has a flaw. If exitError.ExitCode() returns a value other than 1 (e.g., 2 or higher), the code falls through without exiting, logging the same error twice and calling os.Exit(1) at line 111. This creates confusing duplicate error logs. The code should exit after handling any exit error, not just exit code 1, or add an else statement to prevent fall-through.

Copilot uses AI. Check for mistakes.

// Other errors
logger.Error("Failed to run Trivy", logrus.Fields{
"error": err.Error(),
})
color.Red("❌ Error: Failed to run Trivy: %v", err)
Copy link

Copilot AI Jan 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The error formatting is incorrect. color.Red does not support format specifiers like fmt.Printf. The error message will literally print "%v" instead of formatting the error value. Change this to use fmt.Sprintf to format the error first, or use a separate fmt.Printf call.

Suggested change
color.Red("❌ Error: Failed to run Trivy: %v", err)
color.Red(fmt.Sprintf("❌ Error: Failed to run Trivy: %v", err))

Copilot uses AI. Check for mistakes.
os.Exit(1)
}

logger.Info("Container scan completed successfully", logrus.Fields{
"image": imageName,
})

fmt.Println()
color.Green("✅ Success: No vulnerabilities found matching the specified criteria")
}

// buildTrivyArgs constructs the Trivy command arguments based on flags
func buildTrivyArgs(imageName string) []string {
args := []string{
"image",
"--scanners", "vuln",
}

// Apply --ignore-unfixed if enabled (default: true)
if ignoreUnfixedFlag {
args = append(args, "--ignore-unfixed")
}

// Apply --severity (use default if not specified)
severity := severityFlag
if severity == "" {
severity = "HIGH,CRITICAL"
}
args = append(args, "--severity", severity)

// Apply --pkg-types (use default if not specified)
pkgTypes := pkgTypesFlag
if pkgTypes == "" {
pkgTypes = "os"
}
args = append(args, "--pkg-types", pkgTypes)
Comment on lines +408 to +419
Copy link

Copilot AI Jan 20, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The severityFlag and pkgTypesFlag values are passed directly to Trivy without validation. While exec.Command properly separates arguments and prevents shell injection, malicious or malformed values could still cause unexpected Trivy behavior. Consider adding validation to ensure these flags contain only expected characters (e.g., alphanumeric, commas for severity levels).

Copilot uses AI. Check for mistakes.

// Always apply --exit-code 1 (not user-configurable)
args = append(args, "--exit-code", "1")

// Add the image name as the last argument
args = append(args, imageName)

return args
}
Comment on lines +2 to +428
Copy link

Copilot AI Jan 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new command lacks test coverage. Similar commands in this repository have corresponding test files (e.g., analyze_test.go, config_test.go, init_test.go, upload_test.go). Consider adding a container_scan_test.go file to test the buildTrivyArgs function and the error handling logic in runContainerScan.

Copilot uses AI. Check for mistakes.
1 change: 1 addition & 0 deletions cmd/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func shouldSkipValidation(cmdName string) bool {
"reset", // config reset should work even with empty/invalid codacy.yaml
"codacy-cli", // root command when called without subcommands
"update",
"container-scan", // container scanning doesn't need codacy.yaml
}

for _, skipCmd := range skipCommands {
Expand Down
Loading