Skip to content
Open
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
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
264 changes: 264 additions & 0 deletions cmd/container_scan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,264 @@
// Package cmd implements the CLI commands for the Codacy CLI tool.
package cmd

import (
"fmt"
"os"
"os/exec"
"regexp"
"strings"

"codacy/cli-v2/config"
config_file "codacy/cli-v2/config-file"
"codacy/cli-v2/utils/logger"

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

// validImageNamePattern validates Docker image references
// Allows: registry/namespace/image:tag or image@sha256:digest
// Based on Docker image reference specification
var validImageNamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._\-/:@]*$`)
Comment on lines +22 to +23
Copy link

Copilot AI Jan 26, 2026

Choose a reason for hiding this comment

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

The regex pattern allows characters that may not be valid in Docker image references. Specifically, the underscore character is not typically allowed in Docker image repository names (though it's allowed in tags). The pattern ^[a-zA-Z0-9][a-zA-Z0-9._\-/:@]*$ would allow "my_invalid_repo:tag" which Docker would reject.

According to the Docker image specification, repository names should follow stricter rules. While the subsequent dangerous character checks provide some protection, having an inaccurate regex could cause confusing error messages where validation passes but Docker rejects the image name.

Suggested change
// Based on Docker image reference specification
var validImageNamePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._\-/:@]*$`)
// Based on Docker image reference specification (repository names are strict, tags more permissive)
var validImageNamePattern = regexp.MustCompile(`^(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?))*)(?::[0-9]+)?/)?[a-z0-9]+(?:(?:[._]|__|[-]*)[a-z0-9]+)*(?:/[a-z0-9]+(?:(?:[._]|__|[-]*)[a-z0-9]+)*)*(?::[\w][\w.-]{0,127})?(?:@[A-Za-z][A-Za-z0-9]*:[0-9a-fA-F]{32,})?$`)

Copilot uses AI. Check for mistakes.

// exitFunc is a variable to allow mocking os.Exit in tests
var exitFunc = os.Exit

// CommandRunner interface for running external commands (allows mocking in tests)
type CommandRunner interface {
Run(name string, args []string) error
}

// ExecCommandRunner runs commands using exec.Command
type ExecCommandRunner struct{}

// Run executes a command and returns its exit error
func (r *ExecCommandRunner) Run(name string, args []string) error {
// #nosec G204 -- name comes from config (codacy-installed Trivy path),
// and args are validated by validateImageName() which checks for shell metacharacters.
// exec.Command passes arguments directly without shell interpretation.
cmd := exec.Command(name, args...)

Check failure on line 41 in cmd/container_scan.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/container_scan.go#L41

Detected non-static command inside Command.

Check failure on line 41 in cmd/container_scan.go

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

cmd/container_scan.go#L41

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.

Choose a reason for hiding this comment

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

Choose a reason for hiding this comment

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

cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}

// commandRunner is the default command runner, can be replaced in tests
var commandRunner CommandRunner = &ExecCommandRunner{}

// ExitCoder interface for errors that have an exit code
type ExitCoder interface {
ExitCode() int
}

// getExitCode returns the exit code from an error if it implements ExitCoder
func getExitCode(err error) int {
if exitErr, ok := err.(ExitCoder); ok {
return exitErr.ExitCode()
}
return -1
}

// 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 <IMAGE_NAME>",
Short: "Scan a container image for vulnerabilities using Trivy",
Long: `Scan a container image 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: ` # Scan an image
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,
}

// validateImageName checks if the image name is a valid Docker image reference
// and doesn't contain shell metacharacters that could be used for command injection
func validateImageName(imageName string) error {
if imageName == "" {
return fmt.Errorf("image name cannot be empty")
}

// Check for maximum length (Docker has a practical limit)
if len(imageName) > 256 {
return fmt.Errorf("image name is too long (max 256 characters)")
}

// Check for dangerous shell metacharacters first for specific error messages
dangerousChars := []string{";", "&", "|", "$", "`", "(", ")", "{", "}", "<", ">", "!", "\\", "\n", "\r", "'", "\""}
for _, char := range dangerousChars {
if strings.Contains(imageName, char) {
return fmt.Errorf("invalid image name: contains disallowed character '%s'", char)
}
}

// Validate against allowed pattern for any other invalid characters
if !validImageNamePattern.MatchString(imageName) {
return fmt.Errorf("invalid image name format: contains disallowed characters")
}
Comment on lines +123 to +125
Copy link

Copilot AI Jan 26, 2026

Choose a reason for hiding this comment

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

The validation logic at line 127 is unreachable. After checking for dangerous characters in the loop (lines 119-124), if the imageName contains any of them, the function returns an error. Therefore, the validImageNamePattern check on line 127 will never execute for strings containing those characters.

This means the regex check only catches characters that aren't in the dangerousChars list. Consider either removing the redundant check or restructuring to validate with the regex first, then provide more specific error messages for dangerous characters.

Copilot uses AI. Check for mistakes.

return nil
}

