Skip to content
Closed
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
6 changes: 6 additions & 0 deletions internal/tool/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ func runCommand(cmd *exec.Cmd) (*string, *string, error) {
var stderr bytes.Buffer
cmd.Stderr = &stderr
cmdOutput, err := cmd.Output()
// Opengrep exits 2 when some files had errors but still prints the full JSON report,
// whose errors are reported as file errors, so its results are kept
var exitErr *exec.ExitError
if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 && json.Valid(cmdOutput) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 MEDIUM RISK

If Opengrep exits 2 with null or {} on stdout, the scan is treated as successful with no findings, and stderr is discarded. Consider requiring a report object with the expected results and errors fields before suppressing the exit error.

TIP React 👍 if this review is right, or reply with what's wrong and how it could be better to help improve the reviewer.

err = nil
}
if err != nil {
stderrString := stderr.String()
return nil, &stderrString, err
Expand Down
38 changes: 38 additions & 0 deletions internal/tool/command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,44 @@ func TestRunCommand_Error(t *testing.T) {
assert.Empty(t, stderr, "Expected empty stderr for a failed command")
}

func TestRunCommand_ExitCode2WithReport(t *testing.T) {
// Arrange
report := `{"results": [], "errors": [{"level": "error", "message": "Out of memory"}]}`
mockCmd := exec.Command("sh", "-c", "echo '"+report+"'; echo 'Scan Status' >&2; exit 2")

// Act
stdout, stderr, err := runCommand(mockCmd)

// Assert
assert.NoError(t, err)
assert.Nil(t, stderr)
assert.Equal(t, report+"\n", *stdout)
}

func TestRunCommand_ExitCode2WithoutReport(t *testing.T) {
// Arrange
mockCmd := exec.Command("sh", "-c", "echo 'not a report'; exit 2")

// Act
stdout, _, err := runCommand(mockCmd)

// Assert
assert.Error(t, err)
assert.Nil(t, stdout)
}

func TestRunCommand_OtherExitCodeWithReport(t *testing.T) {
// Arrange
mockCmd := exec.Command("sh", "-c", `echo '{"results": [], "errors": []}'; exit 7`)

// Act
stdout, _, err := runCommand(mockCmd)

// Assert
assert.Error(t, err)
assert.Nil(t, stdout)
}

func TestParseCommandOutput(t *testing.T) {
// Arrange
mockPatternDescriptions := []codacy.PatternDescription{
Expand Down