-
Notifications
You must be signed in to change notification settings - Fork 10
Feature/container scan #194
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
c8c5182
add container-scan command to trivy scan containers
franciscoovazevedo 25dcb9b
add tests and codacy suggestion improvments
franciscoovazevedo 9539333
allow list of images as argument
franciscoovazevedo 078a26a
codacy and copilot review changes applied
franciscoovazevedo d4d0d2c
add tests and codacy vulns fixed
franciscoovazevedo 027955b
not use PATH
andrzej-janczak 3635fa0
Refactor container scan command to accept a single image argument andβ¦
andrzej-janczak 7fe9d0f
Enhance container scan functionality by adding RunWithStderr method tβ¦
andrzej-janczak df0ffea
Update expected SARIF output for vulnerability rules in Trivy tests. β¦
andrzej-janczak e4b5e94
Refactor container scan command by removing severity and package typeβ¦
andrzej-janczak File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,269 @@ | ||
| // Package cmd implements the CLI commands for the Codacy CLI tool. | ||
| package cmd | ||
|
|
||
| import ( | ||
| "bytes" | ||
| "fmt" | ||
| "io" | ||
| "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._\-/:@]*$`) | ||
|
|
||
| // 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 | ||
| // RunWithStderr runs the command; if stderr is not nil, Trivy stderr is written to both os.Stderr and stderr. | ||
| RunWithStderr(name string, args []string, stderr io.Writer) 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 { | ||
| return r.RunWithStderr(name, args, nil) | ||
| } | ||
|
|
||
| // RunWithStderr runs the command; if stderr is not nil, command stderr is written to both os.Stderr and stderr. | ||
| func (r *ExecCommandRunner) RunWithStderr(name string, args []string, stderr io.Writer) 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...) | ||
| cmd.Stdout = os.Stdout | ||
| if stderr != nil { | ||
| cmd.Stderr = io.MultiWriter(os.Stderr, stderr) | ||
| } else { | ||
| 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 ( | ||
| ignoreUnfixedFlag bool | ||
| ) | ||
|
|
||
| func init() { | ||
| 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. | ||
|
|
||
| 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 | ||
|
|
||
| # 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") | ||
| } | ||
|
|
||
| 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.") | ||
| 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) | ||
| return 2 | ||
| } | ||
| logger.Info("Starting container scan", logrus.Fields{"image": imageName}) | ||
|
|
||
| trivyPath, err := getTrivyPath() | ||
| if err != nil { | ||
| handleTrivyNotFound(err) | ||
| return 2 | ||
| } | ||
|
|
||
| hasVulnerabilities := scanImage(imageName, trivyPath) | ||
| if hasVulnerabilities == -1 { | ||
| return 2 | ||
| } | ||
| return printScanSummary(hasVulnerabilities == 1) | ||
| } | ||
|
|
||
| // isScanFailure returns true if Trivy stderr indicates the scan failed (e.g. image not found, no runtime) | ||
| // rather than a successful scan that found vulnerabilities. Trivy uses exit code 1 for both cases. | ||
| func isScanFailure(stderr []byte) bool { | ||
| s := string(stderr) | ||
| return strings.Contains(s, "FATAL") || | ||
| strings.Contains(s, "run error") || | ||
| strings.Contains(s, "image scan error") || | ||
| strings.Contains(s, "unable to find the specified image") | ||
| } | ||
|
|
||
| // 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)}) | ||
|
|
||
| var stderrBuf bytes.Buffer | ||
| if err := commandRunner.RunWithStderr(trivyPath, args, &stderrBuf); err != nil { | ||
| code := getExitCode(err) | ||
| if code == 1 && isScanFailure(stderrBuf.Bytes()) { | ||
| logger.Error("Scan failed (e.g. image not found or no container runtime)", logrus.Fields{"image": imageName, "error": err.Error()}) | ||
| color.Red("β Scanning failed: unable to scan the container image (e.g. image not found or no container runtime)") | ||
| return -1 | ||
| } | ||
| if code == 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) | ||
| 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") | ||
| 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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. we should not allow users to define this flags |
||
| if ignoreUnfixedFlag { | ||
| args = append(args, "--ignore-unfixed") | ||
| } | ||
|
|
||
| // Fixed severity and package types (not user-configurable) | ||
| args = append(args, "--severity", "HIGH,CRITICAL", "--pkg-types", "os") | ||
|
|
||
| // 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 | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
executeContainerScanboth callshandleTrivyNotFound(err)(which invokesexitFunc(2)) and then returns2, whichrunContainerScanpasses again toexitFunc. In production this double-exit isnβt observable becauseos.Exitterminates the process immediately, but it mixes responsibilities for exiting between lower- and higher-level helpers and forces the tests to stubexitFuncaround both places. To simplify control flow and make the code easier to reason about and test, consider havingexecuteContainerScanonly return an exit code (for example by changinghandleTrivyNotFoundto just log and return a code) and letrunContainerScanbe the single place that callsexitFunc.