// getTrivyPathResolver is set by tests to mock Trivy path resolution; when nil, real config/install logic is used
var getTrivyPathResolver func() (string, error)

// getTrivyPath returns the path to the Trivy binary (codacy-installed, installed on demand if needed) and an error if not found
func getTrivyPath() (string, error) {
if getTrivyPathResolver != nil {
return getTrivyPathResolver()
}
if err := config.Config.CreateCodacyDirs(); err != nil {
return "", fmt.Errorf("failed to create codacy directories: %w", err)
}
_ = config_file.ReadConfigFile(config.Config.ProjectConfigFile())
tool := config.Config.Tools()["trivy"]
if tool == nil || !config.Config.IsToolInstalled("trivy", tool) {
if err := config.InstallTool("trivy", tool, ""); err != nil {
return "", fmt.Errorf("failed to install Trivy: %w", err)
}
tool = config.Config.Tools()["trivy"]
}
if tool == nil {
return "", fmt.Errorf("trivy not in config after install")
}
trivyPath, ok := tool.Binaries["trivy"]
if !ok || trivyPath == "" {
return "", fmt.Errorf("trivy binary path not found")
}
logger.Info("Found Trivy", logrus.Fields{"path": trivyPath})
return trivyPath, nil
}

// handleTrivyNotFound prints error message and exits with code 2
func handleTrivyNotFound(err error) {
logger.Error("Trivy not found", logrus.Fields{"error": err.Error()})
color.Red("❌ Error: Trivy could not be installed or found")
fmt.Println("Run 'codacy-cli init' if you have no project yet, then try container-scan again so Trivy can be installed automatically.")
fmt.Println("exit-code 2")
exitFunc(2)
}

func runContainerScan(_ *cobra.Command, args []string) {
exitCode := executeContainerScan(args[0])
exitFunc(exitCode)
}

// executeContainerScan performs the container scan and returns an exit code
// Exit codes: 0 = success, 1 = vulnerabilities found, 2 = error
func executeContainerScan(imageName string) int {
if err := validateImageName(imageName); err != nil {
logger.Error("Invalid image name", logrus.Fields{"image": imageName, "error": err.Error()})
color.Red("❌ Error: %v", err)
fmt.Println("exit-code 2")
return 2
}
logger.Info("Starting container scan", logrus.Fields{"image": imageName})

trivyPath, err := getTrivyPath()
if err != nil {
handleTrivyNotFound(err)
return 2
Comment on lines +185 to +188
Copy link

Copilot AI Jan 26, 2026

Choose a reason for hiding this comment

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

The function signature of handleTrivyNotFound doesn't return a value, but in executeContainerScan at line 169, it's called and then explicitly returns 2. This is confusing because handleTrivyNotFound already calls exitFunc(2) which terminates the program in production.

The return 2 statement at line 170 only executes in tests where exitFunc is mocked. This creates a code smell where the control flow depends on whether exitFunc is mocked or not. Consider removing the exitFunc call from handleTrivyNotFound and having it return an int instead, letting the caller decide whether to exit.

Copilot uses AI. Check for mistakes.
}

hasVulnerabilities := scanImage(imageName, trivyPath)
if hasVulnerabilities == -1 {
return 2
}
return printScanSummary(hasVulnerabilities == 1)
}

// scanImage scans the image and returns: 0=no vulns, 1=vulns found, -1=error
func scanImage(imageName, trivyPath string) int {
fmt.Printf("🔍 Scanning container image: %s\n\n", imageName)
args := buildTrivyArgs(imageName)
logger.Info("Running Trivy container scan", logrus.Fields{"command": fmt.Sprintf("%s %v", trivyPath, args)})

if err := commandRunner.Run(trivyPath, args); err != nil {
if getExitCode(err) == 1 {
logger.Warn("Vulnerabilities found in image", logrus.Fields{"image": imageName})
return 1
}
logger.Error("Failed to run Trivy", logrus.Fields{"error": err.Error(), "image": imageName})
color.Red("❌ Error: Failed to run Trivy for %s: %v", imageName, err)
fmt.Println("exit-code 2")
return -1
}
logger.Info("No vulnerabilities found in image", logrus.Fields{"image": imageName})
return 0
}

func printScanSummary(hasVulnerabilities bool) int {
fmt.Println()
if hasVulnerabilities {
logger.Warn("Container scan completed with vulnerabilities", logrus.Fields{})
color.Red("❌ Scanning failed: vulnerabilities found in the container image")
fmt.Println("exit-code 1")
return 1
}
logger.Info("Container scan completed successfully", logrus.Fields{})
color.Green("✅ Success: No vulnerabilities found matching the specified criteria")
return 0
}

// 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)

// 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
}
Loading
Loading